code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _name_from_project_path(path, project, template): """Validate a URI path and get the leaf object's name. :type path: str :param path: URI path containing the name. :type project: str :param project: (Optional) The project associated with the request. It is included for vali...
Validate a URI path and get the leaf object's name. :type path: str :param path: URI path containing the name. :type project: str :param project: (Optional) The project associated with the request. It is included for validation purposes. If passed as None, disa...
def shutdown(cls, dir_): """ :param dir_: The directory that will contain the cache state file. """ cacheInfo = cls._CacheState._load(os.path.join(dir_, '_cacheState')) cls.findAndHandleDeadJobs(cacheInfo, batchSystemShutdown=True) shutil.rmtree(dir_)
:param dir_: The directory that will contain the cache state file.
def receive_trial_result(self, parameter_id, parameters, value): '''Record the result from a trial Parameters ---------- parameters: dict value : dict/float if value is dict, it should have "default" key. value is final metrics of the trial. ''' ...
Record the result from a trial Parameters ---------- parameters: dict value : dict/float if value is dict, it should have "default" key. value is final metrics of the trial.
def get_object(self, point, buffer_size=0, multiple=False): """ lookup object based on point as [longitude, latitude] """ # first search bounding boxes # idx.intersection method modifies input if it is a list try: tmp = tuple(point) except TypeError: retur...
lookup object based on point as [longitude, latitude]
def dragdrop(self, chviewer, uris): """Called when a drop operation is performed on a channel viewer. We are called back with a URL and we attempt to (down)load it if it names a file. """ # find out our channel chname = self.get_channel_name(chviewer) self.open_ur...
Called when a drop operation is performed on a channel viewer. We are called back with a URL and we attempt to (down)load it if it names a file.
def handle_message(self, msg): """manage message of different type and in the context of path""" if msg.module not in self._modules: if msg.module: self.writeln("************* Module %s" % msg.module) self._modules.add(msg.module) else: ...
manage message of different type and in the context of path
def dragData(self, x=None, y=None): """ Returns any drag information that will be used from this chart item. :return <QMimeData> || None """ # look for specific drag information for this item first = (x, y) second = (x, None) third ...
Returns any drag information that will be used from this chart item. :return <QMimeData> || None
def get_version_from_dirname(name, parent): """Extracted sdist""" parent = parent.resolve() re_dirname = re.compile(f"{name}-{RE_VERSION}$") if not re_dirname.match(parent.name): return None return Version.parse(parent.name[len(name) + 1 :])
Extracted sdist
def getTotal(self): """ Compute TotalPrice """ total = 0 for lineitem in self.supplyorder_lineitems: total += Decimal(lineitem['Quantity']) * \ Decimal(lineitem['Price']) * \ ((Decimal(lineitem['VAT']) /100) + 1) return total
Compute TotalPrice
def _write_object(self, val, outstream): ''' Write object into the stream :param val: :param outstream: ''' # first attempt using an existing custom serializer serializer = self.__lookup_serializer(getattr(val, '__class__')) if serializer is not None: ...
Write object into the stream :param val: :param outstream:
def _spill(self): """ dump already partitioned data into disks. It will dump the data in batch for better performance. """ global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(pat...
dump already partitioned data into disks. It will dump the data in batch for better performance.
def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None): """Computes difference between logit for `label` and next highest logit. The loss is high when `label` is unlikely (targeted by default). This follows the same interface as `loss_fn` for TensorOptimizer and projected_optimization, i.e...
Computes difference between logit for `label` and next highest logit. The loss is high when `label` is unlikely (targeted by default). This follows the same interface as `loss_fn` for TensorOptimizer and projected_optimization, i.e. it returns a batch of loss values.
def get(self, remote_path, local_path='', overwrite=False, synopsis=True): ''' a method to copy a folder or file from AWS instance to local device :param remote_path: string with path to copy contents on remote host :param local_path: [optional] string with path to folder or file o...
a method to copy a folder or file from AWS instance to local device :param remote_path: string with path to copy contents on remote host :param local_path: [optional] string with path to folder or file on local host :param overwrite: [optional] boolean to enable file overwrite on remote host ...
def config_add(self, key, value, **kwargs): """ Add a value to a key. Returns a list of warnings Conda may have emitted. """ cmd_list = ['config', '--add', key, value] cmd_list.extend(self._setup_config_from_kwargs(kwargs)) return self._call_and_parse( ...
Add a value to a key. Returns a list of warnings Conda may have emitted.
def send(self, msg_p): """ Send a zmsg message to the actor, take ownership of the message and destroy when it has been sent. """ return lib.zactor_send(self._as_parameter_, byref(zmsg_p.from_param(msg_p)))
Send a zmsg message to the actor, take ownership of the message and destroy when it has been sent.
def legal_module_name(self, name): """Legal module names are dotted strings where each part is a valid Python identifier. (and not a keyword, and support unicode identifiers in Python3, ..) """ if name in self._legal_mnames: return self._legal_mnames[...
Legal module names are dotted strings where each part is a valid Python identifier. (and not a keyword, and support unicode identifiers in Python3, ..)
def set_privilege(self, name, value=None): """Configures the user privilege value in EOS Args: name (str): The name of the user to craete value (int): The privilege value to assign to the user. Valid values are in the range of 0 to 15 Returns: ...
Configures the user privilege value in EOS Args: name (str): The name of the user to craete value (int): The privilege value to assign to the user. Valid values are in the range of 0 to 15 Returns: True if the operation was successful otherwise Fal...
def tagref(self, index): """Get the tag and reference number of a vgroup member, given the index number of that member. Args:: index member index (0 based) Returns:: 2-element tuple: - member tag - member reference number C libra...
Get the tag and reference number of a vgroup member, given the index number of that member. Args:: index member index (0 based) Returns:: 2-element tuple: - member tag - member reference number C library equivalent : Vgettagref
def min_sequence_length(self, dataset_split): """Determine the minimum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The minimum length that a sequence can be for this dataset_split. """ return { problem.DatasetSplit.TRAIN: 8, ...
Determine the minimum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The minimum length that a sequence can be for this dataset_split.
def request_view(request, request_pk): ''' The view of a single request. ''' if request.is_ajax(): if not request.user.is_authenticated(): return HttpResponse(json.dumps(dict()), content_type="application/json") try: relevant_reque...
The view of a single request.
def raise_os_error(_errno, path=None): """ Helper for raising the correct exception under Python 3 while still being able to raise the same common exception class in Python 2.7. """ msg = "%s: '%s'" % (strerror(_errno), path) if path else strerror(_errno) raise OSError(_errno, msg)
Helper for raising the correct exception under Python 3 while still being able to raise the same common exception class in Python 2.7.
def solve(self, max_worlds=10000, silent=False): """ find the best world to make people happy """ self.num_worlds = 0 num_unhappy = 0 for tax_rate in range(self.tax_range[0],self.tax_range[1]): for equity in range(self.equity_range[0],self.equity_range[1]): ...
find the best world to make people happy
def to_primitive(value, convert_instances=False, convert_datetime=True, level=0, max_depth=3): """Convert a complex object into primitives. Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures. ...
Convert a complex object into primitives. Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures. To handle cyclical data structures we could track the actual objects visited in a set, but not all objects are...
def automatic_density(cls, structure, kppa, chksymbreak=None, use_symmetries=True, use_time_reversal=True, shifts=(0.5, 0.5, 0.5)): """ Returns an automatic Kpoint object based on a structure and a kpoint density. Uses Gamma centered meshes for hexagonal cells and Monkh...
Returns an automatic Kpoint object based on a structure and a kpoint density. Uses Gamma centered meshes for hexagonal cells and Monkhorst-Pack grids otherwise. Algorithm: Uses a simple approach scaling the number of divisions along each reciprocal lattice vector proportional to...
def get(self, endpoint, **kwargs): """Get a resource. Args: endpoint: resource endpoint. """ return self._request(requests.get, endpoint, **kwargs)
Get a resource. Args: endpoint: resource endpoint.
def conv(input, kernel, biases, k_h, k_w, c_o, s_h, s_w, padding="VALID", group=1): """ Convolution layer helper function From https://github.com/ethereon/caffe-tensorflow """ c_i = input.get_shape()[-1] assert c_i%group==0 assert c_o%group==0 convolve = lambda i, k: tf.nn.conv2d(i, k, ...
Convolution layer helper function From https://github.com/ethereon/caffe-tensorflow
def encodeEntitiesReentrant(self, input): """Do a global encoding of a string, replacing the predefined entities and non ASCII values with their entities and CharRef counterparts. Contrary to xmlEncodeEntities, this routine is reentrant, and result must be deallocated. """ ...
Do a global encoding of a string, replacing the predefined entities and non ASCII values with their entities and CharRef counterparts. Contrary to xmlEncodeEntities, this routine is reentrant, and result must be deallocated.
def _PromptUserForInput(self, input_text): """Prompts user for an input. Args: input_text (str): text used for prompting the user for input. Returns: str: input read from the user. """ self._output_writer.Write('{0:s}: '.format(input_text)) return self._input_reader.Read()
Prompts user for an input. Args: input_text (str): text used for prompting the user for input. Returns: str: input read from the user.
def assertSingleClass(self,P): """ Check whether the rate/probability matrix consists of a single connected class. If this is not the case, the steady state distribution is not well defined. """ components, _ = csgraph.connected_components(P, directed=True, connection='weak') ...
Check whether the rate/probability matrix consists of a single connected class. If this is not the case, the steady state distribution is not well defined.
def _finalize_axis(self, key, **kwargs): """ Extends the ElementPlot _finalize_axis method to set appropriate labels, and axes options for 3D Plots. """ axis = self.handles['axis'] self.handles['fig'].set_frameon(False) axis.grid(self.show_grid) axis.view_...
Extends the ElementPlot _finalize_axis method to set appropriate labels, and axes options for 3D Plots.
def ann_default_transformer(fills=ANN_DEFAULT_FILLS): """ Return a simple transformer function for parsing ANN annotations. N.B., ignores all but the first effect. """ def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect...
Return a simple transformer function for parsing ANN annotations. N.B., ignores all but the first effect.
def copy(location): """copy file or directory at a given location; can be pasted later""" copyData = settings.getDataFile() copyFileLocation = os.path.abspath(location) copy = {"copyLocation": copyFileLocation} dataFile = open(copyData, "wb") pickle.dump(copy, dataFile) speech.speak(location + " copied successfu...
copy file or directory at a given location; can be pasted later
def mutual_info_score(self, reference_clusters): """ Calculates the MI (mutual information) w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: The resulting MI score. """ return mutual_info_sc...
Calculates the MI (mutual information) w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: The resulting MI score.
def totz(when, tz=None): """ Return a date, time, or datetime converted to a datetime in the given timezone. If when is a datetime and has no timezone it is assumed to be local time. Date and time objects are also assumed to be UTC. The tz value defaults to UTC. Raise TypeError if when cannot be convert...
Return a date, time, or datetime converted to a datetime in the given timezone. If when is a datetime and has no timezone it is assumed to be local time. Date and time objects are also assumed to be UTC. The tz value defaults to UTC. Raise TypeError if when cannot be converted to a datetime.
def getID(code_file): """Get the language ID of the input file language""" json_path = ghostfolder+'/'+json_file if os.path.exists(json_path): pass else: download_file('https://ghostbin.com/languages.json') lang = detect_lang(code_file) json_data = json.load(file(json_path))#don't think i need this though ...
Get the language ID of the input file language
def _jobs(): ''' Return the currently configured jobs. ''' response = salt.utils.http.query( "{0}/scheduler/jobs".format(_base_url()), decode_type='json', decode=True, ) jobs = {} for job in response['dict']: jobs[job.pop('name')] = job return jobs
Return the currently configured jobs.
def quaternion_from_matrix(matrix): """Return quaternion from rotation matrix. >>> R = rotation_matrix(0.123, (1, 2, 3)) >>> q = quaternion_from_matrix(R) >>> numpy.allclose(q, [0.0164262, 0.0328524, 0.0492786, 0.9981095]) True """ q = numpy.empty((4, ), dtype=numpy.float64) M = numpy....
Return quaternion from rotation matrix. >>> R = rotation_matrix(0.123, (1, 2, 3)) >>> q = quaternion_from_matrix(R) >>> numpy.allclose(q, [0.0164262, 0.0328524, 0.0492786, 0.9981095]) True
def remove_from_space_size(self, removal_bytes): # type: (int) -> None ''' Remove bytes from the volume descriptor. Parameters: removal_bytes - The number of bytes to remove. Returns: Nothing. ''' if not self._initialized: raise pycd...
Remove bytes from the volume descriptor. Parameters: removal_bytes - The number of bytes to remove. Returns: Nothing.
def download(directory, master_token=None, member=None, access_token=None, source=None, project_data=False, max_size='128m', verbose=False, debug=False, memberlist=None, excludelist=None, id_filename=False): """ Download data from project members to the target directory. ...
Download data from project members to the target directory. Unless this is a member-specific download, directories will be created for each project member ID. Also, unless a source is specified, all shared sources are downloaded and data is sorted into subdirectories according to source. Projects ...
def _grow_to(self, width, height, top_tc=None): """ Grow this cell to *width* grid columns and *height* rows by expanding horizontal spans and creating continuation cells to form vertical spans. """ def vMerge_val(top_tc): if top_tc is not self: ...
Grow this cell to *width* grid columns and *height* rows by expanding horizontal spans and creating continuation cells to form vertical spans.
def create(self, jti, aud=''): """Adds a token to the blacklist. Args: jti (str): the jti of the JWT to blacklist. aud (str, optional): The JWT's aud claim. The client_id of the application for which it was issued. body (dict): See: http...
Adds a token to the blacklist. Args: jti (str): the jti of the JWT to blacklist. aud (str, optional): The JWT's aud claim. The client_id of the application for which it was issued. body (dict): See: https://auth0.com/docs/api/management/v2#!/Bla...
def redirect_stdout(self): """Redirect stdout to file so that it can be tailed and aggregated with the other logs.""" self.hijacked_stdout = sys.stdout self.hijacked_stderr = sys.stderr # 0 must be set as the buffer, otherwise lines won't get logged in time. sys.stdout = open(sel...
Redirect stdout to file so that it can be tailed and aggregated with the other logs.
def cast_bytes(s, encoding=None): """Source: https://github.com/ipython/ipython_genutils""" if not isinstance(s, bytes): return encode(s, encoding) return s
Source: https://github.com/ipython/ipython_genutils
def all_tokens(self, delimiter=' ', label_list_ids=None): """ Return a list of all tokens occurring in one of the labels in the label-lists. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.L...
Return a list of all tokens occurring in one of the labels in the label-lists. Args: delimiter (str): The delimiter used to split labels into tokens (see :meth:`audiomate.annotations.Label.tokenized`). label_list_ids (list): If not None, only labels ...
def get_card(self, card_id, **query_params): ''' Get a Card for a given card id. Returns a Card object. Returns: Card: The card with the given card_id ''' card_json = self.fetch_json( uri_path=self.base_uri + '/cards/' + card_id ) return ...
Get a Card for a given card id. Returns a Card object. Returns: Card: The card with the given card_id
def subCell2DCoords(*args, **kwargs): '''Same as subCell2DSlices but returning coordinates Example: g = subCell2DCoords(arr, shape) for x, y in g: plt.plot(x, y) ''' for _, _, s0, s1 in subCell2DSlices(*args, **kwargs): yield ((s1.start, s1.start, s1.sto...
Same as subCell2DSlices but returning coordinates Example: g = subCell2DCoords(arr, shape) for x, y in g: plt.plot(x, y)
def is_date_ranges_intersection(t1start, t1end, t2start, t2end): """ Проверяем совпадают ли периоды """ return (t1start <= t2start <= t1end) or (t2start <= t1start <= t2end)
Проверяем совпадают ли периоды
def put_event(self, data): """ Create event from `data` and add it to the queue. :arg json data: The JSON data from which to create the event. :Raises: :class:`pygerrit.error.GerritError` if the queue is full, or the factory could not create the event. """ try: ...
Create event from `data` and add it to the queue. :arg json data: The JSON data from which to create the event. :Raises: :class:`pygerrit.error.GerritError` if the queue is full, or the factory could not create the event.
def pprint(data): """ Returns an indented HTML pretty-print version of JSON. Take the event_payload JSON, indent it, order the keys and then present it as a <code> block. That's about as good as we can get until someone builds a custom syntax function. """ pretty = json.dumps(data, sort_ke...
Returns an indented HTML pretty-print version of JSON. Take the event_payload JSON, indent it, order the keys and then present it as a <code> block. That's about as good as we can get until someone builds a custom syntax function.
def add_agent_preset(self, file_path): """ Loads a preset using file_path with all values from that path loaded :param file_path: the path to load the preset from. We'll throw an exception if it's invalid. :return preset: the agent preset created """ if file_path is not N...
Loads a preset using file_path with all values from that path loaded :param file_path: the path to load the preset from. We'll throw an exception if it's invalid. :return preset: the agent preset created
def create_api_v4_equipment(self): """Get an instance of Api Equipment services facade.""" return ApiV4Equipment( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of Api Equipment services facade.
def listdir(self, directory_path=None, hidden_files=False): """ Return a list of files and directories in a given directory. :param directory_path: Optional str (defaults to current directory) :param hidden_files: Include hidden files :return: Directory listing """ ...
Return a list of files and directories in a given directory. :param directory_path: Optional str (defaults to current directory) :param hidden_files: Include hidden files :return: Directory listing
def _status_query(query, hostname, enumerate=None, service=None): ''' Send query along to Nagios. ''' config = _config() data = None params = { 'hostname': hostname, 'query': query, } ret = { 'result': False } if enumerate: params['formatoptions...
Send query along to Nagios.
def set_distributed_assembled_rows_cols(self, irn_loc, jcn_loc): """Set the distributed assembled matrix row & column numbers. Distributed assembled matrices require setting icntl(18) != 0. """ assert irn_loc.size == jcn_loc.size self._refs.update(irn_loc=irn_loc, jcn_loc=jcn_l...
Set the distributed assembled matrix row & column numbers. Distributed assembled matrices require setting icntl(18) != 0.
def tmpl_asciify(text): """ * synopsis: ``%asciify{text}`` * description: Translate non-ASCII characters to their ASCII \ equivalents. For example, “café” becomes “cafe”. Uses the mapping \ provided by the unidecode module. """ ger_umlaute = {'ae': u'ä', ...
* synopsis: ``%asciify{text}`` * description: Translate non-ASCII characters to their ASCII \ equivalents. For example, “café” becomes “cafe”. Uses the mapping \ provided by the unidecode module.
def _parse_args(): """ Parse the command line for options """ parser = optparse.OptionParser() parser.add_option( '--user', dest='user_install', action='store_true', default=False, help='install in user site package (requires Python 2.6 or later)') parser.add_option( '--d...
Parse the command line for options
def chain(self, token: 'CancelToken') -> 'CancelToken': """ Return a new CancelToken chaining this and the given token. The new CancelToken's triggered will return True if trigger() has been called on either of the chained tokens, but calling trigger() on the new token has no ef...
Return a new CancelToken chaining this and the given token. The new CancelToken's triggered will return True if trigger() has been called on either of the chained tokens, but calling trigger() on the new token has no effect on either of the chained tokens.
def fetch_txs_rpc( self, bitcoind_opts, txids ): """ Fetch the given list of transactions via the JSON-RPC interface. Return a dict of parsed transactions on success, keyed by txid. Return None on error """ headers = {'content-type': 'application/json'}...
Fetch the given list of transactions via the JSON-RPC interface. Return a dict of parsed transactions on success, keyed by txid. Return None on error
def market_buy(self, security, amount, ttype=None, **kwargs): """ 市价买入 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余...
市价买入 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'}
def push_to_registry(self, image, image_tag: str): """ Pushes a local image to a registry based on the ``use_registry_name`` setting. :type image: docker.models.images.Image :raise PushToRegistryError: If the push fails. """ # already tagged, so it's already pushed if f"...
Pushes a local image to a registry based on the ``use_registry_name`` setting. :type image: docker.models.images.Image :raise PushToRegistryError: If the push fails.
def _get_provisioning_state(self, response): """ Attempt to get provisioning state from resource. :param requests.Response response: latest REST call response. :returns: Status if found, else 'None'. """ if self._is_empty(response): return None body = ...
Attempt to get provisioning state from resource. :param requests.Response response: latest REST call response. :returns: Status if found, else 'None'.
def augpath(path, suffix='', prefix='', ext=None, base=None, multidot=False): """ Augments a path with a new basename, extension, prefix and/or suffix. A prefix is inserted before the basename. A suffix is inserted between the basename and the extension. The basename and extension can be replaced w...
Augments a path with a new basename, extension, prefix and/or suffix. A prefix is inserted before the basename. A suffix is inserted between the basename and the extension. The basename and extension can be replaced with a new one. Args: path (PathLike): string representation of a path ...
def run_option_hooks(parser, disable_missing=True): """ Executes registered plugins using option hooks for the provided ``SettingParser`` instance. `parser` ``SettingParser`` instance. `disable_missing` Set to ``True`` to disable any plugins using option hooks whose ...
Executes registered plugins using option hooks for the provided ``SettingParser`` instance. `parser` ``SettingParser`` instance. `disable_missing` Set to ``True`` to disable any plugins using option hooks whose defined option hooks are not available in the da...
def _get_tab_zpe(cls): """Generate and return the COBS ZPE table.""" if not cls._tabs['dec_cobs_zpe']: # Compute the COBS ZPE table for decoding cls._tabs['dec_cobs_zpe']['\xe0'] = (224, '') cls._tabs['dec_cobs_zpe'].update(dict((chr(l), (l, '\0')) ...
Generate and return the COBS ZPE table.
def amplifier_gain(self, channels=None): """ Get the amplifier gain used for the specified channel(s). The amplifier gain for channel "n" is extracted from the $PnG parameter, if available. Parameters ---------- channels : int, str, list of int, list of str ...
Get the amplifier gain used for the specified channel(s). The amplifier gain for channel "n" is extracted from the $PnG parameter, if available. Parameters ---------- channels : int, str, list of int, list of str Channel(s) for which to get the amplifier gain. If No...
def write_single_coil(self, bit_addr, bit_value): """Modbus function WRITE_SINGLE_COIL (0x05) :param bit_addr: bit address (0 to 65535) :type bit_addr: int :param bit_value: bit value to write :type bit_value: bool :returns: True if write ok or None if fail :rtyp...
Modbus function WRITE_SINGLE_COIL (0x05) :param bit_addr: bit address (0 to 65535) :type bit_addr: int :param bit_value: bit value to write :type bit_value: bool :returns: True if write ok or None if fail :rtype: bool or None
def wait_for_web_available(self): """ Wait for the web server to become available or raise DatacatsError if it fails to start. """ try: if not wait_for_service_available( self._get_container_name('web'), self.web_address(), ...
Wait for the web server to become available or raise DatacatsError if it fails to start.
def messageReceived(self, message): """ Called on incoming message from ZeroMQ. Dispatches message to back to the requestor. :param message: message data """ msgId, msg = message[0], message[2:] self._releaseId(msgId) d, canceller = self._requests.pop(ms...
Called on incoming message from ZeroMQ. Dispatches message to back to the requestor. :param message: message data
def add_analyses(cls, source): """Dynamically add new analysis methods to the Timeseries class. Args: source: Can be a function, module or the filename of a python file. If a filename or a module is given, then all functions defined inside not starting with _ will be a...
Dynamically add new analysis methods to the Timeseries class. Args: source: Can be a function, module or the filename of a python file. If a filename or a module is given, then all functions defined inside not starting with _ will be added as methods. The only restric...
def cli(env, identifier, count): """Get details for a ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count))
Get details for a ticket.
def view_slow_sources(token, dstore, maxrows=20): """ Returns the slowest sources """ info = dstore['source_info'].value info.sort(order='calc_time') return rst_table(info[::-1][:maxrows])
Returns the slowest sources
def sigmoid_cross_entropy_one_hot(logits, labels, weights_fn=None): """Calculate sigmoid cross entropy for one-hot lanels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels and...
Calculate sigmoid cross entropy for one-hot lanels and logits. Args: logits: Tensor of size [batch-size, o=1, p=1, num-classes] labels: Tensor of size [batch-size, o=1, p=1, num-classes] weights_fn: Function that takes in labels and weighs examples (unused) Returns: cross_entropy (scalar), weights
def respond_webhook(self, environ): """ Passes the request onto a bot with a webhook if the webhook path is requested. """ request = FieldStorage(fp=environ["wsgi.input"], environ=environ) url = environ["PATH_INFO"] params = dict([(k, request[k].value) for k in re...
Passes the request onto a bot with a webhook if the webhook path is requested.
def get_blocks_byte_array(self, buffer=False): """Return a list of all blocks in this chunk.""" if buffer: length = len(self.blocksList) return BytesIO(pack(">i", length)+self.get_blocks_byte_array()) else: return array.array('B', self.blocksList).tostring()
Return a list of all blocks in this chunk.
def ready_nodes_iter(self, graph_copy): """Generate ready targets from the graph `graph_copy`. The input graph is mutated by this method, so it has to be a mutable copy of the graph (e.g. not original copy, or read-only view). Caller **must** call `done()` after processing every genera...
Generate ready targets from the graph `graph_copy`. The input graph is mutated by this method, so it has to be a mutable copy of the graph (e.g. not original copy, or read-only view). Caller **must** call `done()` after processing every generated target, so additional ready targets can...
def get_modules(): ''' List available ``eselect`` modules. CLI Example: .. code-block:: bash salt '*' eselect.get_modules ''' modules = [] module_list = exec_action('modules', 'list', action_parameter='--only-names') if not module_list: return None for module in m...
List available ``eselect`` modules. CLI Example: .. code-block:: bash salt '*' eselect.get_modules
def tsToDf(tso): """ Create Pandas DataFrame from TimeSeries object. Use: Must first extractTs to get a time series. Then pick one item from time series and pass it through :param dict tso: Time series entry :return dict dfs: Pandas dataframes """ dfs = {} try: dfs = ts_to_df(ts...
Create Pandas DataFrame from TimeSeries object. Use: Must first extractTs to get a time series. Then pick one item from time series and pass it through :param dict tso: Time series entry :return dict dfs: Pandas dataframes
def get_avatar_metadata(self): """Gets the metadata for an asset. return: (osid.Metadata) - metadata for the asset *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template meta...
Gets the metadata for an asset. return: (osid.Metadata) - metadata for the asset *compliance: mandatory -- This method must be implemented.*
def track_event(user_id, event_name, properties): """ Emit a track event to segment (and forwarded to GA) for some parts of the Enterprise workflows. """ # Only call the endpoint if the import was successful. if segment: segment.track(user_id, event_name, properties)
Emit a track event to segment (and forwarded to GA) for some parts of the Enterprise workflows.
def force_delete_key(address): """ Delete the key from the keyring and the Key and Address objects from the database """ address_object = Address.objects.get(address=address) address_object.key.delete() address_object.delete()
Delete the key from the keyring and the Key and Address objects from the database
def _int_from_str(string): """ Convert string into integer Raise: TypeError if string is not a valid integer """ float_num = float(string) int_num = int(float_num) if float_num == int_num: return int_num else: # Needed to handle pseudos with fractional charge ...
Convert string into integer Raise: TypeError if string is not a valid integer
def _create_http_basic_session(self, username, password, timeout=None): """ Creates a basic http session. :param username: Username for the session :type username: str :param password: Password for the username :type password: str :param timeout: If set determines the ti...
Creates a basic http session. :param username: Username for the session :type username: str :param password: Password for the username :type password: str :param timeout: If set determines the timeout period for the Session. :type timeout: Optional[int] :rtype: ...
def build_rule(cls, rule, method=None): """Creates a routing rule based on either the class name (minus the 'View' suffix) or the defined `base_route` attribute of the class :param rule: the path portion that should be appended to the route base :param method: if a...
Creates a routing rule based on either the class name (minus the 'View' suffix) or the defined `base_route` attribute of the class :param rule: the path portion that should be appended to the route base :param method: if a method's arguments should be considered when ...
def delete(self, **kwargs): """Delete a resource by issuing a DELETE http request against it.""" self.method = 'delete' if len(kwargs) > 0: self.load(self.client.delete(self.url, params=kwargs)) else: self.load(self.client.delete(self.url)) self.parent.rem...
Delete a resource by issuing a DELETE http request against it.
def file_key_regenerate( blockchain_id, hostname, config_path=CONFIG_PATH, wallet_keys=None ): """ Generate a new encryption key. Retire the existing key, if it exists. Return {'status': True} on success Return {'error': ...} on error """ config_dir = os.path.dirname(config_path) cu...
Generate a new encryption key. Retire the existing key, if it exists. Return {'status': True} on success Return {'error': ...} on error
def create_shipment(self, data=None): """Create a shipment for an order. When no data arg is given, a shipment for all order lines is assumed.""" if data is None: data = {'lines': []} return Shipments(self.client).on(self).create(data)
Create a shipment for an order. When no data arg is given, a shipment for all order lines is assumed.
def _initialize(self, device_description, permitted_ips): """ :type device_description: str :type permitted_ips: list[str] :rtype: None """ self._initialize_installation() self._register_device(device_description, permitted_ips) self._initialize_session(...
:type device_description: str :type permitted_ips: list[str] :rtype: None
def decoherence_noise_with_asymmetric_ro(gates: Sequence[Gate], p00=0.975, p11=0.911): """Similar to :py:func:`_decoherence_noise_model`, but with asymmetric readout. For simplicity, we use the default values for T1, T2, gate times, et al. and only allow the specification of readout fidelities. """ ...
Similar to :py:func:`_decoherence_noise_model`, but with asymmetric readout. For simplicity, we use the default values for T1, T2, gate times, et al. and only allow the specification of readout fidelities.
def __unget_service_from_factory(self, bundle, reference, service=None): # type: (Any, ServiceReference, Any) -> bool """ Removes the usage of a a service factory or a prototype service factory by a bundle :param bundle: The bundle that used the service :param reference:...
Removes the usage of a a service factory or a prototype service factory by a bundle :param bundle: The bundle that used the service :param reference: A service reference :param service: Service instance (for prototype factories) :return: True if the bundle usage has been removed
def _apply_rewrites(date_classes, rules): """ Return a list of date elements by applying rewrites to the initial date element list """ for rule in rules: date_classes = rule.execute(date_classes) return date_classes
Return a list of date elements by applying rewrites to the initial date element list
def ancestors(self, node): """Returns set of the ancestors of a node as DAGNodes.""" if isinstance(node, int): warnings.warn('Calling ancestors() with a node id is deprecated,' ' use a DAGNode instead', DeprecationWarning, 2) no...
Returns set of the ancestors of a node as DAGNodes.
def get_project(self, locale, source_language_code=DEFAULT_SOURCE_LANGUAGE, **kwargs): """ Gets or creates the Transifex project for the current project prefix and locale :param locale: A locale to which content is to be translated :type locale: string :param source_language_cod...
Gets or creates the Transifex project for the current project prefix and locale :param locale: A locale to which content is to be translated :type locale: string :param source_language_code: The language of the original untranslated content (i.e. Spanish), defaults to DEFAULT_SOURCE...
def get_policy_definitions(settings): """Find all multiauth policy definitions from the settings dict. This function processes the paster deployment settings looking for items that start with "multiauth.policy.<policyname>.". It pulls them all out into a dict indexed by the policy name. """ po...
Find all multiauth policy definitions from the settings dict. This function processes the paster deployment settings looking for items that start with "multiauth.policy.<policyname>.". It pulls them all out into a dict indexed by the policy name.
def send_requests(self, *args): """ Send a set of requests. Each request is sent over its own connection and the function will return when all the requests have been fulfilled. """ threads = [ClientThread(self, req) for req in args] for t in threads: ...
Send a set of requests. Each request is sent over its own connection and the function will return when all the requests have been fulfilled.
def artist_commentary_create_update(self, post_id, original_title, original_description, translated_title, translated_description): """Create or update artist commentary (Requires login) (UNTESTED). Parameters: ...
Create or update artist commentary (Requires login) (UNTESTED). Parameters: post_id (int): Post id. original_title (str): Original title. original_description (str): Original description. translated_title (str): Translated title. translated_descriptio...
def _names(section, option): """List of cli strings for a given option.""" meta = section.def_[option] action = meta.cmd_kwargs.get('action') if action is internal.Switch: names = ['-{}'.format(option), '+{}'.format(option)] if meta.shortname is not None: names.append('-{}'.f...
List of cli strings for a given option.
def try_next(self): """Advance the cursor without blocking indefinitely. This method returns the next change document without waiting indefinitely for the next change. For example:: with db.collection.watch() as stream: while stream.alive: change...
Advance the cursor without blocking indefinitely. This method returns the next change document without waiting indefinitely for the next change. For example:: with db.collection.watch() as stream: while stream.alive: change = stream.try_next() ...
def peek(self, storagemodel:object, modeldefinition = None) -> StorageQueueModel: """ lookup the next message in queue """ try: messages = modeldefinition['queueservice'].peek_messages(storagemodel._queuename, num_messages=1) """ parse retrieved message """ for mess...
lookup the next message in queue
def load_dataset(self, dataset, verbose=True): """ Load a directory of gnt files. Yields the image and label in tuples. :param dataset: The directory to load. :return: Yields (Pillow.Image.Image, label) pairs. """ assert self.get_dataset(dataset) is True, "Datasets aren'...
Load a directory of gnt files. Yields the image and label in tuples. :param dataset: The directory to load. :return: Yields (Pillow.Image.Image, label) pairs.
def delete(): """Deletes local XML file""" path = cache.local_path( filename=ALLELE_XML_FILENAME, url=ALLELE_XML_URL, decompress=ALLELE_XML_DECOMPRESS) os.remove(path)
Deletes local XML file