positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _analyse_overview_field(content): ''' Split the field in drbd-overview ''' if "(" in content: # Output like "Connected(2*)" or "UpToDate(2*)" return content.split("(")[0], content.split("(")[0] elif "/" in content: # Output like "Primar/Second" or "UpToDa/UpToDa" ...
Split the field in drbd-overview
def trigger(self, event, *args): """Triggers the specified event by invoking EventHook.trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used ...
Triggers the specified event by invoking EventHook.trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param args: event arg...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word if hasattr(self, 'sounds_like') and self.sounds_like is not None: _dict['sounds_like'] = self.sound...
Return a json dictionary representing this model.
def get_app_ext(self, loops=float('inf')): """ get_app_ext(loops=float('inf')) Application extention. This part specifies the amount of loops. If loops is 0 or inf, it goes on infinitely. """ if loops == 0 or loops == float('inf'): loops = 2**16 - 1 # b...
get_app_ext(loops=float('inf')) Application extention. This part specifies the amount of loops. If loops is 0 or inf, it goes on infinitely.
def sample(self, sample_indices=None, num_samples=1): """ returns samples according to the KDE Parameters ---------- sample_inices: list of ints Indices into the training data used as centers for the samples num_samples: int if samples_indices is None, this specifies how many samples ...
returns samples according to the KDE Parameters ---------- sample_inices: list of ints Indices into the training data used as centers for the samples num_samples: int if samples_indices is None, this specifies how many samples are drawn.
def GetInput(self): """Yield client urns.""" client_list = GetAllClients(token=self.token) logging.debug("Got %d clients", len(client_list)) for client_group in collection.Batch(client_list, self.client_chunksize): for fd in aff4.FACTORY.MultiOpen( client_group, mode="r", ...
Yield client urns.
def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_blade_swbd(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status") config = logical_chassis_fwdl_status outpu...
Auto Generated Code
def list_all(self): """All items""" return list(set( item for items in self._routes.values() for item in items ))
All items
def p_block(p): """block : '{' commands '}' """ # section 3.2: REQUIRE command must come before any other commands, # which means it can't be in the block of another command if any(command.RULE_IDENTIFIER == 'REQUIRE' for command in p[2].commands): print("REQUIRE command not allowed i...
block : '{' commands '}'
def printMetaDataFor(archive, location): """ Prints metadata for given location. :param archive: CombineArchive instance :param location: :return: """ desc = archive.getMetadataForLocation(location) if desc.isEmpty(): print(" no metadata for '{0}'".format(location)) return ...
Prints metadata for given location. :param archive: CombineArchive instance :param location: :return:
def do_parameter(self,args): """Print a parameter""" parser = CommandArgumentParser("parameter") parser.add_argument(dest="id",help="Parameter to print") args = vars(parser.parse_args(args)) print "printing parameter {}".format(args['id']) try: index ...
Print a parameter
def configure_app(app): """Configure Flask/Celery application. * Rio will find environment variable `RIO_SETTINGS` first:: $ export RIO_SETTINGS=/path/to/settings.cfg $ rio worker * If `RIO_SETTINGS` is missing, Rio will try to load configuration module in `rio.settings` according t...
Configure Flask/Celery application. * Rio will find environment variable `RIO_SETTINGS` first:: $ export RIO_SETTINGS=/path/to/settings.cfg $ rio worker * If `RIO_SETTINGS` is missing, Rio will try to load configuration module in `rio.settings` according to another environment var...
def windows_install(path_to_python=""): """ Sets the .py extension to be associated with the ftype Python which is then set to the python.exe you provide in the path_to_python variable or after the -p flag if run as a script. Once the python environment is set up the function proceeds to set PATH an...
Sets the .py extension to be associated with the ftype Python which is then set to the python.exe you provide in the path_to_python variable or after the -p flag if run as a script. Once the python environment is set up the function proceeds to set PATH and PYTHONPATH using setx. Parameters -------...
def get_item_sh(self, item, roles=None, date_field=None): """Add sorting hat enrichment fields""" eitem_sh = {} created = str_to_datetime(date_field) for rol in roles: identity = self.get_sh_identity(item, rol) eitem_sh.update(self.get_item_sh_fields(identity, c...
Add sorting hat enrichment fields
def slicer(document, first_page=None, last_page=None, suffix='sliced', tempdir=None): """Slice a PDF document to remove pages.""" # Set output file name if tempdir: with NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False) as temp: output = temp.name elif suffix: outp...
Slice a PDF document to remove pages.
def decoded_output_boxes(self): """ Returns: Nx#classx4 """ ret = self._cascade_boxes[-1] ret = tf.expand_dims(ret, 1) # class-agnostic return tf.tile(ret, [1, self.num_classes, 1])
Returns: Nx#classx4
def release_to_branch(self, release_id): """ Shortcut to translate a release identifier to a branch name. :param release_id: A :attr:`Release.identifier` value (a string). :returns: A branch name (a string). :raises: :exc:`~exceptions.TypeError` when :attr:`release_scheme` isn't...
Shortcut to translate a release identifier to a branch name. :param release_id: A :attr:`Release.identifier` value (a string). :returns: A branch name (a string). :raises: :exc:`~exceptions.TypeError` when :attr:`release_scheme` isn't 'branches'.
def _setup_gc2_framework(self): """ This method establishes the GC2 framework for a multi-segment (and indeed multi-typology) case based on the description in Spudich & Chiou (2015) - see section on Generalized Coordinate System for Multiple Rupture Traces """ # G...
This method establishes the GC2 framework for a multi-segment (and indeed multi-typology) case based on the description in Spudich & Chiou (2015) - see section on Generalized Coordinate System for Multiple Rupture Traces
def _read_msg(self): """read message from server""" # # NOTE: # '_recv_socket(nbytes)' was implemented as # 'socket.recv(nbytes, socket.MSG_WAITALL)' # but socket.MSG_WAITALL proved not reliable # def _recv_socket(nbytes): """read nbytes byte...
read message from server
def airline_delay(data_set='airline_delay', num_train=700000, num_test=100000, seed=default_seed): """Airline delay data used in Gaussian Processes for Big Data by Hensman, Fusi and Lawrence""" if not data_available(data_set): download_data(data_set) dir_path = os.path.join(data_path, data_set) ...
Airline delay data used in Gaussian Processes for Big Data by Hensman, Fusi and Lawrence
def get_job_list(self, project_name): """ Get the list of pending, running and finished jobs of some project. :param project_name: the project name :return: a dictionary that list inculde job name and status example: {"status": "ok", ...
Get the list of pending, running and finished jobs of some project. :param project_name: the project name :return: a dictionary that list inculde job name and status example: {"status": "ok", "pending": [{"id": "78391cc0fcaf11e1b0090800272a6d06", "sp...
def visit_keyword(self, node): """return an astroid.Keyword node as string""" if node.arg is None: return "**%s" % node.value.accept(self) return "%s=%s" % (node.arg, node.value.accept(self))
return an astroid.Keyword node as string
def cutoff_filename(prefix, suffix, input_str): """ Cuts off the start and end of a string, as specified by 2 parameters Parameters ---------- prefix : string, if input_str starts with prefix, will cut off prefix suffix : string, if input_str end with suffix, will cut off suffix input_str :...
Cuts off the start and end of a string, as specified by 2 parameters Parameters ---------- prefix : string, if input_str starts with prefix, will cut off prefix suffix : string, if input_str end with suffix, will cut off suffix input_str : the string to be processed Returns ------- A s...
def delete_namespace(parsed_xml): """ Identifies the namespace associated with the root node of a XML document and removes that names from the document. :param parsed_xml: lxml.Etree object. :return: Returns the sources document with the namespace removed. """ if parsed_xml.getroot().tag.st...
Identifies the namespace associated with the root node of a XML document and removes that names from the document. :param parsed_xml: lxml.Etree object. :return: Returns the sources document with the namespace removed.
def select_many_with_index( self, collection_selector=IndexedElement, result_selector=lambda source_element, collection_element: collection_element): '''Projects each element of a sequence to an intermediate new sequence, incorporati...
Projects each element of a sequence to an intermediate new sequence, incorporating the index of the element, flattens the resulting sequence into one sequence and optionally transforms the flattened sequence using a selector function. Note: This method uses deferred execution. ...
def draw(self): ''' Draws samples from the `true` distribution. Returns: `np.ndarray` of samples. ''' observed_arr = self.__image_true_sampler.draw() observed_arr = self.add_condition(observed_arr) return observed_arr
Draws samples from the `true` distribution. Returns: `np.ndarray` of samples.
def _scale_back_response(bqm, response, scalar, ignored_interactions, ignored_variables, ignore_offset): """Helper function to scale back the response of sample method""" if len(ignored_interactions) + len( ignored_variables) + ignore_offset == 0: response.record.ene...
Helper function to scale back the response of sample method
def file_exists(self, filename, shutit_pexpect_child=None, directory=False, note=None, loglevel=logging.DEBUG): """Return True if file exists on the target host, else False @param filename: Filename to determine the existence of...
Return True if file exists on the target host, else False @param filename: Filename to determine the existence of. @param shutit_pexpect_child: See send() @param directory: Indicate that the file is a directory. @param note: See send() @type filename: string @type directory: boolean ...
def stream(self, status=values.unset, phone_number=values.unset, incoming_phone_number_sid=values.unset, friendly_name=values.unset, unique_name=values.unset, limit=None, page_size=None): """ Streams DependentHostedNumberOrderInstance records from the API as a generator str...
Streams DependentHostedNumberOrderInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param DependentHostedNumberO...
def remover_grupo(self, id_equipamento, id_grupo): """Remove a associação de um equipamento com um grupo de equipamento. :param id_equipamento: Identificador do equipamento. :param id_grupo: Identificador do grupo de equipamento. :return: None :raise EquipamentoGrupoNaoExisteE...
Remove a associação de um equipamento com um grupo de equipamento. :param id_equipamento: Identificador do equipamento. :param id_grupo: Identificador do grupo de equipamento. :return: None :raise EquipamentoGrupoNaoExisteError: Associação entre grupo e equipamento não cadastrada. ...
def list_check(*args, func=None): """Check if arguments are list type.""" func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (list, collections.UserList, collections.abc.MutableSequence)): name = type(var).__name__ raise ListError( f'...
Check if arguments are list type.
def _check_wait_input_flag(self): """ Returns a function to stop the search of the investigated node of the ArciDispatch algorithm. :return: A function to stop the search. :rtype: (bool, str) -> bool """ wf_pred = self._wf_pred # Namespace shortcuts...
Returns a function to stop the search of the investigated node of the ArciDispatch algorithm. :return: A function to stop the search. :rtype: (bool, str) -> bool
def process_module(self, yam): """Process data nodes, RPCs and notifications in a single module.""" for ann in yam.search(("ietf-yang-metadata", "annotation")): self.process_annotation(ann) for ch in yam.i_children[:]: if ch.keyword == "rpc": self.process_...
Process data nodes, RPCs and notifications in a single module.
def forward_all_signals_async(target_pid, process_name): """Install all signal handler that forwards all signals to the given process.""" def forwarding_signal_handler(signum): _forward_signal(signum, process_name, forwarding_signal_handler.target_pid) # Somehow we get a Python SystemError sometime...
Install all signal handler that forwards all signals to the given process.
def sudo_required(func): """ Enforces a view to have elevated privileges. Should likely be paired with ``@login_required``. >>> @sudo_required >>> def secure_page(request): >>> ... """ @wraps(func) def inner(request, *args, **kwargs): if not request.is_sudo(): ...
Enforces a view to have elevated privileges. Should likely be paired with ``@login_required``. >>> @sudo_required >>> def secure_page(request): >>> ...
def is_expired(self): """ ``True`` if the signature has an expiration date, and is expired. Otherwise, ``False`` """ expires_at = self.expires_at if expires_at is not None and expires_at != self.created: return expires_at < datetime.utcnow() return False
``True`` if the signature has an expiration date, and is expired. Otherwise, ``False``
def overlay_gateway_access_lists_ipv6_in_cg_ipv6_acl_in_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway...
Auto Generated Code
async def Create(self, notes): ''' notes : str Returns -> typing.Union[str, int, _ForwardRef('Number')] ''' # map input types to rpc msg _params = dict() msg = dict(type='Backups', request='Create', version=2, ...
notes : str Returns -> typing.Union[str, int, _ForwardRef('Number')]
def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) ...
Destroy the named VMs
def _parse_storage_embedded_health(self, data): """Gets the storage data from get_embedded_health Parse the get_host_health_data() for essential properties :param data: the output returned by get_host_health_data() :returns: disk size in GB. """ local_gb = 0 st...
Gets the storage data from get_embedded_health Parse the get_host_health_data() for essential properties :param data: the output returned by get_host_health_data() :returns: disk size in GB.
def full(self, name, fill_value, **kwargs): """Create an array. Keyword arguments as per :func:`zarr.creation.full`.""" return self._write_op(self._full_nosync, name, fill_value, **kwargs)
Create an array. Keyword arguments as per :func:`zarr.creation.full`.
def watch_logfile(self, logfile_path): """Analyzes queries from the tail of a given log file""" self._run_stats['logSource'] = logfile_path log_parser = LogParser() # For each new line in the logfile ... output_time = time.time() + WATCH_DISPLAY_REFRESH_SECONDS try: ...
Analyzes queries from the tail of a given log file
def min(self, spec): """Adds `min` operator that specifies lower bound for specific index. :Parameters: - `spec`: a list of field, limit pairs specifying the inclusive lower bound for all keys of a specific index in order. .. versionadded:: 2.7 """ if not ...
Adds `min` operator that specifies lower bound for specific index. :Parameters: - `spec`: a list of field, limit pairs specifying the inclusive lower bound for all keys of a specific index in order. .. versionadded:: 2.7
def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :pa...
List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace...
def key_by(self, to_key: Callable[[T], str]) -> 'TDict[T]': """ :param to_key: value -> key Usage: >>> TList(['a1', 'b2', 'c3']).key_by(lambda x: x[0]).to_json() '{"a": "a1","b": "b2","c": "c3"}' >>> TList([1, 2, 3, 4, 5]).key_by(lambda x: x % 2).to_json() ...
:param to_key: value -> key Usage: >>> TList(['a1', 'b2', 'c3']).key_by(lambda x: x[0]).to_json() '{"a": "a1","b": "b2","c": "c3"}' >>> TList([1, 2, 3, 4, 5]).key_by(lambda x: x % 2).to_json() '{"0": 4,"1": 5}'
def get_copy_token( self, bucket: str, key: str, cloud_checksum: str, ) -> typing.Any: """ Given a bucket, key, and the expected cloud-provided checksum, retrieve a token that can be passed into :func:`~cloud_blobstore.BlobStore.copy` that guar...
Given a bucket, key, and the expected cloud-provided checksum, retrieve a token that can be passed into :func:`~cloud_blobstore.BlobStore.copy` that guarantees the copy refers to the same version of the blob identified by the checksum. :param bucket: the bucket the object resides in. :pa...
def get_index_translog_disable_flush(self): """Return a dictionary showing the position of the 'translog.disable_flush' knob for each index in the cluster. The dictionary will look like this: { "index1": True, # Autoflushing DISABLED "index2": ...
Return a dictionary showing the position of the 'translog.disable_flush' knob for each index in the cluster. The dictionary will look like this: { "index1": True, # Autoflushing DISABLED "index2": False, # Autoflushing ENABLED "inde...
def get_smtp_mail(self): """ Returns the SMTP formatted email, as it may be passed to sendmail. :rtype: string :return: The SMTP formatted mail. """ header = self.get_smtp_header() body = self.get_body().replace('\n', '\r\n') return header + '\r\n' + bod...
Returns the SMTP formatted email, as it may be passed to sendmail. :rtype: string :return: The SMTP formatted mail.
def roll_mean(input, window): '''Apply a rolling mean function to an array. This is a simple rolling aggregation.''' nobs, i, j, sum_x = 0,0,0,0. N = len(input) if window > N: raise ValueError('Out of bound') output = np.ndarray(N-window+1,dtype=input.dtype) for val in inpu...
Apply a rolling mean function to an array. This is a simple rolling aggregation.
def set_unbind(self): """ Unsets key bindings. """ self.unbind('<Button-1>') self.unbind('<Button-3>') self.unbind('<Up>') self.unbind('<Down>') self.unbind('<Shift-Up>') self.unbind('<Shift-Down>') self.unbind('<Control-Up>') self....
Unsets key bindings.
def clean_storage(block_device): ''' Ensures a block device is clean. That is: - unmounted - any lvm volume groups are deactivated - any lvm physical device signatures removed - partition table wiped :param block_device: str: Full path to block device to clean. ''' ...
Ensures a block device is clean. That is: - unmounted - any lvm volume groups are deactivated - any lvm physical device signatures removed - partition table wiped :param block_device: str: Full path to block device to clean.
def _get_row_str(self, i): """ Returns a string representation of the key information in a row """ row_data = ["{:s}".format(self.data['eventID'][i]), "{:g}".format(self.data['year'][i]), "{:g}".format(self.data['month'][i]), "{...
Returns a string representation of the key information in a row
def publish(context): """Publishes the project""" commit_version_change(context) if context.github: # github token project_settings = project_config(context.module_name) if not project_settings['gh_token']: click.echo('You need a GitHub token for changes to create a rele...
Publishes the project
def get_activities_for_objectives(self, objective_ids=None): """Gets the activities for the given objectives. In plenary mode, the returned list contains all of the activities specified in the objective Id list, in the order of the list, including duplicates, or an error results if a cou...
Gets the activities for the given objectives. In plenary mode, the returned list contains all of the activities specified in the objective Id list, in the order of the list, including duplicates, or an error results if a course offering Id in the supplied list is not found or inaccessibl...
def clone(self, substitutions, commit=True, **kwargs): """ Clone a DAG, optionally skipping the commit. """ return self.store.clone(substitutions, **kwargs)
Clone a DAG, optionally skipping the commit.
def _handle_client_error(): """ Handle boto exception and convert to class IO exceptions Raises: OSError subclasses: IO error. """ try: yield except _ClientError as exception: error = exception.response['Error'] if error['Code'] in _ERROR_CODES: ...
Handle boto exception and convert to class IO exceptions Raises: OSError subclasses: IO error.
async def system_bus_async(loop = None, **kwargs) : "returns a Connection object for the D-Bus system bus." return \ Connection \ ( await dbus.Connection.bus_get_async(DBUS.BUS_SYSTEM, private = False, loop = loop) ) \ .register_additional_standard(**kwargs)
returns a Connection object for the D-Bus system bus.
def from_series(self, series, add_index_column=True): """ Set tabular attributes to the writer from :py:class:`pandas.Series`. Following attributes are set by the method: - :py:attr:`~.headers` - :py:attr:`~.value_matrix` - :py:attr:`~.type_hints` Ar...
Set tabular attributes to the writer from :py:class:`pandas.Series`. Following attributes are set by the method: - :py:attr:`~.headers` - :py:attr:`~.value_matrix` - :py:attr:`~.type_hints` Args: series(pandas.Series): Input pandas.Series...
def get_v_total_stress_at_depth(self, z): """ Determine the vertical total stress at depth z, where z can be a number or an array of numbers. """ if not hasattr(z, "__len__"): return self.one_vertical_total_stress(z) else: sigma_v_effs = [] fo...
Determine the vertical total stress at depth z, where z can be a number or an array of numbers.
def get(self, timeout=None, block=True, throw_dead=True): """ Sleep waiting for a message to arrive on this receiver. :param float timeout: If not :data:`None`, specifies a timeout in seconds. :raises mitogen.core.ChannelError: The remote end indicated the chann...
Sleep waiting for a message to arrive on this receiver. :param float timeout: If not :data:`None`, specifies a timeout in seconds. :raises mitogen.core.ChannelError: The remote end indicated the channel should be closed, communication with it was lost, or :meth:`clo...
def pairedBEDIterator(inputStreams, mirror=False, mirrorScore=None, ignoreStrand=False, ignoreScore=True, ignoreName=True, sortedby=ITERATOR_SORTED_END, scoreType=float, verbose=False): """ Iterate over multiple BED format files simultaneously and yi...
Iterate over multiple BED format files simultaneously and yield lists of genomic intervals for each matching set of intervals found. By default, regions which are not found in all files will be skipped (mirror = false). Optionally (by setting mirror to true) if a file is missing an interval, it can be added on-...
def parse_annotation(code): """Parse an annotation string. Return an AST Expr node. code: annotation string (excluding '@') """ module = ast.parse(code) assert type(module) is ast.Module, 'internal error #1' assert len(module.body) == 1, 'Annotation contains more than one expression' ass...
Parse an annotation string. Return an AST Expr node. code: annotation string (excluding '@')
def get_outfile(self, outfile, goids=None): """Return output file for GO Term plot.""" # 1. Use the user-specfied output filename for the GO Term plot if outfile != self.dflt_outfile: return outfile # 2. If only plotting 1 GO term, use GO is in plot name if goids is n...
Return output file for GO Term plot.
def completeness(self, delta, method='step'): """ Return the completeness as a function of magnitude. ADW: Eventually want a completeness mask to set overall efficiency. """ delta = np.asarray(delta) if method == 'step': func = lambda delta: (delta > 0).astyp...
Return the completeness as a function of magnitude. ADW: Eventually want a completeness mask to set overall efficiency.
def signout(self, redirect_url = "/"): """ 注销登录状态 参数: redirect_url 跳转链接,为 None 时不跳转 (Ajax 可能用得到)。 """ self.clear_cookie(self._USER_NAME) if redirect_url: self.redirect(redirect_url)
注销登录状态 参数: redirect_url 跳转链接,为 None 时不跳转 (Ajax 可能用得到)。
def getAsKmlPngAnimation(self, session, projectFile=None, path=None, documentName=None, colorRamp=None, alpha=1.0, noDataValue=0, drawOrder=0, cellSize=None, resampleMethod='NearestNeighbour'): """ Retrieve the WMS dataset as a PNG time stamped KMZ Args: ...
Retrieve the WMS dataset as a PNG time stamped KMZ Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database. projectFile(:class:`gsshapy.orm.ProjectFile`): Project file object for the GSSHA project to which the WMS dataset belong...
def select_enclosed_points(dataset, surface, tolerance=0.001, inside_out=False, check_surface=True): """Mark points as to whether they are inside a closed surface. This evaluates all the input points to determine whether they are in an enclosed surface. The filter produces a (0,1...
Mark points as to whether they are inside a closed surface. This evaluates all the input points to determine whether they are in an enclosed surface. The filter produces a (0,1) mask (in the form of a vtkDataArray) that indicates whether points are outside (mask value=0) or inside (mask ...
def pay_deliver_notify(self, **deliver_info): """ 通知 腾讯发货 一般形式 :: wxclient.pay_delivernotify( openid=openid, transid=transaction_id, out_trade_no=本地订单号, deliver_timestamp=int(time.time()), deliver_status...
通知 腾讯发货 一般形式 :: wxclient.pay_delivernotify( openid=openid, transid=transaction_id, out_trade_no=本地订单号, deliver_timestamp=int(time.time()), deliver_status="1", deliver_msg="ok" ) :par...
def draw_curve(self, grid_characters: BoxDrawCharacterSet, *, top: bool = False, left: bool = False, right: bool = False, bottom: bool = False, crossing_char: Optional[str] = None): ...
Draws lines in the box using the given character set. Supports merging the new lines with the lines from a previous call to draw_curve, including when they have different character sets (assuming there exist characters merging the two). Args: grid_characters: The character ...
def add_tags(self, archive_name, tags): ''' Add tags to an archive Parameters ---------- archive_name:s tr Name of archive tags: list or tuple of strings tags to add to the archive ''' updated_tag_list = list(self._get_tags(archi...
Add tags to an archive Parameters ---------- archive_name:s tr Name of archive tags: list or tuple of strings tags to add to the archive
def add_session(session=None): r"""Add a session to the SessionActivity table. :param session: Flask Session object to add. If None, ``session`` is used. The object is expected to have a dictionary entry named ``"user_id"`` and a field ``sid_s`` """ user_id, sid_s = session['user_id'], ...
r"""Add a session to the SessionActivity table. :param session: Flask Session object to add. If None, ``session`` is used. The object is expected to have a dictionary entry named ``"user_id"`` and a field ``sid_s``
def get_term_freq_df(self, label_append=' freq'): ''' Parameters ------- label_append : str Returns ------- pd.DataFrame indexed on terms, with columns giving frequencies for each ''' ''' row = self._row_category_ids() newX = csr_...
Parameters ------- label_append : str Returns ------- pd.DataFrame indexed on terms, with columns giving frequencies for each
def loadJSON(self, json_string): """ Sets the values of the run parameters given an JSON string """ g = get_root(self).globals user = json.loads(json_string)['user'] def setField(widget, field): val = user.get(field) if val is not None: ...
Sets the values of the run parameters given an JSON string
def _read_name_text( self, bufr, platform_id, encoding_id, strings_offset, name_str_offset, length): """ Return the unicode name string at *name_str_offset* or |None| if decoding its format is not supported. """ raw_name = self._raw_name_string( ...
Return the unicode name string at *name_str_offset* or |None| if decoding its format is not supported.
def data_not_in(db_data, user_data): """Validate data not in user data. Args: db_data (str): The data store in Redis. user_data (list): The user provided data. Returns: bool: True if the data passed validation. """ if isinstance(user_data, li...
Validate data not in user data. Args: db_data (str): The data store in Redis. user_data (list): The user provided data. Returns: bool: True if the data passed validation.
def tokenize(self, text): ''' tokenize function in Tokenizer. ''' start = -1 tokens = [] for i, character in enumerate(text): if character == ' ' or character == '\t': if start >= 0: word = text[start:i] ...
tokenize function in Tokenizer.
def _readbytes(self, length, start): """Read bytes and return them. Note that length is in bits.""" assert length % 8 == 0 assert start + length <= self.len if not (start + self._offset) % 8: return bytes(self._datastore.getbyteslice((start + self._offset) // 8, ...
Read bytes and return them. Note that length is in bits.
def visitSenseFlags(self, ctx: ShExDocParser.SenseFlagsContext): """ '!' '^'? | '^' '!'? """ if '!' in ctx.getText(): self.expression.negated = True if '^' in ctx.getText(): self.expression.inverse = True
'!' '^'? | '^' '!'?
def setExpertLevel(self): """ Set expert level """ g = get_root(self).globals level = g.cpars['expert_level'] # now set whether buttons are permanently enabled or not if level == 0 or level == 1: self.load.setNonExpert() self.save.setNonEx...
Set expert level
def get_position(self, dt): """Given dt in [0, 1], return the current position of the tile.""" return self.sx + self.dx * dt, self.sy + self.dy * dt
Given dt in [0, 1], return the current position of the tile.
def _guess_iface_name(netif): """ We attempt to guess the name of interfaces that are truncated from the output of ifconfig -l. If there is only one possible candidate matching the interface name then we return it. If there are none or more, then we return None. """ with os.popen('%s -l'...
We attempt to guess the name of interfaces that are truncated from the output of ifconfig -l. If there is only one possible candidate matching the interface name then we return it. If there are none or more, then we return None.
def sasdata2dataframe(self, table: str, libref: str = '', dsopts: dict = None, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame': """ This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object. SASdata object that refers to the Sas Da...
This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object. SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref f...
def history(self): """Returns an SQLAlchemy query of the object's history (previous versions). If the class does not support history/versioning, returns None. """ history = self.history_class if history: return self.session.query(history).filter(history.id == ...
Returns an SQLAlchemy query of the object's history (previous versions). If the class does not support history/versioning, returns None.
def get_field(name, data, default="object", document_object_field=None, is_document=False): """ Return a valid Field by given data """ if isinstance(data, AbstractField): return data data = keys_to_string(data) _type = data.get('type', default) if _type == "string": return St...
Return a valid Field by given data
def is_valid_bucket_notification_config(notifications): """ Validate the notifications config structure :param notifications: Dictionary with specific structure. :return: True if input is a valid bucket notifications structure. Raise :exc:`InvalidArgumentError` otherwise. """ # check if ...
Validate the notifications config structure :param notifications: Dictionary with specific structure. :return: True if input is a valid bucket notifications structure. Raise :exc:`InvalidArgumentError` otherwise.
def render(self, context): """Handle the actual rendering. """ user = self._get_value(self.user_key, context) feature = self._get_value(self.feature, context) if feature is None: return '' allowed = show_feature(user, feature) return self.nodelist.re...
Handle the actual rendering.
def to_posix_path(code_path): """ Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path. Parameters ---------- code_path : str Directory in the host operating system that should be mounted within the container. Returns ------- ...
Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path. Parameters ---------- code_path : str Directory in the host operating system that should be mounted within the container. Returns ------- str Posix equivalent of absolute ...
def fwdl_status_output_fwdl_entries_blade_slot(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fwdl_status = ET.Element("fwdl_status") config = fwdl_status output = ET.SubElement(fwdl_status, "output") fwdl_entries = ET.SubElement(output,...
Auto Generated Code
def forward_for_single_feature_map(self, anchors, objectness, box_regression): """ Arguments: anchors: list[BoxList] objectness: tensor of size N, A, H, W box_regression: tensor of size N, A * 4, H, W """ device = objectness.device N, A, H, W =...
Arguments: anchors: list[BoxList] objectness: tensor of size N, A, H, W box_regression: tensor of size N, A * 4, H, W
def _estimate_param_scan_worker(estimator, params, X, evaluate, evaluate_args, failfast, return_exceptions): """ Method that runs estimation for several parameter settings. Defined as a worker for parallelization """ # run estimation model = None try: # catch a...
Method that runs estimation for several parameter settings. Defined as a worker for parallelization
def _serialize_parameters(parameters): """Serialize some parameters to match python native types with formats specified in google api docs like: * True/False -> "true"/"false", * {"a": 1, "b":2} -> "a:1|b:2" :type parameters: dict oif query parameters """ for ke...
Serialize some parameters to match python native types with formats specified in google api docs like: * True/False -> "true"/"false", * {"a": 1, "b":2} -> "a:1|b:2" :type parameters: dict oif query parameters
def ndtr(a): """ Returns the area under the Gaussian probability density function, integrated from minus infinity to x. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ndtr.html#scipy.special.ndtr """ sqrth = math.sqrt(2) / 2 x = float(a) * sqrth z = abs(x) ...
Returns the area under the Gaussian probability density function, integrated from minus infinity to x. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ndtr.html#scipy.special.ndtr
def _runUnrealBuildTool(self, target, platform, configuration, args, capture=False): """ Invokes UnrealBuildTool with the specified parameters """ platform = self._transformBuildToolPlatform(platform) arguments = [self.getBuildScript(), target, platform, configuration] + args if capture == True: return U...
Invokes UnrealBuildTool with the specified parameters
def from_cn(cls, common_name): """ Retrieve a certificate by its common name. """ # search with cn result_cn = [(cert['id'], [cert['cn']] + cert['altnames']) for cert in cls.list({'status': ['pending', 'valid'], 'items_per_page': 50...
Retrieve a certificate by its common name.
def draw_bounding_boxes(images, annotations, confidence_threshold=0): """ Visualizes bounding boxes (ground truth or predictions) by returning annotated copies of the images. Parameters ---------- images: SArray or Image An `SArray` of type `Image`. A single `Image` instance may also be...
Visualizes bounding boxes (ground truth or predictions) by returning annotated copies of the images. Parameters ---------- images: SArray or Image An `SArray` of type `Image`. A single `Image` instance may also be given. annotations: SArray or list An `SArray` of annotation...
def unregister(self, command): """ Unregisters an existing command, so that this command is no longer available on the command line interface. This function is mainly used during plugin deactivation. :param command: Name of the command """ if command not in self._comman...
Unregisters an existing command, so that this command is no longer available on the command line interface. This function is mainly used during plugin deactivation. :param command: Name of the command
def enable_category(self, category: str) -> None: """ Enable an entire category of commands :param category: the category to enable """ for cmd_name in list(self.disabled_commands): func = self.disabled_commands[cmd_name].command_function if hasattr(func, ...
Enable an entire category of commands :param category: the category to enable
def update_registration(self, regr, uri=None): """ Submit a registration to the server to update it. :param ~acme.messages.RegistrationResource regr: The registration to update. Can be a :class:`~acme.messages.NewRegistration` instead, in order to create a new registrat...
Submit a registration to the server to update it. :param ~acme.messages.RegistrationResource regr: The registration to update. Can be a :class:`~acme.messages.NewRegistration` instead, in order to create a new registration. :param str uri: The url to submit to. Must be ...
def _iter_lexerclasses(plugins=True): """Return an iterator over all lexer classes.""" for key in sorted(LEXERS): module_name, name = LEXERS[key][:2] if name not in _lexer_cache: _load_lexers(module_name) yield _lexer_cache[name] if plugins: for lexer in find_plug...
Return an iterator over all lexer classes.
def remove(name=None, pkgs=None, **kwargs): ''' Remove the passed package(s) from the system using winrepo .. versionadded:: 0.16.0 Args: name (str): The name(s) of the package(s) to be uninstalled. Can be a single package or a comma delimited list of packages, no space...
Remove the passed package(s) from the system using winrepo .. versionadded:: 0.16.0 Args: name (str): The name(s) of the package(s) to be uninstalled. Can be a single package or a comma delimited list of packages, no spaces. pkgs (list): A list of packages ...