_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q18600
Logger.warning
train
def warning(self, msg, *args, **kwargs) -> Task: # type: ignore """ Log msg with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.warning("Houston, we have a bit of a problem", exc_info=1) """ ...
python
{ "resource": "" }
q18601
Logger.error
train
def error(self, msg, *args, **kwargs) -> Task: # type: ignore """ Log msg with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.error("Houston, we have a major problem", exc_info=1) """ retu...
python
{ "resource": "" }
q18602
Logger.critical
train
def critical(self, msg, *args, **kwargs) -> Task: # type: ignore """ Log msg with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.critical("Houston, we have a major disaster", exc_info=1) """ ...
python
{ "resource": "" }
q18603
Logger.exception
train
def exception( # type: ignore self, msg, *args, exc_info=True, **kwargs ) -> Task: """ Convenience method for logging an ERROR with exception information. """ return self.error(msg, *args, exc_info=exc_info, **kwargs)
python
{ "resource": "" }
q18604
validate_aggregation
train
def validate_aggregation(agg): """Validate an aggregation for use in Vega-Lite. Translate agg to one of the following supported named aggregations: ['mean', 'sum', 'median', 'min', 'max', 'count'] Parameters ---------- agg : string or callable A string Supported reductions are ['m...
python
{ "resource": "" }
q18605
andrews_curves
train
def andrews_curves( data, class_column, samples=200, alpha=None, width=450, height=300, **kwds ): """ Generates an Andrews curves visualization for visualising clusters of multivariate data. Andrews curves have the functional form: f(t) = x_1/sqrt(2) + x_2 sin(t) + x_3 cos(t) + x_4 ...
python
{ "resource": "" }
q18606
dict_hash
train
def dict_hash(dct): """Return a hash of the contents of a dictionary""" dct_s = json.dumps(dct, sort_keys=True) try: m = md5(dct_s) except TypeError: m = md5(dct_s.encode()) return m.hexdigest()
python
{ "resource": "" }
q18607
exec_then_eval
train
def exec_then_eval(code, namespace=None): """Exec a code block & return evaluation of the last line""" # TODO: make this less brittle. namespace = namespace or {} block = ast.parse(code, mode='exec') last = ast.Expression(block.body.pop().value) exec(compile(block, '<string>', mode='exec'), na...
python
{ "resource": "" }
q18608
import_obj
train
def import_obj(clsname, default_module=None): """ Import the object given by clsname. If default_module is specified, import from this module. """ if default_module is not None: if not clsname.startswith(default_module + '.'): clsname = '{0}.{1}'.format(default_module, clsname) ...
python
{ "resource": "" }
q18609
get_scheme_cartocss
train
def get_scheme_cartocss(column, scheme_info): """Get TurboCARTO CartoCSS based on input parameters""" if 'colors' in scheme_info: color_scheme = '({})'.format(','.join(scheme_info['colors'])) else: color_scheme = 'cartocolor({})'.format(scheme_info['name']) if not isinstance(scheme_info[...
python
{ "resource": "" }
q18610
custom
train
def custom(colors, bins=None, bin_method=BinMethod.quantiles): """Create a custom scheme. Args: colors (list of str): List of hex values for styling data bins (int, optional): Number of bins to style by. If not given, the number of colors will be used. bin_method (str, optiona...
python
{ "resource": "" }
q18611
scheme
train
def scheme(name, bins, bin_method='quantiles'): """Return a custom scheme based on CARTOColors. Args: name (str): Name of a CARTOColor. bins (int or iterable): If an `int`, the number of bins for classifying data. CARTOColors have 7 bins max for quantitative data, and 11 max ...
python
{ "resource": "" }
q18612
CartoContext._is_authenticated
train
def _is_authenticated(self): """Checks if credentials allow for authenticated carto access""" if not self.auth_api_client.is_valid_api_key(): raise CartoException( 'Cannot authenticate user `{}`. Check credentials.'.format( self.creds.username()))
python
{ "resource": "" }
q18613
CartoContext.read
train
def read(self, table_name, limit=None, decode_geom=False, shared_user=None, retry_times=3): """Read a table from CARTO into a pandas DataFrames. Args: table_name (str): Name of table in user's CARTO account. limit (int, optional): Read only `limit` lines from `ta...
python
{ "resource": "" }
q18614
CartoContext.tables
train
def tables(self): """List all tables in user's CARTO account Returns: :obj:`list` of :py:class:`Table <cartoframes.analysis.Table>` """ datasets = DatasetManager(self.auth_client).filter( show_table_size_and_row_count='false', show_table='false', ...
python
{ "resource": "" }
q18615
CartoContext.write
train
def write(self, df, table_name, temp_dir=CACHE_DIR, overwrite=False, lnglat=None, encode_geom=False, geom_col=None, **kwargs): """Write a DataFrame to a CARTO table. Examples: Write a pandas DataFrame to CARTO. .. code:: python cc.write(df, 'brook...
python
{ "resource": "" }
q18616
CartoContext._get_privacy
train
def _get_privacy(self, table_name): """gets current privacy of a table""" ds_manager = DatasetManager(self.auth_client) try: dataset = ds_manager.get(table_name) return dataset.privacy.lower() except NotFoundException: return None
python
{ "resource": "" }
q18617
CartoContext._update_privacy
train
def _update_privacy(self, table_name, privacy): """Updates the privacy of a dataset""" ds_manager = DatasetManager(self.auth_client) dataset = ds_manager.get(table_name) dataset.privacy = privacy dataset.save()
python
{ "resource": "" }
q18618
CartoContext.fetch
train
def fetch(self, query, decode_geom=False): """Pull the result from an arbitrary SELECT SQL query from a CARTO account into a pandas DataFrame. Args: query (str): SELECT query to run against CARTO user database. This data will then be converted into a pandas DataFrame. ...
python
{ "resource": "" }
q18619
CartoContext.query
train
def query(self, query, table_name=None, decode_geom=False, is_select=None): """Pull the result from an arbitrary SQL SELECT query from a CARTO account into a pandas DataFrame. This is the default behavior, when `is_select=True` Can also be used to perform database operations (creating/dropping ...
python
{ "resource": "" }
q18620
CartoContext._check_query
train
def _check_query(self, query, style_cols=None): """Checks if query from Layer or QueryLayer is valid""" try: self.sql_client.send( utils.minify_sql(( 'EXPLAIN', 'SELECT', ' {style_cols}{comma}', ...
python
{ "resource": "" }
q18621
CartoContext._get_bounds
train
def _get_bounds(self, layers): """Return the bounds of all data layers involved in a cartoframes map. Args: layers (list): List of cartoframes layers. See `cartoframes.layers` for all types. Returns: dict: Dictionary of northern, southern, eastern, and w...
python
{ "resource": "" }
q18622
vmap
train
def vmap(layers, context, size=None, basemap=BaseMaps.voyager, bounds=None, viewport=None, **kwargs): """CARTO VL-powered interactive map Args: layers (list of Layer-types): List of layers. One or more of :py:class:`Layer <cartoframes.cont...
python
{ "resource": "" }
q18623
_get_bounds_local
train
def _get_bounds_local(layers): """Aggregates bounding boxes of all local layers return: dict of bounding box of all bounds in layers """ if not layers: return {'west': None, 'south': None, 'east': None, 'north': None} bounds = layers[0].bounds for layer in layers[1:]: boun...
python
{ "resource": "" }
q18624
_combine_bounds
train
def _combine_bounds(bbox1, bbox2): """Takes two bounding boxes dicts and gives a new bbox that encompasses them both""" WORLD = {'west': -180, 'south': -85.1, 'east': 180, 'north': 85.1} ALL_KEYS = set(WORLD.keys()) def dict_all_nones(bbox_dict): """Returns True if all dict values are None"...
python
{ "resource": "" }
q18625
QueryLayer._compose_style
train
def _compose_style(self): """Appends `prop` with `style` to layer styling""" valid_styles = ( 'color', 'width', 'filter', 'strokeWidth', 'strokeColor', ) self.styling = '\n'.join( '{prop}: {style}'.format(prop=s, style=getattr(self, s)) for s in valid_...
python
{ "resource": "" }
q18626
QueryLayer._set_interactivity
train
def _set_interactivity(self, interactivity): """Adds interactivity syntax to the styling""" event_default = 'hover' if interactivity is None: return if isinstance(interactivity, (tuple, list)): self.interactivity = event_default interactive_cols = '\n'...
python
{ "resource": "" }
q18627
get_map_name
train
def get_map_name(layers, has_zoom): """Creates a map named based on supplied parameters""" version = '20170406' num_layers = len(non_basemap_layers(layers)) has_labels = len(layers) > 1 and layers[-1].is_basemap has_time = has_time_layer(layers) basemap_id = dict(light=0, dark=1, voyager=2)[laye...
python
{ "resource": "" }
q18628
get_map_template
train
def get_map_template(layers, has_zoom): """Creates a map template based on custom parameters supplied""" num_layers = len(non_basemap_layers(layers)) has_time = has_time_layer(layers) name = get_map_name(layers, has_zoom=has_zoom) # Add basemap layer layers_field = [{ 'type': 'http', ...
python
{ "resource": "" }
q18629
QueryLayer._parse_color
train
def _parse_color(self, color): """Setup the color scheme""" # If column was specified, force a scheme # It could be that there is a column named 'blue' for example if isinstance(color, dict): if 'column' not in color: raise ValueError("Color must include a 'co...
python
{ "resource": "" }
q18630
QueryLayer._parse_time
train
def _parse_time(self, time): """Parse time inputs""" if time is None: return None if isinstance(time, dict): if 'column' not in time: raise ValueError("`time` must include a 'column' key/value") time_column = time['column'] time_op...
python
{ "resource": "" }
q18631
QueryLayer._parse_size
train
def _parse_size(self, size, has_time=False): """Parse size inputs""" if has_time: size = size or 4 else: size = size or 10 if isinstance(size, str): size = {'column': size} if isinstance(size, dict): if 'column' not in size: ...
python
{ "resource": "" }
q18632
QueryLayer._validate_columns
train
def _validate_columns(self): """Validate the options in the styles""" geom_cols = {'the_geom', 'the_geom_webmercator', } col_overlap = set(self.style_cols) & geom_cols if col_overlap: raise ValueError('Style columns cannot be geometry ' 'columns. ...
python
{ "resource": "" }
q18633
QueryLayer._setup
train
def _setup(self, layers, layer_idx): """Setups layers once geometry types and data types are known, and when a map is requested to be rendered from zero or more data layers""" basemap = layers[0] # if color not specified, choose a default if self.time: # default time...
python
{ "resource": "" }
q18634
QueryLayer._choose_scheme
train
def _choose_scheme(self): """Choose color scheme""" if self.style_cols[self.color] in ('string', 'boolean', ): self.scheme = antique(10) elif self.style_cols[self.color] in ('number', ): self.scheme = mint(5) elif self.style_cols[self.color] in ('date', 'geometry'...
python
{ "resource": "" }
q18635
normalize_names
train
def normalize_names(column_names): """Given an arbitrary column name, translate to a SQL-normalized column name a la CARTO's Import API will translate to Examples * 'Field: 2' -> 'field_2' * '2 Items' -> '_2_items' * 'Unnamed: 0' -> 'unnamed_0', * '20...
python
{ "resource": "" }
q18636
cssify
train
def cssify(css_dict): """Function to get CartoCSS from Python dicts""" css = '' for key, value in dict_items(css_dict): css += '{key} {{ '.format(key=key) for field, field_value in dict_items(value): css += ' {field}: {field_value};'.format(field=field, ...
python
{ "resource": "" }
q18637
temp_ignore_warnings
train
def temp_ignore_warnings(func): """Temporarily ignores warnings like those emitted by the carto python sdk """ @wraps(func) def wrapper(*args, **kwargs): """wrapper around func to filter/reset warnings""" with catch_warnings(): filterwarnings('ignore') evaled_func...
python
{ "resource": "" }
q18638
get_columns
train
def get_columns(context, query): """Get list of cartoframes.columns.Column""" table_info = context.sql_client.send(query) if 'fields' in table_info: return Column.from_sql_api_fields(table_info['fields']) return None
python
{ "resource": "" }
q18639
get_column_names
train
def get_column_names(context, query): """Get column names and types from a query""" table_info = context.sql_client.send(query) if 'fields' in table_info: return table_info['fields'] return None
python
{ "resource": "" }
q18640
_encode_decode_decorator
train
def _encode_decode_decorator(func): """decorator for encoding and decoding geoms""" def wrapper(*args): """error catching""" try: processed_geom = func(*args) return processed_geom except ImportError as err: raise ImportError('The Python package `shape...
python
{ "resource": "" }
q18641
_decode_geom
train
def _decode_geom(ewkb): """Decode encoded wkb into a shapely geometry """ # it's already a shapely object if hasattr(ewkb, 'geom_type'): return ewkb from shapely import wkb from shapely import wkt if ewkb: try: return wkb.loads(ba.unhexlify(ewkb)) except ...
python
{ "resource": "" }
q18642
Dataset.exists
train
def exists(self): """Checks to see if table exists""" try: self.cc.sql_client.send( 'EXPLAIN SELECT * FROM "{table_name}"'.format( table_name=self.table_name), do_post=False) return True except CartoException as err: ...
python
{ "resource": "" }
q18643
Credentials.save
train
def save(self, config_loc=None): """Saves current user credentials to user directory. Args: config_loc (str, optional): Location where credentials are to be stored. If no argument is provided, it will be send to the default location. Example: ...
python
{ "resource": "" }
q18644
Credentials._retrieve
train
def _retrieve(self, config_file=None): """Retrives credentials from a file. Defaults to the user config directory""" with open(config_file or _DEFAULT_PATH, 'r') as f: creds = json.load(f) self._key = creds.get('key') self._base_url = creds.get('base_url') sel...
python
{ "resource": "" }
q18645
Credentials.delete
train
def delete(self, config_file=None): """Deletes the credentials file specified in `config_file`. If no file is specified, it deletes the default user credential file. Args: config_file (str): Path to configuration file. Defaults to delete the user default location if ...
python
{ "resource": "" }
q18646
Credentials.set
train
def set(self, key=None, username=None, base_url=None): """Update the credentials of a Credentials instance instead with new values. Args: key (str): API key of user account. Defaults to previous value if not specified. username (str): User name of account...
python
{ "resource": "" }
q18647
Credentials.base_url
train
def base_url(self, base_url=None): """Return or set `base_url`. Args: base_url (str, optional): If set, updates the `base_url`. Otherwise returns current `base_url`. Note: This does not update the `username` attribute. Separately update the u...
python
{ "resource": "" }
q18648
chat
train
def chat(room=None, stream=None, **kwargs): """Quick setup for a chatroom. :param str room: Roomname, if not given, a random sequence is generated and printed. :param MediaStream stream: The media stream to share, if not given a CameraStream will be created. :rtype: WebRTCRoom """ if room is N...
python
{ "resource": "" }
q18649
SceneGraph.add_child
train
def add_child(self, child): """Adds an object as a child in the scene graph.""" if not issubclass(child.__class__, SceneGraph): raise TypeError("child must have parent/child iteration implemented to be a node in a SceneGraph.") # if not hasattr(child, 'update'): # raise T...
python
{ "resource": "" }
q18650
ProjectionBase.copy
train
def copy(self): """Returns a copy of the projection matrix""" params = {} for key, val in self.__dict__.items(): if 'matrix' not in key: k = key[1:] if key[0] == '_' else key params[k] = val # params = {param: params[param] for param in params}...
python
{ "resource": "" }
q18651
PerspectiveProjection.match_aspect_to_viewport
train
def match_aspect_to_viewport(self): """Updates Camera.aspect to match the viewport's aspect ratio.""" viewport = self.viewport self.aspect = float(viewport.width) / viewport.height
python
{ "resource": "" }
q18652
Camera.to_pickle
train
def to_pickle(self, filename): """Save Camera to a pickle file, given a filename.""" with open(filename, 'wb') as f: pickle.dump(self, f)
python
{ "resource": "" }
q18653
Camera.from_pickle
train
def from_pickle(cls, filename): """Loads and Returns a Camera from a pickle file, given a filename.""" with open(filename, 'rb') as f: cam = pickle.load(f) projection = cam.projection.copy() return cls(projection=projection, position=cam.position.xyz, rotation=cam.rotation._...
python
{ "resource": "" }
q18654
CameraGroup.look_at
train
def look_at(self, x, y, z): """Converges the two cameras to look at the specific point""" for camera in self.cameras: camera.look_at(x, y, z)
python
{ "resource": "" }
q18655
FBO.bind
train
def bind(self): """Bind the FBO. Anything drawn afterward will be stored in the FBO's texture.""" # This is called simply to deal with anything that might be currently bound (for example, Pyglet objects), gl.glBindTexture(gl.GL_TEXTURE_2D, 0) # Store current viewport size for later ...
python
{ "resource": "" }
q18656
FBO.unbind
train
def unbind(self): """Unbind the FBO.""" # Unbind the FBO if self.texture.mipmap: with self.texture: self.texture.generate_mipmap() gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, 0) # Restore the old viewport size gl.glViewport(*self._old_view...
python
{ "resource": "" }
q18657
create_opengl_object
train
def create_opengl_object(gl_gen_function, n=1): """Returns int pointing to an OpenGL texture""" handle = gl.GLuint(1) gl_gen_function(n, byref(handle)) # Create n Empty Objects if n > 1: return [handle.value + el for el in range(n)] # Return list of handle values else: return handl...
python
{ "resource": "" }
q18658
vec
train
def vec(data, dtype=float): """ Makes GLfloat or GLuint vector containing float or uint args. By default, newtype is 'float', but can be set to 'int' to make uint list. """ gl_types = {float: gl.GLfloat, int: gl.GLuint} try: gl_dtype = gl_types[dtype] except K...
python
{ "resource": "" }
q18659
calculate_normals
train
def calculate_normals(vertices): """Return Nx3 normal array from Nx3 vertex array.""" verts = np.array(vertices, dtype=float) normals = np.zeros_like(verts) for start, end in pairwise(np.arange(0, verts.shape[0] + 1, 3)): vecs = np.vstack((verts[start + 1] - verts[start], verts[start + 2] - vert...
python
{ "resource": "" }
q18660
Scene.draw
train
def draw(self, clear=True): """Draw each visible mesh in the scene from the perspective of the scene's camera and lit by its light.""" if clear: self.clear() with self.gl_states, self.camera, self.light: for mesh in self.meshes: try: m...
python
{ "resource": "" }
q18661
Scene.draw360_to_texture
train
def draw360_to_texture(self, cubetexture, **kwargs): """ Draw each visible mesh in the scene from the perspective of the scene's camera and lit by its light, and applies it to each face of cubetexture, which should be currently bound to an FBO. """ assert self.camera.projection....
python
{ "resource": "" }
q18662
VAO.assign_vertex_attrib_location
train
def assign_vertex_attrib_location(self, vbo, location): """Load data into a vbo""" with vbo: if self.n_verts: assert vbo.data.shape[0] == self.n_verts else: self.n_verts = vbo.data.shape[0] # vbo.buffer_data() gl.glVertexAt...
python
{ "resource": "" }
q18663
Mesh.copy
train
def copy(self): """Returns a copy of the Mesh.""" return Mesh(arrays=deepcopy([arr.copy() for arr in [self.vertices, self.normals, self.texcoords]]), texture=self.textures, mean_center=deepcopy(self._mean_center), position=self.position.xyz, rotation=self.rotation.__class__(*self.rot...
python
{ "resource": "" }
q18664
Mesh.from_pickle
train
def from_pickle(cls, filename): """Loads and Returns a Mesh from a pickle file, given a filename.""" with open(filename, 'rb') as f: mesh = pickle.load(f).copy() return mesh
python
{ "resource": "" }
q18665
Mesh.reset_uniforms
train
def reset_uniforms(self): """ Resets the uniforms to the Mesh object to the ""global"" coordinate system""" self.uniforms['model_matrix'] = self.model_matrix_global.view() self.uniforms['normal_matrix'] = self.normal_matrix_global.view()
python
{ "resource": "" }
q18666
Mesh._fill_vao
train
def _fill_vao(self): """Put array location in VAO for shader in same order as arrays given to Mesh.""" with self.vao: self.vbos = [] for loc, verts in enumerate(self.arrays): vbo = VBO(verts) self.vbos.append(vbo) self.vao.assign_ve...
python
{ "resource": "" }
q18667
Mesh.draw
train
def draw(self): """ Draw the Mesh if it's visible, from the perspective of the camera and lit by the light. The function sends the uniforms""" if not self.vao: self.vao = VAO(indices=self.array_indices) self._fill_vao() if self.visible: if self.dynamic: ...
python
{ "resource": "" }
q18668
cross_product_matrix
train
def cross_product_matrix(vec): """Returns a 3x3 cross-product matrix from a 3-element vector.""" return np.array([[0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]])
python
{ "resource": "" }
q18669
Texture.max_texture_limit
train
def max_texture_limit(self): """The maximum number of textures available for this graphic card's fragment shader.""" max_unit_array = (gl.GLint * 1)() gl.glGetIntegerv(gl.GL_MAX_TEXTURE_IMAGE_UNITS, max_unit_array) return max_unit_array[0]
python
{ "resource": "" }
q18670
Texture._apply_filter_settings
train
def _apply_filter_settings(self): """Applies some hard-coded texture filtering settings.""" # TODO: Allow easy customization of filters if self.mipmap: gl.glTexParameterf(self.target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR) else: gl.glTexParameterf(s...
python
{ "resource": "" }
q18671
Texture.attach_to_fbo
train
def attach_to_fbo(self): """Attach the texture to a bound FBO object, for rendering to texture.""" gl.glFramebufferTexture2DEXT(gl.GL_FRAMEBUFFER_EXT, self.attachment_point, self.target0, self.id, 0)
python
{ "resource": "" }
q18672
Texture.from_image
train
def from_image(cls, img_filename, mipmap=False, **kwargs): """Uses Pyglet's image.load function to generate a Texture from an image file. If 'mipmap', then texture will have mipmap layers calculated.""" img = pyglet.image.load(img_filename) tex = img.get_mipmapped_texture() if mipmap els...
python
{ "resource": "" }
q18673
TextureCube._genTex2D
train
def _genTex2D(self): """Generate an empty texture in OpenGL""" for face in range(6): gl.glTexImage2D(self.target0 + face, 0, self.internal_fmt, self.width, self.height, 0, self.pixel_fmt, gl.GL_UNSIGNED_BYTE, 0)
python
{ "resource": "" }
q18674
WavefrontReader.get_mesh
train
def get_mesh(self, body_name, **kwargs): """Builds Mesh from geom name in the wavefront file. Takes all keyword arguments that Mesh takes.""" body = self.bodies[body_name] vertices = body['v'] normals = body['vn'] if 'vn' in body else None texcoords = body['vt'] if 'vt' in body ...
python
{ "resource": "" }
q18675
UniformCollection.send
train
def send(self): """ Sends all the key-value pairs to the graphics card. These uniform variables will be available in the currently-bound shader. """ for name, array in iteritems(self): shader_id = c_int(0) gl.glGetIntegerv(gl.GL_CURRENT_PROGRAM, byref(sh...
python
{ "resource": "" }
q18676
Shader.bind
train
def bind(self): """Activate this Shader, making it the currently-bound program. Any Mesh.draw() calls after bind() will have their data processed by this Shader. To unbind, call Shader.unbind(). Example:: shader.bind() mesh.draw() shader.unbind() .. ...
python
{ "resource": "" }
q18677
Shader.from_file
train
def from_file(cls, vert, frag, **kwargs): """ Reads the shader programs, given the vert and frag filenames Arguments: - vert (str): The filename of the vertex shader program (ex: 'vertshader.vert') - frag (str): The filename of the fragment shader program (ex: 'fragshade...
python
{ "resource": "" }
q18678
Shader.link
train
def link(self): """link the program, making it the active shader. .. note:: Shader.bind() is preferred here, because link() Requires the Shader to be compiled already. """ gl.glLinkProgram(self.id) # Check if linking was successful. If not, print the log. link_status =...
python
{ "resource": "" }
q18679
PhysicalGraph.add_child
train
def add_child(self, child, modify=False): """ Adds an object as a child in the scene graph. With modify=True, model_matrix_transform gets change from identity and prevents the changes of the coordinates of the child""" SceneGraph.add_child(self, child) self.notify() if modify: ...
python
{ "resource": "" }
q18680
Example.setup_tree
train
def setup_tree(self): """Setup an example Treeview""" self.tree.insert("", tk.END, text="Example 1", iid="1") self.tree.insert("", tk.END, text="Example 2", iid="2") self.tree.insert("2", tk.END, text="Example Child") self.tree.heading("#0", text="Example heading")
python
{ "resource": "" }
q18681
Example.grid_widgets
train
def grid_widgets(self): """Put widgets in the grid""" sticky = {"sticky": "nswe"} self.label.grid(row=1, column=1, columnspan=2, **sticky) self.dropdown.grid(row=2, column=1, **sticky) self.entry.grid(row=2, column=2, **sticky) self.button.grid(row=3, column=1, columnspan...
python
{ "resource": "" }
q18682
Example.screenshot
train
def screenshot(self, *args): """Take a screenshot, crop and save""" from mss import mss if not os.path.exists("screenshots"): os.makedirs("screenshots") box = { "top": self.winfo_y(), "left": self.winfo_x(), "width": self.winfo_width(), ...
python
{ "resource": "" }
q18683
Example.screenshot_themes
train
def screenshot_themes(self, *args): """Take a screenshot for all themes available""" from time import sleep for theme in THEMES: example.set_theme(theme) example.update() sleep(0.05) self.screenshot()
python
{ "resource": "" }
q18684
ThemedWidget._load_themes
train
def _load_themes(self): """Load the themes into the Tkinter interpreter""" with utils.temporary_chdir(utils.get_file_directory()): self._append_theme_dir("themes") self.tk.eval("source themes/pkgIndex.tcl") theme_dir = "gif" if not self.png_support else "png" ...
python
{ "resource": "" }
q18685
ThemedWidget._append_theme_dir
train
def _append_theme_dir(self, name): """Append a theme dir to the Tk interpreter auto_path""" path = "[{}]".format(get_file_directory() + "/" + name) self.tk.call("lappend", "auto_path", path)
python
{ "resource": "" }
q18686
ThemedWidget.set_theme
train
def set_theme(self, theme_name): """ Set new theme to use. Uses a direct tk call to allow usage of the themes supplied with this package. :param theme_name: name of theme to activate """ package = theme_name if theme_name not in self.PACKAGES else self.PACKAGES[theme_nam...
python
{ "resource": "" }
q18687
ThemedWidget.set_theme_advanced
train
def set_theme_advanced(self, theme_name, brightness=1.0, saturation=1.0, hue=1.0, preserve_transparency=True, output_dir=None, advanced_name="advanced"): """ Load an advanced theme that is dynamically created Appli...
python
{ "resource": "" }
q18688
ThemedWidget._setup_advanced_theme
train
def _setup_advanced_theme(self, theme_name, output_dir, advanced_name): """ Setup all the files required to enable an advanced theme. Copies all the files over and creates the required directories if they do not exist. :param theme_name: theme to copy the files over from ...
python
{ "resource": "" }
q18689
ThemedWidget._setup_images
train
def _setup_images(directory, brightness, saturation, hue, preserve_transparency): """ Apply modifiers to the images of a theme Modifies the images using the PIL.ImageEnhance module. Using this function, theme images are modified to given them a unique look and feel. Works best w...
python
{ "resource": "" }
q18690
ThemedTk.set_theme
train
def set_theme(self, theme_name, toplevel=None, themebg=None): """Redirect the set_theme call to also set Tk background color""" if self._toplevel is not None and toplevel is None: toplevel = self._toplevel if self._themebg is not None and themebg is None: themebg = self._...
python
{ "resource": "" }
q18691
ThemedTk.config
train
def config(self, kw=None, **kwargs): """configure redirect to support additional options""" themebg = kwargs.pop("themebg", self._themebg) toplevel = kwargs.pop("toplevel", self._toplevel) theme = kwargs.pop("theme", self.current_theme) color = self._get_bg_color() if the...
python
{ "resource": "" }
q18692
ThemedTk.cget
train
def cget(self, k): """cget redirect to support additional options""" if k == "themebg": return self._themebg elif k == "toplevel": return self._toplevel elif k == "theme": return self.current_theme return tk.Tk.cget(self, k)
python
{ "resource": "" }
q18693
build_and_install_wheel
train
def build_and_install_wheel(python): """Build a binary distribution wheel and install it""" dist_type = "bdist_wheel" if not SDIST else "sdist" return_code = run_command("{} setup.py {}".format(python, dist_type)) if return_code != 0: print("Building and installing wheel failed.") exit(r...
python
{ "resource": "" }
q18694
ci
train
def ci(python="python", codecov="codecov", coverage_file="coverage.xml", wheel=True): """ Run the most common CI tasks """ # Import pip from pip import __version__ as pip_version if Version(pip_version) >= Version("10.0.0"): import pip._internal as pip else: import pip ...
python
{ "resource": "" }
q18695
ci_macos
train
def ci_macos(): """ Setup Travis-CI macOS for wheel building """ run_command("brew install $PYTHON pipenv || echo \"Installed PipEnv\"") command_string = "sudo -H $PIP install " for element in DEPENDENCIES + REQUIREMENTS + ["-U"]: command_string += element + " " run_command(command_s...
python
{ "resource": "" }
q18696
ThemedStyle.theme_use
train
def theme_use(self, theme_name=None): """ Set a new theme to use or return current theme name :param theme_name: name of theme to use :returns: active theme name """ if theme_name is not None: self.set_theme(theme_name) return ttk.Style.theme_use(self...
python
{ "resource": "" }
q18697
get_temp_directory
train
def get_temp_directory(): """Return an absolute path to an existing temporary directory""" # Supports all platforms supported by tempfile directory = os.path.join(gettempdir(), "ttkthemes") if not os.path.exists(directory): os.makedirs(directory) return directory
python
{ "resource": "" }
q18698
create_directory
train
def create_directory(directory): """Create directory but first delete it if it exists""" if os.path.exists(directory): rmtree(directory) os.makedirs(directory) return directory
python
{ "resource": "" }
q18699
make_transparent
train
def make_transparent(image): """Turn all black pixels in an image into transparent ones""" data = image.copy().getdata() modified = [] for item in data: if _check_pixel(item) is True: modified.append((255, 255, 255, 255)) # White transparent pixel continue modifi...
python
{ "resource": "" }