INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return True if the results are ready.
def is_ready(self, check=True): """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 "...
Return the results when they become ready.
def poll(self, timeout=30, interval=2): """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.membe...
Return the results now.
def get(self): """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 ha...
List groups by page.
def list(self, page=1, per_page=10, omit=None): """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 supporte...
List all groups.
def list_all(self, per_page=10, omit=None): """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: nu...
List all former groups.
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) return [Group(self, **group) for group in response.data]
Get a single group by ID.
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` """ url = utils.urljoin(self.url, id) response = self.session.get(url) return Group(self, **response.data)
Create a new group.
def create(self, name, description=None, image_url=None, share=None, **kwargs): """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 des...
Update the details of a group.
def update(self, id, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs): """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" ...
Destroy a group.
def destroy(self, id): """Destroy a group. :param str id: a group ID :return: ``True`` if successful :rtype: bool """ path = '{}/destroy'.format(id) url = utils.urljoin(self.url, path) response = self.session.post(url) return response.ok
Join a group using a share token.
def join(self, group_id, share_token): """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` """ path = '{}/join/{}'.format(group_id, ...
Rejoin a former 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:`~groupy.api.groups.Group` """ url = utils.urljoin(self.url, 'join') payload = {'group_id': group_id} response = self.sess...
Change the owner of a group.
def change_owners(self, group_id, owner_id): """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...
Update the details of the group.
def update(self, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs): """Update the details of the group. :param str name: group name (140 characters maximum) :param str description: short description (255 characters maximum) :param str im...
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.
def create_bot(self, name, avatar_url=None, callback_url=None, dm_notification=None, **kwargs): """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...
Get your membership.
def get_membership(self): """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:`refres...
Update your own membership.
def update_membership(self, nickname=None, **kwargs): """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` """ return self.memberships.upda...
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(base, str(path)) return url
Return the group_id and share_token in a group s share url.
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.rstrip('/').split('/') return group_id, share_token
Return an RFC 3339 timestamp.
def get_rfc3339(when): """Return an RFC 3339 timestamp. :param datetime.datetime when: a datetime in UTC :return: RFC 3339 timestamp :rtype: str """ microseconds = format(when.microsecond, '04d')[:4] rfc3339 = '%Y-%m-%dT%H:%M:%S.{}Z' return when.strftime(rfc3339.format(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.
def find(self, objects): """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.MultipleMatc...
Return a list of bots.
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.
def create(self, name, group_id, avatar_url=None, callback_url=None, dm_notification=None, **kwargs): """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 ...
Post a new message as a bot to its room.
def post(self, bot_id, text, attachments=None): """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 succe...
Destroy a bot.
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 """ url = utils.urljoin(self.url, 'destroy') payload = {'bot_id': bot_id} response = self.session.post(url, json=payl...
Post a message as the bot.
def post(self, text, attachments=None): """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 """ return self.manager....
Flatten a nested sequence. A sequence could be a nested list of lists or tuples or a combination of both
def flatten_until(is_leaf, xs): """ 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. Neste...
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_by_spec(f_spec, wrapped)
A persistent stale - free memoization decorator.
def cachier(stale_after=None, next_time=False, pickle_reload=True, mongetter=None): """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, noti...
Search for UD s definition ID and return list of UrbanDefinition objects.
def defineID(defid): """Search for UD's definition ID and return list of UrbanDefinition objects. Keyword arguments: defid -- definition ID to search for (int or str) """ json = _get_urban_json(UD_DEFID_URL + urlquote(str(defid))) return _parse_urban_json(json)
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.repair() if plot: print('Plotting repaired mesh') ...
Loads triangular mesh from vertex and face numpy arrays.
def load_arrays(self, v, f): """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 ...
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.
def plot(self, show_holes=True): """ Plot the mesh. Parameters ---------- show_holes : bool, optional Shows boundaries. Default True """ if show_holes: edges = self.mesh.extract_edges(boundary_edges=True, ...
Performs mesh repair using MeshFix s default repair process.
def repair(self, verbose=False, joincomp=False, remove_smallest_components=True): """Performs mesh repair using MeshFix's default repair process. Parameters ---------- verbose : bool, optional Enables or disables debug printing. Disabled by default. ...
Writes a surface mesh to disk.
def write(self, filename, binary=True): """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 exten...
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['User-Agent'] = user_agent data = params and six.moves.urllib.parse.urlencode(params) or None ...
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" cmd = 'pdftohtml -xml -nodrm -zo...
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, 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. """ connection = _State.connection() ...
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 = _State.connection() _State.new_transaction() if data is None: data = [] result = connection.execute('select...
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'): """ 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. ...
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.keys()) == []: _State.t...
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"') return {row['name']: row['sql'] for row in response}
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 = _State.connection() _State.reflect_metadata() vars_table = sqlalchemy.Table( _State.vars_table_name, _State.meta...
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'), "big_integer": lambda x: int(x), "date": 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, it will be a unique index. """ connection = _State.connection() _State.reflect_metadata() table_name = _State.table.name t...
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. """ new_columns = [] for column_name, column_value in list(row.items()): new_column = sqlalchemy.Column(column_na...
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) _State.table_pending = False _State.reflect_metada...
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[0] # caption, align, x, head, body # Set ...
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: # Unattributed, bail out has_...
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-function-args PANDOCVERSIO...
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 headers for the request. If there is a problem with the http connection a clockwork_exceptions.HttpException is raised """ r = _urllib.Request(url, xml) r.add_header('Content-Type'...
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 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""" xml_root ...
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') wrapper_id = 0 for m in messages: ...
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' : 'Concat', 'from_name': 'From', ...
Helper to convert serialized pstats back to a list of raw entries.
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 is a tuple of (filename, line number, function name) entries = {} allcallers = {} # first pass over stats to build ...
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], stdout=devnull) else: retcode = subproces...
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 to <outfile>") parser.add_argument('-i', '--infile', metavar='inp...
convert profiling_data to calltree format and dump it to outputfile
def convert(profiling_data, outputfile): """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...
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, key=_entry_sort_key): self._o...
Launch kcachegrind on the converted entries.
def visualize(self): """Launch kcachegrind on the converted entries. One of the executables listed in KCACHEGRIND_EXECUTABLES must be present in the system path. """ available_cmd = None for cmd in KCACHEGRIND_EXECUTABLES: if is_installed(cmd): ...
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.app ctx = stack.top if ctx is not None: ...
Initializes the Flask - Bouncer extension for the specified 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_extension() self.app.before_request(self.check_implicit_rules) if kwargs.get('ensure_author...
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: raise Unauthorized return response
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 automatically check the permissions for you """ if not self.request_is_managed_by_flask_classy(): return if self.method_is_ex...
Rotates the given texture by a given angle.
def rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5): """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) ...
Fits a layer into a texture by scaling each axis to ( 0 1 ).
def fit_texture(layer): """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. """ x, y = layer x = (x - np.nanmin(x)) / (np.nanmax(x) -...
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) ) actual = Counter( min(i, graph.get_disjoint(i)) for i 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 this solution is valid. assert check_valid_solution(solution, graph) return [graph.get...
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 of the state is yielded at...
def branching_turtle_generator(turtle_program, turn_amount=DEFAULT_TURN, initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1): """Given a turtle program, creates a generator of turtle positions. The state of the turtle consists of its position and angle. The turtle starts a...
Makes a texture from a turtle program.
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN, initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1): """Makes a texture from a turtle program. Args: turtle_program (str): a string representing the turtle program; see the docstring of `branching_turtle_ge...
Applies a given set of substitution rules to the given string or generator. For more background see: https:// en. wikipedia. org/ wiki/ L - system
def transform_sequence(sequence, transformations): """Applies a given set of substitution rules to the given string or generator. For more background see: https://en.wikipedia.org/wiki/L-system Args: sequence (str): a string or generator onto which transformations are applied transform...
Chains a transformation a given number of times.
def transform_multiple(sequence, transformations, iterations): """Chains a transformation a given number of times. Args: sequence (str): a string or generator onto which transformations are applied transformations (dict): a dictionary mapping each char to the string that is substitu...
Generates a texture by running transformations on a turtle program.
def l_system(axiom, transformations, iterations=1, angle=45, resolution=1): """Generates a texture by running transformations on a turtle program. First, the given transformations are applied to the axiom. This is repeated `iterations` times. Then, the output is run as a turtle program to get a texture...
Returns the path corresponding to the node i.
def get_path(self, i): """Returns the path corresponding to the node i.""" index = (i - 1) // 2 reverse = (i - 1) % 2 path = self.paths[index] if reverse: return path.reversed() else: return path
Returns the distance between the end of path i and the start of path j.
def cost(self, i, j): """Returns the distance between the end of path i and the start of path j.""" return dist(self.endpoints[i][1], self.endpoints[j][0])
Returns the starting coordinates of node i as a pair or the end coordinates iff end is True.
def get_coordinates(self, i, end=False): """Returns the starting coordinates of node i as a pair, or the end coordinates iff end is True.""" if end: endpoint = self.endpoints[i][1] else: endpoint = self.endpoints[i][0] return (endpoint.real, endpoint.imag)
Returns a generator over ( index start coordinate ) pairs excluding the origin.
def iter_starts_with_index(self): """Returns a generator over (index, start coordinate) pairs, excluding the origin.""" for i in range(1, len(self.endpoints)): yield i, self.get_coordinates(i)
Returns a generator over 2 - element lists of indexes which must be mutually exclusive in a solution ( i. e. pairs of nodes which represent the same path in opposite directions. )
def iter_disjunctions(self): """Returns a generator over 2-element lists of indexes which must be mutually exclusive in a solution (i.e. pairs of nodes which represent the same path in opposite directions.)""" for i in range(1, len(self.endpoints), 2): yield [i, self.get_disj...
Preview a plot in a jupyter notebook.
def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT): """Preview a plot in a jupyter notebook. Args: plot (list): the plot to display (list of layers) width (int): the width of the preview height (int): the height of the preview Returns: An object that render...
Calculates the size of the SVG viewBox to use.
def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN): """Calculates the size of the SVG viewBox to use. Args: layers (list): the layers in the image aspect_ratio (float): the height of the output divided by the width margin (float): minimum amount of buffer to ad...
Generates an SVG path from a given layer.
def _layer_to_path_gen(layer): """Generates an SVG path from a given layer. Args: layer (layer): the layer to convert Yields: str: the next component of the path """ draw = False for x, y in zip(*layer): if np.isnan(x) or np.isnan(y): draw = False el...
Converts a plot ( list of layers ) into an SVG document.
def plot_to_svg(plot, width, height, unit=''): """Converts a plot (list of layers) into an SVG document. Args: plot (list): list of layers that make up the plot width (float): the width of the resulting image height (float): the height of the resulting image unit (str): the unit...
Writes a plot SVG to a file.
def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT): """Writes a plot SVG to a file. Args: plot (list): a list of layers to plot filename (str): the name of the file to write width (float): the width of the output SVG heig...
Draws a layer on the given matplotlib axis.
def draw_layer(ax, layer): """Draws a layer on the given matplotlib axis. Args: ax (axis): the matplotlib axis to draw on layer (layer): the layers to plot """ ax.set_aspect('equal', 'datalim') ax.plot(*layer) ax.axis('off')
Returns values on a surface for points on a texture.
def map_texture_to_surface(texture, surface): """Returns values on a surface for points on a texture. Args: texture (texture): the texture to trace over the surface surface (surface): the surface to trace along Returns: an array of surface heights for each point in the text...
Creates a texture by adding z - values to an existing texture and projecting.
def project_texture(texture_xy, texture_z, angle=DEFAULT_ANGLE): """Creates a texture by adding z-values to an existing texture and projecting. When working with surfaces there are two ways to accomplish the same thing: 1. project the surface and map a texture to the projected surface 2. map a texture...
Returns the height of the surface when projected at the given angle.
def project_surface(surface, angle=DEFAULT_ANGLE): """Returns the height of the surface when projected at the given angle. Args: surface (surface): the surface to project angle (float): the angle at which to project the surface Returns: surface: A projected surface. """ z_c...
Maps a texture onto a surface then projects to 2D and returns a layer.
def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE): """Maps a texture onto a surface, then projects to 2D and returns a layer. Args: texture (texture): the texture to project surface (surface): the surface to project onto angle (float): the projection angle in degrees...
Removes parts of a projected surface that are not visible.
def _remove_hidden_parts(projected_surface): """Removes parts of a projected surface that are not visible. Args: projected_surface (surface): the surface to use Returns: surface: A projected surface. """ surface = np.copy(projected_surface) surface[~_make_occlusion_mask(project...
Projects a texture onto a surface with occluded areas removed.
def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE): """Projects a texture onto a surface with occluded areas removed. Args: texture (texture): the texture to map to the projected surface surface (surface): the surface to project angle (float): the angle to project at...
Makes a texture consisting of a given number of horizontal lines.
def make_lines_texture(num_lines=10, resolution=50): """Makes a texture consisting of a given number of horizontal lines. Args: num_lines (int): the number of lines to draw resolution (int): the number of midpoints on each line Returns: A texture. """ x, y = np.meshgrid( ...
Makes a texture consisting of a grid of vertical and horizontal lines.
def make_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50): """Makes a texture consisting of a grid of vertical and horizontal lines. Args: num_h_lines (int): the number of horizontal lines to draw num_v_lines (int): the number of vertical lines to draw resolution (int): the n...
Makes a texture consisting of a spiral from the origin.
def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000): """Makes a texture consisting of a spiral from the origin. Args: spirals (float): the number of rotations to make ccw (bool): make spirals counter-clockwise (default is clockwise) offset (float): if non-zero, ...