text
stringlengths
81
112k
Set the params so that the next page is fetched. def set_next_page_params(self): """Set the params so that the next page is fetched.""" if self.items: index = self.get_last_item_index() self.params[self.mode] = self.get_next_page_param(self.items[index])
List the users you have blocked. :return: a list of :class:`~groupy.api.blocks.Block`'s :rtype: :class:`list` def list(self): """List the users you have blocked. :return: a list of :class:`~groupy.api.blocks.Block`'s :rtype: :class:`list` """ params = {'user': ...
Check if there is a block between you and the given user. :return: ``True`` if the given user has been blocked :rtype: bool def between(self, other_user_id): """Check if there is a block between you and the given user. :return: ``True`` if the given user has been blocked :rtyp...
Block the given user. :param str other_user_id: the ID of the user to block :return: the block created :rtype: :class:`~groupy.api.blocks.Block` def block(self, other_user_id): """Block the given user. :param str other_user_id: the ID of the user to block :return: the ...
Unblock the given user. :param str other_user_id: the ID of the user to unblock :return: ``True`` if successful :rtype: bool def unblock(self, other_user_id): """Unblock the given user. :param str other_user_id: the ID of the user to unblock :return: ``True`` if succes...
List a page of chats. :param int page: which page :param int per_page: how many chats per page :return: chats with other users :rtype: :class:`~groupy.pagers.ChatList` def list(self, page=1, per_page=10): """List a page of chats. :param int page: which page :pa...
Return a page of group messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``, or ``after_id``. :param str before_id: message ID for paging backwards :param str after_id: message ID for paging forwards :param...
Return a page of group messages created since a message. This is used to fetch the most recent messages after another. There may exist messages between the one given and the ones returned. Use :func:`list_after` to retrieve newer messages without skipping any. :param str message_id: th...
Return a page of group messages created after a message. This is used to page forwards through messages. :param str message_id: the ID of a message :param int limit: maximum number of messages per page :return: group messages :rtype: :class:`~groupy.pagers.MessageList` def lis...
Return all group messages created before a message. :param str message_id: the ID of a message :param int limit: maximum number of messages per page :return: group messages :rtype: generator def list_all_before(self, message_id, limit=None): """Return all group messages created...
Return all group messages created after a message. :param str message_id: the ID of a message :param int limit: maximum number of messages per page :return: group messages :rtype: generator def list_all_after(self, message_id, limit=None): """Return all group messages created a...
Create a new message in the group. :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :param str source_guid: a unique identifier for the message :return: the created message :rtype: :class:`~groupy.api.mes...
Return a page of direct messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``. :param str before_id: message ID for paging backwards :param str since_id: message ID for most recent messages since :return: di...
Return all direct messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``. :param str before_id: message ID for paging backwards :param str since_id: message ID for most recent messages since :return: direct m...
Add a user to the group. You must provide either the email, phone number, or user_id that uniquely identifies a user. :param str nickname: new name for the user in the group :param str email: email address of the user :param str phone_number: phone number of the user :p...
Add multiple users to the group at once. Each given user must be a dictionary containing a nickname and either an email, phone number, or user_id. :param args users: the users to add :return: a membership request :rtype: :class:`MembershipRequest` def add_multiple(self, *users...
Check for results of a membership request. :param str results_id: the ID of a membership request :return: successfully created memberships :rtype: :class:`list` :raises groupy.exceptions.ResultsNotReady: if the results are not ready :raises groupy.exceptions.ResultsExpired: if t...
Update your own membership. Note that this fails on former groups. :param str nickname: new nickname :return: updated membership :rtype: :class:`~groupy.api.memberships.Member` def update(self, nickname=None, **kwargs): """Update your own membership. Note that this fa...
Remove a member from the group. :param str membership_id: the ID of a member in this group :return: ``True`` if the member was successfully removed :rtype: bool def remove(self, membership_id): """Remove a member from the group. :param str membership_id: the ID of a member in ...
Post a direct message to the user. :param str text: the message content :param attachments: message attachments :param str source_guid: a client-side unique ID for the message :return: the message sent :rtype: :class:`~groupy.api.messages.DirectMessage` def post(self, text=None...
Add the member to another group. If a nickname is not provided the member's current nickname is used. :param str group_id: the group_id of a group :param str nickname: a new nickname :return: a membership request :rtype: :class:`MembershipRequest` def add_to_group(self, group_...
Check for and fetch the results if ready. def check_if_ready(self): """Check for and fetch the results if ready.""" try: results = self.manager.check(self.results_id) except exceptions.ResultsNotReady as e: self._is_ready = False self._not_ready_exception = e...
Return the requests that failed. :param results: the results of a membership request check :type results: :class:`list` :return: the failed requests :rtype: generator def get_failed_requests(self, results): """Return the requests that failed. :param results: the result...
Return the newly added members. :param results: the results of a membership request check :type results: :class:`list` :return: the successful requests, as :class:`~groupy.api.memberships.Members` :rtype: generator def get_new_members(self, results): """Return the newly added m...
Return ``True`` if the results are ready. If you pass ``check=False``, no attempt is made to check again for results. :param bool check: whether to query for the results :return: ``True`` if the results are ready :rtype: bool def is_ready(self, check=True): """Return `...
Return the results when they become ready. :param int timeout: the maximum time to wait for the results :param float interval: the number of seconds between checks :return: the membership request result :rtype: :class:`~groupy.api.memberships.MembershipResult.Results` def poll(self, ti...
Return the results now. :return: the membership request results :rtype: :class:`~groupy.api.memberships.MembershipResult.Results` :raises groupy.exceptions.ResultsNotReady: if the results are not ready :raises groupy.exceptions.ResultsExpired: if the results have expired def get(self):...
List groups by page. The API allows certain fields to be excluded from the results so that very large groups can be fetched without exceeding the maximum response size. At the time of this writing, only 'memberships' is supported. :param int page: page number :param int...
List all groups. Since the order of groups is determined by recent activity, this is the recommended way to obtain a list of all groups. See :func:`~groupy.api.groups.Groups.list` for details about ``omit``. :param int per_page: number of groups per page :param int omit: a comm...
List all former groups. :return: a list of groups :rtype: :class:`list` def list_former(self): """List all former groups. :return: a list of groups :rtype: :class:`list` """ url = utils.urljoin(self.url, 'former') response = self.session.get(url) ...
Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group` def get(self, id): """Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group` """ ...
Create a new group. Note that, although possible, there may be issues when not using an image URL from GroupMe's image service. :param str name: group name (140 characters maximum) :param str description: short description (255 characters maximum) :param str image_url: GroupMe ...
Update the details of a group. .. note:: There are significant bugs in this endpoint! 1. not providing ``name`` produces 400: "Topic can't be blank" 2. not providing ``office_mode`` produces 500: "sql: Scan error on column index 14: sql/driver: couldn't convert ...
Destroy a group. :param str id: a group ID :return: ``True`` if successful :rtype: bool def destroy(self, id): """Destroy a group. :param str id: a group ID :return: ``True`` if successful :rtype: bool """ path = '{}/destroy'.format(id) ...
Join a group using a share token. :param str group_id: the group_id of a group :param str share_token: the share token :return: the group :rtype: :class:`~groupy.api.groups.Group` def join(self, group_id, share_token): """Join a group using a share token. :param str gr...
Rejoin a former group. :param str group_id: the group_id of a group :return: the group :rtype: :class:`~groupy.api.groups.Group` def rejoin(self, group_id): """Rejoin a former group. :param str group_id: the group_id of a group :return: the group :rtype: :class...
Change the owner of a group. .. note:: you must be the owner to change owners :param str group_id: the group_id of a group :param str owner_id: the ID of the new owner :return: the result :rtype: :class:`~groupy.api.groups.ChangeOwnersResult` def change_owners(self, group_id, ...
Update the details of the group. :param str name: group name (140 characters maximum) :param str description: short description (255 characters maximum) :param str image_url: GroupMe image service URL :param bool office_mode: (undocumented) :param bool share: whether to generate...
Refresh the group from the server in place. def refresh_from_server(self): """Refresh the group from the server in place.""" group = self.manager.get(id=self.id) self.__init__(self.manager, **group.data)
Create a new bot in a particular group. :param str name: bot name :param str avatar_url: the URL of an image to use as an avatar :param str callback_url: a POST-back URL for each new message :param bool dm_notification: whether to POST-back for direct messages? :return: the new ...
Get your membership. Note that your membership may not exist. For example, you do not have a membership in a former group. Also, the group returned by the API when rejoining a former group does not contain your membership. You must call :func:`refresh_from_server` to update the list of ...
Update your own membership. Note that this fails on former groups. :param str nickname: new nickname :return: updated membership :rtype: :class:`~groupy.api.members.Member` def update_membership(self, nickname=None, **kwargs): """Update your own membership. Note that ...
Join a base url with a relative path. def urljoin(base, path=None): """Join a base url with a relative path.""" # /foo/bar + baz makes /foo/bar/baz instead of /foo/baz if path is None: url = base else: if not base.endswith('/'): base += '/' url = urllib.parse.urljoin...
Return the group_id and share_token in a group's share url. :param str share_url: the share url of a group def parse_share_url(share_url): """Return the group_id and share_token in a group's share url. :param str share_url: the share url of a group """ *__, group_id, share_token = share_url.rstri...
Return an RFC 3339 timestamp. :param datetime.datetime when: a datetime in UTC :return: RFC 3339 timestamp :rtype: str def get_rfc3339(when): """Return an RFC 3339 timestamp. :param datetime.datetime when: a datetime in UTC :return: RFC 3339 timestamp :rtype: str """ microseconds ...
Create a filter from keyword arguments. def make_filter(**tests): """Create a filter from keyword arguments.""" tests = [AttrTest(k, v) for k, v in tests.items()] return Filter(tests)
Find exactly one match in the list of objects. :param objects: objects to filter :type objects: :class:`list` :return: the one matching object :raises groupy.exceptions.NoMatchesError: if no objects match :raises groupy.exceptions.MultipleMatchesError: if multiple objects match ...
Return a list of bots. :return: all of your bots :rtype: :class:`list` def list(self): """Return a list of bots. :return: all of your bots :rtype: :class:`list` """ response = self.session.get(self.url) return [Bot(self, **bot) for bot in response.data]
Create a new bot in a particular group. :param str name: bot name :param str group_id: the group_id of a group :param str avatar_url: the URL of an image to use as an avatar :param str callback_url: a POST-back URL for each new message :param bool dm_notification: whether to POS...
Post a new message as a bot to its room. :param str bot_id: the ID of the bot :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :return: ``True`` if successful :rtype: bool def post(self, bot_id, text, at...
Destroy a bot. :param str bot_id: the ID of the bot to destroy :return: ``True`` if successful :rtype: bool def destroy(self, bot_id): """Destroy a bot. :param str bot_id: the ID of the bot to destroy :return: ``True`` if successful :rtype: bool """ ...
Post a message as the bot. :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :return: ``True`` if successful :rtype: bool def post(self, text, attachments=None): """Post a message as the bot. :pa...
Flatten a nested sequence. A sequence could be a nested list of lists or tuples or a combination of both :param is_leaf: Predicate. Predicate to determine whether an item in the iterable `xs` is a leaf node or not. :param xs: Iterable. Nested lists or tuples :return: list. def fl...
Calls the function f by flipping the first two positional arguments def flip(f): """ Calls the function f by flipping the first two positional arguments """ def wrapped(*args, **kwargs): return f(*flip_first_two(args), **kwargs) f_spec = make_func_curry_spec(f) return curry_b...
A persistent, stale-free memoization decorator. The positional and keyword arguments to the wrapped function must be hashable (i.e. Python's immutable built-in objects, not mutable containers). Also, notice that since objects which are instances of user-defined classes are hashable but all compare uneq...
Search for UD's definition ID and return list of UrbanDefinition objects. Keyword arguments: defid -- definition ID to search for (int or str) def defineID(defid): """Search for UD's definition ID and return list of UrbanDefinition objects. Keyword arguments: defid -- definition ID to search for ...
Check that a non-Python dependency is installed. def has_external_dependency(name): 'Check that a non-Python dependency is installed.' for directory in os.environ['PATH'].split(':'): if os.path.exists(os.path.join(directory, name)): return True return False
Tests VTK interface and mesh repair of Stanford Bunny Mesh def with_vtk(plot=True): """ Tests VTK interface and mesh repair of Stanford Bunny Mesh """ mesh = vtki.PolyData(bunny_scan) meshfix = pymeshfix.MeshFix(mesh) if plot: print('Plotting input mesh') meshfix.plot() meshfix.repa...
Loads triangular mesh from vertex and face numpy arrays. Both vertex and face arrays should be 2D arrays with each vertex containing XYZ data and each face containing three points. Parameters ---------- v : np.ndarray n x 3 vertex array. f : np.ndar...
Return the surface mesh def mesh(self): """Return the surface mesh""" triangles = np.empty((self.f.shape[0], 4)) triangles[:, -3:] = self.f triangles[:, 0] = 3 return vtki.PolyData(self.v, triangles, deep=False)
Plot the mesh. Parameters ---------- show_holes : bool, optional Shows boundaries. Default True def plot(self, show_holes=True): """ Plot the mesh. Parameters ---------- show_holes : bool, optional Shows boundaries. Default Tru...
Performs mesh repair using MeshFix's default repair process. Parameters ---------- verbose : bool, optional Enables or disables debug printing. Disabled by default. joincomp : bool, optional Attempts to join nearby open components. remove_small...
Writes a surface mesh to disk. Written file may be an ASCII or binary ply, stl, or vtk mesh file. Parameters ---------- filename : str Filename of mesh to be written. Filetype is inferred from the extension of the filename unless overridden with ...
Scrape a URL optionally with parameters. This is effectively a wrapper around urllib2.urlopen. def scrape(url, params=None, user_agent=None): ''' Scrape a URL optionally with parameters. This is effectively a wrapper around urllib2.urlopen. ''' headers = {} if user_agent: headers[...
converts pdf file to xml file def pdftoxml(pdfdata, options=""): """converts pdf file to xml file""" pdffout = tempfile.NamedTemporaryFile(suffix='.pdf') pdffout.write(pdfdata) pdffout.flush() xmlin = tempfile.NamedTemporaryFile(mode='r', suffix='.xml') tmpxml = xmlin.name # "temph.xml" c...
Execute an arbitrary SQL query given by query, returning any results as a list of OrderedDicts. A list of values can be supplied as an, additional argument, which will be substituted into question marks in the query. def execute(query, data=None): """ Execute an arbitrary SQL query given by query, ...
Perform a sql select statement with the given query (without 'select') and return any results as a list of OrderedDicts. def select(query, data=None): """ Perform a sql select statement with the given query (without 'select') and return any results as a list of OrderedDicts. """ connection = _S...
Save the given data to the table specified by `table_name` (which defaults to 'swdata'). The data must be a mapping or an iterable of mappings. Unique keys is a list of keys that exist for all rows and for which a unique index will be created. def save(unique_keys, data, table_name='swdata'): """ S...
Specify the table to work on. def _set_table(table_name): """ Specify the table to work on. """ _State.connection() _State.reflect_metadata() _State.table = sqlalchemy.Table(table_name, _State.metadata, extend_existing=True) if list(_State.table.columns....
Return the names of the tables currently in the database. def show_tables(): """ Return the names of the tables currently in the database. """ _State.connection() _State.reflect_metadata() metadata = _State.metadata response = select('name, sql from sqlite_master where type="table"') ...
Save a variable to the table specified by _State.vars_table_name. Key is the name of the variable, and value is the value. def save_var(name, value): """ Save a variable to the table specified by _State.vars_table_name. Key is the name of the variable, and value is the value. """ connection = _...
Returns the variable with the provided key from the table specified by _State.vars_table_name. def get_var(name, default=None): """ Returns the variable with the provided key from the table specified by _State.vars_table_name. """ alchemytypes = {"text": lambda x: x.decode('utf-8'), ...
Create a new index of the columns in column_names, where column_names is a list of strings. If unique is True, it will be a unique index. def create_index(column_names, unique=False): """ Create a new index of the columns in column_names, where column_names is a list of strings. If unique is True, ...
Takes a row and checks to make sure it fits in the columns of the current table. If it does not fit, adds the required columns. def fit_row(connection, row, unique_keys): """ Takes a row and checks to make sure it fits in the columns of the current table. If it does not fit, adds the required columns. ...
Save the table currently waiting to be created. def create_table(unique_keys): """ Save the table currently waiting to be created. """ _State.new_transaction() _State.table.create(bind=_State.engine, checkfirst=True) if unique_keys != []: create_index(unique_keys, unique=True) _Stat...
Add a column to the current table. def add_column(connection, column): """ Add a column to the current table. """ stmt = alembic.ddl.base.AddColumn(_State.table.name, column) connection.execute(stmt) _State.reflect_metadata()
Drop the current table if it exists def drop(): """ Drop the current table if it exists """ # Ensure the connection is up _State.connection() _State.table.drop(checkfirst=True) _State.metadata.remove(_State.table) _State.table = None _State.new_transaction()
Extracts attributes and attaches them to element. def attach_attrs_table(key, value, fmt, meta): """Extracts attributes and attaches them to element.""" # We can't use attach_attrs_factory() because Table is a block-level element if key in ['Table']: assert len(value) == 5 caption = value[...
Processes the attributed tables. def process_tables(key, value, fmt, meta): """Processes the attributed tables.""" global has_unnumbered_tables # pylint: disable=global-statement # Process block-level Table elements if key == 'Table': # Inspect the table if len(value) == 5: # Unatt...
Filters the document AST. def main(): """Filters the document AST.""" # pylint: disable=global-statement global PANDOCVERSION global AttrTable # Get the output format and document fmt = args.fmt doc = json.loads(STDIN.read()) # Initialize pandocxnos # pylint: disable=too-many-fun...
Make a http request to clockwork, using the XML provided Sets sensible headers for the request. If there is a problem with the http connection a clockwork_exceptions.HttpException is raised def request(url, xml): """Make a http request to clockwork, using the XML provided Sets sensible he...
Check the balance fot this account. Returns a dictionary containing: account_type: The account type balance: The balance remaining on the account currency: The currency used for the account balance. Assume GBP in not set def get_balance(self): """Check the balance fo...
Send a SMS message, or an array of SMS messages def send(self, messages): """Send a SMS message, or an array of SMS messages""" tmpSms = SMS(to='', message='') if str(type(messages)) == str(type(tmpSms)): messages = [messages] xml_root = self.__init_xml('Message') ...
Init a etree element and pop a key in there def __init_xml(self, rootElementTag): """Init a etree element and pop a key in there""" xml_root = etree.Element(rootElementTag) key = etree.SubElement(xml_root, "Key") key.text = self.apikey return xml_root
Build a dictionary of SMS message elements def __build_sms_data(self, message): """Build a dictionary of SMS message elements""" attributes = {} attributes_to_translate = { 'to' : 'To', 'message' : 'Content', 'client_id' : 'ClientID', 'concat' :...
Helper to convert serialized pstats back to a list of raw entries. Converse operation of cProfile.Profile.snapshot_stats() def pstats2entries(data): """Helper to convert serialized pstats back to a list of raw entries. Converse operation of cProfile.Profile.snapshot_stats() """ # Each entry's key...
Return whether or not a given executable is installed on the machine. def is_installed(prog): """Return whether or not a given executable is installed on the machine.""" with open(os.devnull, 'w') as devnull: try: if os.name == 'nt': retcode = subprocess.call(['where', prog]...
Execute the converter using parameters provided on the command line def main(): """Execute the converter using parameters provided on the command line""" parser = argparse.ArgumentParser() parser.add_argument('-o', '--outfile', metavar='output_file_path', help="Save calltree stats ...
convert `profiling_data` to calltree format and dump it to `outputfile` `profiling_data` can either be: - a pstats.Stats instance - the filename of a pstats.Stats dump - the result of a call to cProfile.Profile.getstats() `outputfile` can either be: - a file() instance open in ...
Write the converted entries to out_file def output(self, out_file): """Write the converted entries to out_file""" self.out_file = out_file out_file.write('event: ns : Nanoseconds\n') out_file.write('events: ns\n') self._output_summary() for entry in sorted(self.entries, ...
Launch kcachegrind on the converted entries. One of the executables listed in KCACHEGRIND_EXECUTABLES must be present in the system path. def visualize(self): """Launch kcachegrind on the converted entries. One of the executables listed in KCACHEGRIND_EXECUTABLES must be prese...
Helper method that implements the logic to look up an application. def get_app(self, reference_app=None): """Helper method that implements the logic to look up an application.""" if reference_app is not None: return reference_app if self.app is not None: return self.ap...
Initializes the Flask-Bouncer extension for the specified application. :param app: The application. def init_app(self, app, **kwargs): """ Initializes the Flask-Bouncer extension for the specified application. :param app: The application. """ self.app = app self._init...
checks that an authorization call has been made during the request def check_authorization(self, response): """checks that an authorization call has been made during the request""" if not hasattr(request, '_authorized'): raise Unauthorized elif not request._authorized: r...
if you are using flask classy are using the standard index,new,put,post, etc ... type routes, we will automatically check the permissions for you def check_implicit_rules(self): """ if you are using flask classy are using the standard index,new,put,post, etc ... type routes, we will aut...
Rotates the given texture by a given angle. Args: texture (texture): the texture to rotate rotation (float): the angle of rotation in degrees x_offset (float): the x component of the center of rotation (optional) y_offset (float): the y component of the center of rotation (optional)...
Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture. def fit_texture(layer): """Fits a layer into a texture by scaling each axis to (0, 1). Doe...
Check that the solution is valid: every path is visited exactly once. def check_valid_solution(solution, graph): """Check that the solution is valid: every path is visited exactly once.""" expected = Counter( i for (i, _) in graph.iter_starts_with_index() if i < graph.get_disjoint(i) ) ...
Converts a solution (a list of node indices) into a list of paths suitable for rendering. def get_route_from_solution(solution, graph): """Converts a solution (a list of node indices) into a list of paths suitable for rendering.""" # As a guard against comparing invalid "solutions", # ensure that ...
Given a turtle program, creates a generator of turtle positions. The state of the turtle consists of its position and angle. The turtle starts at the position ``(0, 0)`` facing up. Each character in the turtle program is processed in order and causes an update to the state. The position component o...