code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def pre_save(self, instance, add: bool): """Ran just before the model is saved, allows us to built the slug. Arguments: instance: The model that is being saved. add: Indicates whether this is a new entry to the database or...
Ran just before the model is saved, allows us to built the slug. Arguments: instance: The model that is being saved. add: Indicates whether this is a new entry to the database or an update. Returns: The locali...
def getFullFMAtIndex(self, index): ''' This function creates a complete FM-index for a specific position in the BWT. Example using the above example: BWT Full FM-index $ A C G T C 0 1 2 4 4 $ 0 1 3 4 4 C 1 1 3 4 4 A ...
This function creates a complete FM-index for a specific position in the BWT. Example using the above example: BWT Full FM-index $ A C G T C 0 1 2 4 4 $ 0 1 3 4 4 C 1 1 3 4 4 A 1 1 4 4 4 1 2 4 4 4 @return -...
def list(self, page=1, per_page=50): """ Lists Jobs. https://app.zencoder.com/docs/api/jobs/list """ data = {"page": page, "per_page": per_page} return self.get(self.base_url, data=data)
Lists Jobs. https://app.zencoder.com/docs/api/jobs/list
def _get_create_table_sql(self, table_name, columns, options=None): """ Returns the SQL used to create a table. :param table_name: The name of the table to create :type table_name: str :param columns: The table columns :type columns: dict :param options: The op...
Returns the SQL used to create a table. :param table_name: The name of the table to create :type table_name: str :param columns: The table columns :type columns: dict :param options: The options :type options: dict :rtype: str
def new_pic(cls, id_, name, desc, rId, left, top, width, height): """ Return a new ``<p:pic>`` element tree configured with the supplied parameters. """ xml = cls._pic_tmpl() % ( id_, name, desc, rId, left, top, width, height ) pic = parse_xml(xml) ...
Return a new ``<p:pic>`` element tree configured with the supplied parameters.
def _try_larger_image(self, roi, cur_text, cur_mrz, filter_order=3): """Attempts to improve the OCR result by scaling the image. If the new mrz is better, returns it, otherwise returns the old mrz.""" if roi.shape[1] <= 700: scale_by = int(1050.0 / roi.shape[1] + 0.5) roi...
Attempts to improve the OCR result by scaling the image. If the new mrz is better, returns it, otherwise returns the old mrz.
def _get_symbol_index(stroke_id_needle, segmentation): """ Parameters ---------- stroke_id_needle : int Identifier for the stroke of which the symbol should get found. segmentation : list of lists of integers An ordered segmentation of strokes to symbols. Returns ------- ...
Parameters ---------- stroke_id_needle : int Identifier for the stroke of which the symbol should get found. segmentation : list of lists of integers An ordered segmentation of strokes to symbols. Returns ------- The symbol index in which stroke_id_needle occurs Examples ...
def connect_attenuator(self, connect=True): """Establish a connection to the TDT PA5 attenuator""" if connect: try: pa5 = win32com.client.Dispatch("PA5.x") success = pa5.ConnectPA5('GB', 1) if success == 1: print 'Connection...
Establish a connection to the TDT PA5 attenuator
def select_python_parser(parser=None): """ Select default parser for loading and refactoring steps. Passing `redbaron` as argument will select the old paring engine from v0.3.3 Replacing the redbaron parser was necessary to support Python 3 syntax. We have tried our best to make...
Select default parser for loading and refactoring steps. Passing `redbaron` as argument will select the old paring engine from v0.3.3 Replacing the redbaron parser was necessary to support Python 3 syntax. We have tried our best to make sure there is no user impact on users. However, there may ...
def get_authorizations_by_ids(self, authorization_ids): """Gets an ``AuthorizationList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the authorizations specified in the ``Id`` list, in the order of the list, including duplicates, or an error...
Gets an ``AuthorizationList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the authorizations specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` in the supplied list is not found or ...
def json_encoder_default(obj): """Handle more data types than the default JSON encoder. Specifically, it treats a `set` and a `numpy.array` like a `list`. Example usage: ``json.dumps(obj, default=json_encoder_default)`` """ if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'): ...
Handle more data types than the default JSON encoder. Specifically, it treats a `set` and a `numpy.array` like a `list`. Example usage: ``json.dumps(obj, default=json_encoder_default)``
def _merge_results(self, results): """Combine results of test run with exisiting dict.""" self.results['tests'] += results['tests'] for key, value in results['summary'].items(): self.results['summary'][key] += value
Combine results of test run with exisiting dict.
def hsl_to_rgb(h, s=None, l=None): """Convert the color from HSL coordinates to RGB. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r...
Convert the color from HSL coordinates to RGB. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >...
def weld_iloc_int(array, index): """Retrieves the value at index. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Assumed to be bool data. index : int The array index from which to retrieve value. Returns ------- WeldObject Representation o...
Retrieves the value at index. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Assumed to be bool data. index : int The array index from which to retrieve value. Returns ------- WeldObject Representation of this computation.
def port(self, value): """ Setter for **self.__port** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format( "port", value) ...
Setter for **self.__port** attribute. :param value: Attribute value. :type value: int
def approve(self): """Approve object. This reverts a removal, resets the report counter, marks it with a green check mark (only visible to other moderators) on the website view and sets the approved_by attribute to the logged in user. :returns: The json response from the server...
Approve object. This reverts a removal, resets the report counter, marks it with a green check mark (only visible to other moderators) on the website view and sets the approved_by attribute to the logged in user. :returns: The json response from the server.
def _add_request_data(data, request): """ Attempts to build request data; if successful, sets the 'request' key on `data`. """ try: request_data = _build_request_data(request) except Exception as e: log.exception("Exception while building request_data for Rollbar payload: %r", e) ...
Attempts to build request data; if successful, sets the 'request' key on `data`.
def createTileUrl(self, x, y, z): ''' returns new tile url based on template ''' return self.tileTemplate.replace('{{x}}', str(x)).replace('{{y}}', str( y)).replace('{{z}}', str(z))
returns new tile url based on template
def run_apidoc(_): """This method is required by the setup method below.""" import os dirname = os.path.dirname(__file__) ignore_paths = [os.path.join(dirname, '../../aaf2/model'),] # https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/apidoc.py argv = [ '--force', '--no-...
This method is required by the setup method below.
def validate_args(self): """Input validation!""" def validate_name(): allowed_re = '^[a-z](([a-z0-9_-]+)?([a-z0-9])?)?' assert isinstance(self.params['name'], basestring), ( 'Name must be a string, not %s' % repr(self.params['name'])) assert re.match(a...
Input validation!
def get_change_values(change): """ In the case of deletions, we pull the change values for the XML request from the ResourceRecordSet._initial_vals dict, since we want the original values. For creations, we pull from the attributes on ResourceRecordSet. Since we're dealing with attributes vs. dict ...
In the case of deletions, we pull the change values for the XML request from the ResourceRecordSet._initial_vals dict, since we want the original values. For creations, we pull from the attributes on ResourceRecordSet. Since we're dealing with attributes vs. dict key/vals, we'll abstract this part away...
def count(args): """ %prog count cdhit.consensus.fasta Scan the headers for the consensus clusters and count the number of reads. """ from jcvi.graphics.histogram import stem_leaf_plot from jcvi.utils.cbook import SummaryStats p = OptionParser(count.__doc__) p.add_option("--csv", help=...
%prog count cdhit.consensus.fasta Scan the headers for the consensus clusters and count the number of reads.
def volume(self) -> float: """ Volume of the unit cell. """ m = self._matrix return float(abs(dot(np.cross(m[0], m[1]), m[2])))
Volume of the unit cell.
def expand_file_names(path, files_root): """ Expands paths (e.g. css/*.css in files_root /actual/path/to/css/files/) """ # For non-wildcards just return the path. This allows us to detect when # explicitly listed files are missing. if not any(wildcard in path for wildcard in '*?['): retu...
Expands paths (e.g. css/*.css in files_root /actual/path/to/css/files/)
def get_annotations(self): """ Fetch the annotations field if it does not exist. """ try: obj_list = self.__dict__['annotations'] return [Annotation(i) for i in obj_list] except KeyError: self._lazy_load() obj_list = self.__dict__['...
Fetch the annotations field if it does not exist.
def posted_data_dict(self): """ All the data that PayPal posted to us, as a correctly parsed dictionary of values. """ if not self.query: return None from django.http import QueryDict roughdecode = dict(item.split('=', 1) for item in self.query.split('&')) ...
All the data that PayPal posted to us, as a correctly parsed dictionary of values.
def delete_pool_member(hostname, username, password, name, member): ''' Delete an existing pool member. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to be modified ...
Delete an existing pool member. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to be modified member The name of the member to delete from the pool
def render(template, namespace, app=None): ''' Render the specified template using the Pecan rendering framework with the specified template namespace as a dictionary. Useful in a controller where you have no template specified in the ``@expose``. :param template: The path to your template, as you ...
Render the specified template using the Pecan rendering framework with the specified template namespace as a dictionary. Useful in a controller where you have no template specified in the ``@expose``. :param template: The path to your template, as you would specify in ``@expose``. ...
def follow(user, obj, send_action=True, actor_only=True, flag='', **kwargs): """ Creates a relationship allowing the object's activities to appear in the user's stream. Returns the created ``Follow`` instance. If ``send_action`` is ``True`` (the default) then a ``<user> started following <obje...
Creates a relationship allowing the object's activities to appear in the user's stream. Returns the created ``Follow`` instance. If ``send_action`` is ``True`` (the default) then a ``<user> started following <object>`` action signal is sent. Extra keyword arguments are passed to the action.send ca...
def make_mixture_prior(latent_size, mixture_components): """Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representin...
Creates the mixture of Gaussians prior distribution. Args: latent_size: The dimensionality of the latent representation. mixture_components: Number of elements of the mixture. Returns: random_prior: A `tfd.Distribution` instance representing the distribution over encodings in the absence of any ...
def unpack_thin(thin_path): ''' Unpack the Salt thin archive. ''' tfile = tarfile.TarFile.gzopen(thin_path) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function tfile.extractall(path=OPTIONS.saltdir) tfile.close() os.umask(old_umask) # pylint: disable=blacklisted-function...
Unpack the Salt thin archive.
def _iter_module_files(): """This iterates over all relevant Python files. It goes through all loaded files from modules, all files in folders of already loaded modules as well as all files reachable through a package. """ # The list call is necessary on Python 3 in case the module # dictionary...
This iterates over all relevant Python files. It goes through all loaded files from modules, all files in folders of already loaded modules as well as all files reachable through a package.
def smooth(x, window_len=7, window='hanning'): """ Smooth the data in x using convolution with a window of requested size and type. Parameters ---------- x : array_like(float) A flat NumPy array containing the data to smooth window_len : scalar(int), optional An odd integer ...
Smooth the data in x using convolution with a window of requested size and type. Parameters ---------- x : array_like(float) A flat NumPy array containing the data to smooth window_len : scalar(int), optional An odd integer giving the length of the window. Defaults to 7. window...
def search(name, jail=None, chroot=None, root=None, exact=False, glob=False, regex=False, pcre=False, comment=False, desc=False, full=False, depends=False, size=False, quiet=Fal...
Searches in remote package repositories CLI Example: .. code-block:: bash salt '*' pkg.search pattern jail Perform the search using the ``pkg.conf(5)`` from the specified jail CLI Example: .. code-block:: bash salt '*' pkg.search pattern jail=<jail name or ...
def _cloglog_transform_deriv_v(systematic_utilities, alt_IDs, rows_to_alts, shape_params, output_array=None, *args, **kwargs): """ Parameters ---------- ...
Parameters ---------- systematic_utilities : 1D ndarray. All elements should be ints, floats, or longs. Should contain the systematic utilities of each observation per available alternative. Note that this vector is formed by the dot product of the design matrix with the vector o...
def dashboard(request): "Counts, aggregations and more!" end_time = now() start_time = end_time - timedelta(days=7) defaults = {'start': start_time, 'end': end_time} form = DashboardForm(data=request.GET or defaults) if form.is_valid(): start_time = form.cleaned_data['start'] en...
Counts, aggregations and more!
def get(cls, resource_type): """Returns the ResourceType object for `resource_type`. If no existing object was found, a new type will be created in the database and returned Args: resource_type (str): Resource type name Returns: :obj:`ResourceType` """ ...
Returns the ResourceType object for `resource_type`. If no existing object was found, a new type will be created in the database and returned Args: resource_type (str): Resource type name Returns: :obj:`ResourceType`
def CreatePattern(patternId: int, pattern: ctypes.POINTER(comtypes.IUnknown)): """Create a concreate pattern by pattern id and pattern(POINTER(IUnknown)).""" subPattern = pattern.QueryInterface(GetPatternIdInterface(patternId)) if subPattern: return PatternConstructors[patternId](pattern=subPattern)
Create a concreate pattern by pattern id and pattern(POINTER(IUnknown)).
def transform_folder(args): """ Transform all the files in the source dataset for the given command and save the results as a single pickle file in the destination dataset :param args: tuple with the following arguments: - the command name: 'zero', 'one', 'two', ... - transforms to...
Transform all the files in the source dataset for the given command and save the results as a single pickle file in the destination dataset :param args: tuple with the following arguments: - the command name: 'zero', 'one', 'two', ... - transforms to apply to wav file - ...
def zadd(self, key, score, member, *pairs, exist=None): """Add one or more members to a sorted set or update its score. :raises TypeError: score not int or float :raises TypeError: length of pairs is not even number """ if not isinstance(score, (int, float)): raise T...
Add one or more members to a sorted set or update its score. :raises TypeError: score not int or float :raises TypeError: length of pairs is not even number
def _set_channels(self): """Sets the main channels for the pipeline This method will parse de the :attr:`~Process.processes` attribute and perform the following tasks for each process: - Sets the input/output channels and main input forks and adds them to the process'...
Sets the main channels for the pipeline This method will parse de the :attr:`~Process.processes` attribute and perform the following tasks for each process: - Sets the input/output channels and main input forks and adds them to the process's :attr:`flowcraft.pro...
def last_first_initial(self): """Return a name in the format of: Lastname, F [(Nickname)] """ return ("{}{} ".format(self.last_name, ", " + self.first_name[:1] + "." if self.first_name else "") + ("({}) ".format(self.nickname) ...
Return a name in the format of: Lastname, F [(Nickname)]
def get_state_actions(self, state, **kwargs): """ Creates all missing containers, networks, and volumes. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and ...
Creates all missing containers, networks, and volumes. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :rtype: list[dockermap.map.action.ItemActi...
def getfield(self, pkt, s): """ We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC 5246) to be False. This means that there should not be any length field. However, with TLS 1.3, zero lengths are always...
We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC 5246) to be False. This means that there should not be any length field. However, with TLS 1.3, zero lengths are always explicit.
def edit(i): # pragma: no cover """ Input: { (repo_uoa) - repo UOA module_uoa - module UOA data_uoa - data UOA (ignore_update) - (default==yes) if 'yes', do not add info about update (sort_keys) ...
Input: { (repo_uoa) - repo UOA module_uoa - module UOA data_uoa - data UOA (ignore_update) - (default==yes) if 'yes', do not add info about update (sort_keys) - (default==yes) if 'yes', sort k...
def get_subscription_by_channel_id_and_endpoint_id( self, channel_id, endpoint_id): """ Search for subscription by a given channel and endpoint """ subscriptions = self.search_subscriptions( channel_id=channel_id, endpoint_id=endpoint_id) try: ...
Search for subscription by a given channel and endpoint
def search_reports(self, search_term=None, enclave_ids=None, from_time=None, to_time=None, tags=None, excluded_tags=None): """ Uses the |search_reports_page| method to create a generator th...
Uses the |search_reports_page| method to create a generator that returns each successive report. :param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must be at least 3 characters. :param list(str) enclave_ids: list of enclave ids used to re...
def main(device_type): """Run ssh-agent using given hardware client factory.""" args = create_agent_parser(device_type=device_type).parse_args() util.setup_logging(verbosity=args.verbose, filename=args.log_file) public_keys = None filename = None if args.identity.startswith('/'): filena...
Run ssh-agent using given hardware client factory.
def send(self, stream, retry=16, timeout=60, quiet=0, callback=None): ''' Send a stream via the XMODEM protocol. >>> stream = file('/etc/issue', 'rb') >>> print modem.send(stream) True Returns ``True`` upon succesful transmission or ``False`` in case of ...
Send a stream via the XMODEM protocol. >>> stream = file('/etc/issue', 'rb') >>> print modem.send(stream) True Returns ``True`` upon succesful transmission or ``False`` in case of failure. :param stream: The stream object to send data from. :type st...
def update_widget(self, idx=None): """Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual c...
Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual conditions.
def delete(config, username, type): """Delete an LDAP user.""" client = Client() client.prepare_connection() user_api = API(client) user_api.delete(username, type)
Delete an LDAP user.
def parse_user_params(user_params): """ Parse the user params (-p/--params) and them as a dict. """ if user_params: params = {} try: for param in options.params.split(','): param_key, param_value = param.split('=', 1) params[param_key] = param_...
Parse the user params (-p/--params) and them as a dict.
def detach(self): """Returns a new NDArray, detached from the current graph.""" from . import _ndarray_cls hdl = NDArrayHandle() check_call(_LIB.MXNDArrayDetach(self.handle, ctypes.byref(hdl))) return _ndarray_cls(hdl)
Returns a new NDArray, detached from the current graph.
def add_relation(app_f, app_t, weight=1): ''' Adding relation between two posts. ''' recs = TabRel.select().where( (TabRel.post_f_id == app_f) & (TabRel.post_t_id == app_t) ) if recs.count() > 1: for record in recs: MRelation.delete...
Adding relation between two posts.
def add_sources_from_roi(self, names, roi, free=False, **kwargs): """Add multiple sources to the current ROI model copied from another ROI model. Parameters ---------- names : list List of str source names to add. roi : `~fermipy.roi_model.ROIModel` object ...
Add multiple sources to the current ROI model copied from another ROI model. Parameters ---------- names : list List of str source names to add. roi : `~fermipy.roi_model.ROIModel` object The roi model from which to add sources. free : bool ...
def yaml2tree(cls, yamltree): """Class method that creates a tree from YAML. | # Example yamltree data: | - !Node &root | name: "root node" | parent: null | data: | testpara: 111 | - !Node &child1 | name: "child node" | paren...
Class method that creates a tree from YAML. | # Example yamltree data: | - !Node &root | name: "root node" | parent: null | data: | testpara: 111 | - !Node &child1 | name: "child node" | parent: *root | - !Node &gc1 |...
def get_ser_val_alt(lat: float, lon: float, da_alt_x: xr.DataArray, da_alt: xr.DataArray, da_val: xr.DataArray)->pd.Series: '''interpolate atmospheric variable to a specified altitude Parameters ---------- lat : float latitude of specified site lon : ...
interpolate atmospheric variable to a specified altitude Parameters ---------- lat : float latitude of specified site lon : float longitude of specified site da_alt_x : xr.DataArray desired altitude to interpolate variable at da_alt : xr.DataArray altitude associ...
def transform(self, X): ''' Transform a list of bag features into its projection series representation. Parameters ---------- X : :class:`skl_groups.features.Features` or list of bag feature arrays New data to transform. The data should all lie in [0, 1]; ...
Transform a list of bag features into its projection series representation. Parameters ---------- X : :class:`skl_groups.features.Features` or list of bag feature arrays New data to transform. The data should all lie in [0, 1]; use :class:`skl_groups.preprocessin...
def open(self): """ Setup serial port and set is as escpos device """ self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout, dsrdtr=True) if self.device is not None: ...
Setup serial port and set is as escpos device
def get_free_sphere_params(structure, rad_dict=None, probe_rad=0.1): """ Analyze the void space in the input structure using voronoi decomposition Calls Zeo++ for Voronoi decomposition. Args: structure: pymatgen.core.structure.Structure rad_dict (optional): Dictionary of radii of elemen...
Analyze the void space in the input structure using voronoi decomposition Calls Zeo++ for Voronoi decomposition. Args: structure: pymatgen.core.structure.Structure rad_dict (optional): Dictionary of radii of elements in structure. If not given, Zeo++ default values are used. ...
def generate_files(engine, crypto_factory, min_dt=None, max_dt=None, logger=None): """ Create a generator of decrypted files. Files are yielded in ascending order of their timestamp. This function selects all current notebooks (optionally, falling within a datetime range), decry...
Create a generator of decrypted files. Files are yielded in ascending order of their timestamp. This function selects all current notebooks (optionally, falling within a datetime range), decrypts them, and returns a generator yielding dicts, each containing a decoded notebook and metadata including th...
def nv_tuple_list_replace(l, v): """ replace a tuple in a tuple list """ _found = False for i, x in enumerate(l): if x[0] == v[0]: l[i] = v _found = True if not _found: l.append(v)
replace a tuple in a tuple list
def _hybrid_select_metrics(self, dup_bam, bait_file, target_file): """Generate metrics for hybrid selection efficiency. """ metrics = self._check_metrics_file(dup_bam, "hs_metrics") if not file_exists(metrics): with bed_to_interval(bait_file, dup_bam) as ready_bait: ...
Generate metrics for hybrid selection efficiency.
def deleted(message): """Create a Deleted response builder with specified message.""" def deleted(value, _context, **_params): return Deleted(value, message) return deleted
Create a Deleted response builder with specified message.
def get_software_package_compilation_timestamp(cls,calc,**kwargs): """ Returns the timestamp of package/program compilation in ISO 8601 format. """ from dateutil.parser import parse try: date = calc.out.job_info.get_dict()['compiled'] return parse(...
Returns the timestamp of package/program compilation in ISO 8601 format.
def update_features(self, poly): """Evaluate wavelength at xpos using the provided polynomial.""" for feature in self.features: feature.wavelength = poly(feature.xpos)
Evaluate wavelength at xpos using the provided polynomial.
def error_and_result(f): """ Format task result into json dictionary `{'data': task return value}` if no exception was raised during the task execution. If there was raised an exception during task execution, formats task result into dictionary `{'error': exception message with traceback}`. """ ...
Format task result into json dictionary `{'data': task return value}` if no exception was raised during the task execution. If there was raised an exception during task execution, formats task result into dictionary `{'error': exception message with traceback}`.
def dict_from_prefix(cls, prefix, dictionary): """ >>> from collections import OrderedDict >>> od = OrderedDict() >>> od["problem[q0][a]"]=1 >>> od["problem[q0][b][c]"]=2 >>> od["problem[q1][first]"]=1 >>> od["problem[q1][second]"]=2 ...
>>> from collections import OrderedDict >>> od = OrderedDict() >>> od["problem[q0][a]"]=1 >>> od["problem[q0][b][c]"]=2 >>> od["problem[q1][first]"]=1 >>> od["problem[q1][second]"]=2 >>> AdminCourseEditTask.dict_from_prefix("problem",od) ...
def OnPasteFormat(self, event): """Paste format event handler""" with undo.group(_("Paste format")): self.grid.actions.paste_format() self.grid.ForceRefresh() self.grid.update_attribute_toolbar() self.grid.actions.zoom()
Paste format event handler
def iteritems(self, indices=None): 'Iterate through items in the ``indices`` (defaults to all indices)' if indices is None: indices = force_list(self.indices.keys()) for x in self.itervalues(indices): yield x
Iterate through items in the ``indices`` (defaults to all indices)
def gen_cartesian_product(*args): """ generate cartesian product for lists Args: args (list of list): lists to be generated with cartesian product Returns: list: cartesian product in list Examples: >>> arg1 = [{"a": 1}, {"a": 2}] >>> arg2 = [{"x": 111, "y": 112}, {"x"...
generate cartesian product for lists Args: args (list of list): lists to be generated with cartesian product Returns: list: cartesian product in list Examples: >>> arg1 = [{"a": 1}, {"a": 2}] >>> arg2 = [{"x": 111, "y": 112}, {"x": 121, "y": 122}] >>> args = [arg1...
def AddContract(self, contract): """ Add a contract to the database. Args: contract(neo.SmartContract.Contract): a Contract instance. """ super(UserWallet, self).AddContract(contract) try: db_contract = Contract.get(ScriptHash=contract.ScriptHash...
Add a contract to the database. Args: contract(neo.SmartContract.Contract): a Contract instance.
def load_conf(cfg_path): """ Try to load the given conf file. """ global config try: cfg = open(cfg_path, 'r') except Exception as ex: if verbose: print("Unable to open {0}".format(cfg_path)) print(str(ex)) return False # Read the entire conte...
Try to load the given conf file.
def add_keywords_from_list(self, keyword_list): """To add keywords from a list Args: keyword_list (list(str)): List of keywords to add Examples: >>> keyword_processor.add_keywords_from_list(["java", "python"]}) Raises: AttributeError: If `keyword_lis...
To add keywords from a list Args: keyword_list (list(str)): List of keywords to add Examples: >>> keyword_processor.add_keywords_from_list(["java", "python"]}) Raises: AttributeError: If `keyword_list` is not a list.
def start_adc_comparator(self, channel, high_threshold, low_threshold, gain=1, data_rate=None, active_low=True, traditional=True, latching=False, num_readings=1): """Start continuous ADC conversions on the specified channel (0-3) with the compara...
Start continuous ADC conversions on the specified channel (0-3) with the comparator enabled. When enabled the comparator to will check if the ADC value is within the high_threshold & low_threshold value (both should be signed 16-bit integers) and trigger the ALERT pin. The behavior can...
def po_to_ods(languages, locale_root, po_files_path, temp_file_path): """ Converts po file to csv GDocs spreadsheet readable format. :param languages: list of language codes :param locale_root: path to locale root folder containing directories with languages :param po_files_p...
Converts po file to csv GDocs spreadsheet readable format. :param languages: list of language codes :param locale_root: path to locale root folder containing directories with languages :param po_files_path: path from lang directory to po file :param temp_file_path: path where tem...
def ParseOptions(cls, options, analysis_plugin): """Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. Ba...
Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when unable to connect to Viper instance.
def to_string(value, ctx): """ Tries conversion of any value to a string """ if isinstance(value, bool): return "TRUE" if value else "FALSE" elif isinstance(value, int): return str(value) elif isinstance(value, Decimal): return format_decimal(value) elif isinstance(va...
Tries conversion of any value to a string
def start(self, historics_id): """ Start the historics job with the given ID. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstart :param historics_id: hash of the job to start :type historics_id: str :return: dict of REST AP...
Start the historics job with the given ID. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstart :param historics_id: hash of the job to start :type historics_id: str :return: dict of REST API output with headers attached ...
def authorize(): """Authorize to twitter. Use PIN authentification. :returns: Token for authentificate with Twitter. :rtype: :class:`autotweet.twitter.OAuthToken` """ auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) url = auth.get_authorization_url() print('Open this url on y...
Authorize to twitter. Use PIN authentification. :returns: Token for authentificate with Twitter. :rtype: :class:`autotweet.twitter.OAuthToken`
def install_extensions(extensions, **connection_parameters): """Install Postgres extension if available. Notes ----- - superuser is generally required for installing extensions. - Currently does not support specific schema. """ from postpy.connections import connect conn = connect(**c...
Install Postgres extension if available. Notes ----- - superuser is generally required for installing extensions. - Currently does not support specific schema.
def _compile(cls, lines): '''Return both variable names used in the #for loop in the current line.''' m = cls.RE_FOR.match(lines.current) if m is None: raise DefineBlockError( 'Incorrect block definition at line {}, {}\nShould be ' 'something l...
Return both variable names used in the #for loop in the current line.
def get_loader(vm_, **kwargs): ''' Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overrid...
Returns the information on the loader for a given vm :param vm_: name of the domain :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults CLI Example: .. code...
def get_default_config(self): """ Returns the default collector settings """ config = super(MonitCollector, self).get_default_config() config.update({ 'host': '127.0.0.1', 'port': 2812, 'user': 'monit', 'pass...
Returns the default collector settings
def _epd_residual(coeffs, mags, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd): ''' This is the residual function to minimize using scipy.optimize.leastsq. ''' f = _epd_function(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd) residual = mags - f return residual
This is the residual function to minimize using scipy.optimize.leastsq.
def add(self, post_id): ''' Adding reply to a post. ''' post_data = self.get_post_data() post_data['user_name'] = self.userinfo.user_name post_data['user_id'] = self.userinfo.uid post_data['post_id'] = post_id replyid = MReply.create_reply(post_data) ...
Adding reply to a post.
def add_bias(self, name, b, input_name, output_name, shape_bias = [1]): """ Add bias layer to the model. Parameters ---------- name: str The name of this layer. b: int | numpy.array Bias to add to the input. input_name: str The...
Add bias layer to the model. Parameters ---------- name: str The name of this layer. b: int | numpy.array Bias to add to the input. input_name: str The input blob name of this layer. output_name: str The output blob name of...
def receive_request(self, transaction): """ Manage the observe option in the request end eventually initialize the client for adding to the list of observers or remove from the list. :type transaction: Transaction :param transaction: the transaction that owns the request ...
Manage the observe option in the request end eventually initialize the client for adding to the list of observers or remove from the list. :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the modified transact...
def get_route_shape_segments(cur, route_id): """ Given a route_id, return its stop-sequence. Parameters ---------- cur: sqlite3.Cursor cursor to a GTFS database route_id: str id of the route Returns ------- shape_points: list elements are dictionaries contai...
Given a route_id, return its stop-sequence. Parameters ---------- cur: sqlite3.Cursor cursor to a GTFS database route_id: str id of the route Returns ------- shape_points: list elements are dictionaries containing the 'seq', 'lat', and 'lon' of the shape
def info(path): ''' Display synchronization information. ''' output, err = cli_syncthing_adapter.info(folder=path) if err: click.echo(output, err=err) else: stat = output['status'] click.echo("State: %s" % stat['state']) click.echo("\nTotal Files: %s" % stat['localFiles']) click.echo("File...
Display synchronization information.
def parse_response(self, connection, command_name, **options): """ Parses a response from the ssdb server """ response = connection.read_response() if command_name in self.response_callbacks and len(response): status = nativestr(response[0]) if status == R...
Parses a response from the ssdb server
def send_media_group( self, media: str, disable_notification: bool = False, reply_to_message_id: int = None, **options ): """ Send a group of photos or videos as an album :param media: A JSON-serialized array describing photos and videos to be...
Send a group of photos or videos as an album :param media: A JSON-serialized array describing photos and videos to be sent, must include 2–10 items :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :param reply_to_message_...
def displayEmptyInputWarningBox(display=True, parent=None): """ Displays a warning box for the 'input' parameter. """ if sys.version_info[0] >= 3: from tkinter.messagebox import showwarning else: from tkMessageBox import showwarning if display: msg = 'No valid input files fo...
Displays a warning box for the 'input' parameter.
def _main(args): """Batch compression. args contains: * input - path to input directory * output - path to output directory or None * apikey - TinyPNG API key * overwrite - boolean flag """ if not args.apikey: print("\nPlease provide TinyPNG API key") print("To obta...
Batch compression. args contains: * input - path to input directory * output - path to output directory or None * apikey - TinyPNG API key * overwrite - boolean flag
def setup_ui(self, ): """Create the layouts and set some attributes of the ui :returns: None :rtype: None :raises: None """ grid = QtGui.QGridLayout(self) grid.setContentsMargins(0, 0, 0, 0) self.setLayout(grid)
Create the layouts and set some attributes of the ui :returns: None :rtype: None :raises: None
def construct_mail(self): """ compiles the information contained in this envelope into a :class:`email.Message`. """ # Build body text part. To properly sign/encrypt messages later on, we # convert the text to its canonical format (as per RFC 2015). canonical_form...
compiles the information contained in this envelope into a :class:`email.Message`.
def dict_merge(a, b, dict_boundary): """ Recursively merges dicts. not just simple a['key'] = b['key'], if both a and b have a key who's value is a dict then dict_merge is called on both values and the result stored in the returned dictionary. Also, if keys contain `self._dict_boundary`, they will ...
Recursively merges dicts. not just simple a['key'] = b['key'], if both a and b have a key who's value is a dict then dict_merge is called on both values and the result stored in the returned dictionary. Also, if keys contain `self._dict_boundary`, they will be split into sub dictionaries. :param a...
def init_common(app): """Post initialization.""" if app.config['USERPROFILES_EXTEND_SECURITY_FORMS']: security_ext = app.extensions['security'] security_ext.confirm_register_form = confirm_register_form_factory( security_ext.confirm_register_form) security_ext.register_form =...
Post initialization.
def _attribute_iterator(self, mapped_class, key): """ Returns an iterator over the attributes in this mapping for the given mapped class and attribute key. If this is a pruning mapping, attributes that are ignored because of a custom configuration or because of the default ignor...
Returns an iterator over the attributes in this mapping for the given mapped class and attribute key. If this is a pruning mapping, attributes that are ignored because of a custom configuration or because of the default ignore rules are skipped.
def __prepare_dataset_parameter(self, dataset): """ Processes the dataset parameter for type correctness. Returns it as an SFrame. """ # Translate the dataset argument into the proper type if not isinstance(dataset, _SFrame): def raise_dataset_type_exception(...
Processes the dataset parameter for type correctness. Returns it as an SFrame.