code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def create_context_store(name='default', ttl=settings.CONTEXT_DEFAULT_TTL, store=settings.CONTEXT_STORE) -> 'BaseContextStore': """ Create a context store. By default using the default configured context store, but you can use a custom class if you want to u...
Create a context store. By default using the default configured context store, but you can use a custom class if you want to using the `store` setting. The time to live of each store (aka there is one per conversation) is defined by the `ttl` value, which is also inferred by default from the config...
def query_artifacts(job_ids, log): """Query API again for artifacts. :param iter job_ids: List of AppVeyor jobIDs. :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: List of tuples: (job ID, artifact file name, artifact file size). :rtype: list """...
Query API again for artifacts. :param iter job_ids: List of AppVeyor jobIDs. :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: List of tuples: (job ID, artifact file name, artifact file size). :rtype: list
def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's rpm database (not generally recommended). root use root as top level directory (default: "/") CLI Examples: .. code-block...
List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's rpm database (not generally recommended). root use root as top level directory (default: "/") CLI Examples: .. code-block:: bash salt '*' lowpkg.file_list httpd...
def make_path_qs(self, items): '''Returns a relative path complete with query string for the given dictionary of items. Any items with keys matching this rule's url pattern will be inserted into the path. Any remaining items will be appended as query string parameters. ...
Returns a relative path complete with query string for the given dictionary of items. Any items with keys matching this rule's url pattern will be inserted into the path. Any remaining items will be appended as query string parameters. All items will be urlencoded. Any items wh...
def set_limits(self, min_=None, max_=None): """ Sets limits for this config value If the resulting integer is outside those limits, an exception will be raised :param min_: minima :param max_: maxima """ self._min, self._max = min_, max_
Sets limits for this config value If the resulting integer is outside those limits, an exception will be raised :param min_: minima :param max_: maxima
def get_relation_count_query_for_self_join(self, query, parent): """ Add the constraints for a relationship count query on the same table. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder """ query.select(QueryExp...
Add the constraints for a relationship count query on the same table. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder
def is_filter_with_outer_scope_vertex_field_operator(directive): """Return True if we have a filter directive whose operator applies to the outer scope.""" if directive.name.value != 'filter': return False op_name, _ = _get_filter_op_name_and_values(directive) return op_name in OUTER_SCOPE_VERT...
Return True if we have a filter directive whose operator applies to the outer scope.
def token_from_fragment(self, authorization_response): """Parse token from the URI fragment, used by MobileApplicationClients. :param authorization_response: The full URL of the redirect back to you :return: A token dict """ self._client.parse_request_uri_response( a...
Parse token from the URI fragment, used by MobileApplicationClients. :param authorization_response: The full URL of the redirect back to you :return: A token dict
def get_location(self, location_id, depth=0): """ Retrieves a single location by ID. :param location_id: The unique ID of the location. :type location_id: ``str`` """ response = self._perform_request('/locations/%s?depth=%s' % (location_id, depth)) re...
Retrieves a single location by ID. :param location_id: The unique ID of the location. :type location_id: ``str``
def delete(self): """Deletes the current session file""" if self.filename == ':memory:': return True try: os.remove(self.filename) return True except OSError: return False
Deletes the current session file
def convertTupleArrayToPoints(self, arrayOfPointTuples): """Method used to convert an array of tuples (x,y) into a string suitable for createPolygon or createPolyline @type arrayOfPointTuples: An array containing tuples eg.[(x1,y1),(x2,y2] @param arrayOfPointTuples: All points needed t...
Method used to convert an array of tuples (x,y) into a string suitable for createPolygon or createPolyline @type arrayOfPointTuples: An array containing tuples eg.[(x1,y1),(x2,y2] @param arrayOfPointTuples: All points needed to create the shape @return a string in the form "x1,y1 x2,y2...
def build_dependencies(self): '''build_dependencies High-level api: Briefly compile all yang files and find out dependency infomation of all modules. Returns ------- None Nothing returns. ''' cmd_list = ['pyang', '--plugindir', self.pyang_p...
build_dependencies High-level api: Briefly compile all yang files and find out dependency infomation of all modules. Returns ------- None Nothing returns.
def dump(self): """Returns the results in string format.""" text = '' for result in self.objects: if result.is_failure or result.is_error: text += '\n#{red}#{bright}' text += '{}\n'.format(''.ljust(79, '=')) status = 'FAILED' if resul...
Returns the results in string format.
def items(self): """ Return a copy of the dictionary's list of (key, value) pairs. """ r = [] for key in self._safe_keys(): try: r.append((key, self[key])) except KeyError: pass return r
Return a copy of the dictionary's list of (key, value) pairs.
def get_tiltplane(self, sequence): ''' Extract the main tilting plane basing on Z coordinate ''' sequence = sorted(sequence, key=lambda x: self.virtual_atoms[ x ].z) in_plane = [] for i in range(0, len(sequence)-4): if abs(self.virtual_atoms[ sequence[i] ].z -...
Extract the main tilting plane basing on Z coordinate
def fit(self, X, y=None, input_type='affinity'): """ Fit the model from data in X. Parameters ---------- input_type : string, one of: 'similarity', 'distance' or 'data'. The values of input data X. (default = 'data') X : array-like, shape (n_samples, n_featur...
Fit the model from data in X. Parameters ---------- input_type : string, one of: 'similarity', 'distance' or 'data'. The values of input data X. (default = 'data') X : array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of sam...
def ref(self, orm_classpath, cls_pk=None): """ takes a classpath to allow query-ing from another Orm class the reason why it takes string paths is to avoid infinite recursion import problems because an orm class from module A might have a ref from module B and sometimes it is h...
takes a classpath to allow query-ing from another Orm class the reason why it takes string paths is to avoid infinite recursion import problems because an orm class from module A might have a ref from module B and sometimes it is handy to have module B be able to get the objects from m...
def blend_rect(self, x0, y0, x1, y1, dx, dy, destination, alpha=0xff): """Blend a rectangle onto the image""" x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) for x in range(x0, x1 + 1): for y in range(y0, y1 + 1): o = self._offset(x, y) rgba = self.c...
Blend a rectangle onto the image
def upsert_object_property(self, identifier, properties, ignore_constraints=False): """Manipulate an object's property set. Inserts or updates properties in given dictionary. If a property key does not exist in the object's property set it is created. If the value is None an existing property is...
Manipulate an object's property set. Inserts or updates properties in given dictionary. If a property key does not exist in the object's property set it is created. If the value is None an existing property is deleted. Existing object properties that are not present in the given propert...
def _generalized_word_starts(self, xs): """Helper method returns the starting indexes of strings in GST""" self.word_starts = [] i = 0 for n in range(len(xs)): self.word_starts.append(i) i += len(xs[n]) + 1
Helper method returns the starting indexes of strings in GST
def create_site(self, webspace_name, website_name, geo_region, host_names, plan='VirtualDedicatedPlan', compute_mode='Shared', server_farm=None, site_mode=None): ''' Create a website. webspace_name: The name of the webspace. website_na...
Create a website. webspace_name: The name of the webspace. website_name: The name of the website. geo_region: The geographical region of the webspace that will be created. host_names: An array of fully qualified domain names for website. O...
def create_topic(self, topic_name, topic=None, fail_on_exist=False): ''' Creates a new topic. Once created, this topic resource manifest is immutable. topic_name: Name of the topic to create. topic: Topic object to create. fail_on_exist: ...
Creates a new topic. Once created, this topic resource manifest is immutable. topic_name: Name of the topic to create. topic: Topic object to create. fail_on_exist: Specify whether to throw an exception when the topic exists.
def length_degrees(self): '''Computes the length of the arc in degrees. The length computation corresponds to what you would expect if you would draw the arc using matplotlib taking direction into account. >>> Arc((0,0), 1, 0, 0, True).length_degrees() 0.0 >>> Arc((0,0),...
Computes the length of the arc in degrees. The length computation corresponds to what you would expect if you would draw the arc using matplotlib taking direction into account. >>> Arc((0,0), 1, 0, 0, True).length_degrees() 0.0 >>> Arc((0,0), 2, 0, 0, False).length_degrees() ...
def as_bulk_queries(queries, bulk_size): """Group a iterable of (stmt, args) by stmt into (stmt, bulk_args). bulk_args will be a list of the args grouped by stmt. len(bulk_args) will be <= bulk_size """ stmt_dict = defaultdict(list) for stmt, args in queries: bulk_args = stmt_dict[stmt...
Group a iterable of (stmt, args) by stmt into (stmt, bulk_args). bulk_args will be a list of the args grouped by stmt. len(bulk_args) will be <= bulk_size
def json_request(self, registration_ids, data=None, collapse_key=None, delay_while_idle=False, time_to_live=None, retries=5, dry_run=False): """ Makes a JSON request to GCM servers :param registration_ids: list of the registration ids :param data: dict mapping of ke...
Makes a JSON request to GCM servers :param registration_ids: list of the registration ids :param data: dict mapping of key-value pairs of messages :return dict of response body from Google including multicast_id, success, failure, canonical_ids, etc :raises GCMMissingRegistrationExcepti...
def update_listener(self, lbaas_listener, body=None): """Updates a lbaas_listener.""" return self.put(self.lbaas_listener_path % (lbaas_listener), body=body)
Updates a lbaas_listener.
def flavor_extra_set(request, flavor_id, metadata): """Set the flavor extra spec keys.""" flavor = _nova.novaclient(request).flavors.get(flavor_id) if (not metadata): # not a way to delete keys return None return flavor.set_keys(metadata)
Set the flavor extra spec keys.
def sam2fastq(sam, singles = False, force = False): """ convert sam to fastq """ L, R = None, None for line in sam: if line.startswith('@') is True: continue line = line.strip().split() bit = [True if i == '1' else False \ for i in bin(int(line[1])...
convert sam to fastq
def parse_services(config, services): """Parse configuration to return number of enabled service checks. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. services (list): A list of section names which holds configuration for each se...
Parse configuration to return number of enabled service checks. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. services (list): A list of section names which holds configuration for each service check Returns: A number (i...
def probe(self): """ Probe the file for new lines """ # make sure the filehandler is still valid # (e.g. file stat hasnt changed, file exists etc.) if not self.validate_file_handler(): return [] messages = [] # read any new lines and push th...
Probe the file for new lines
def _speak_normal_inherit(self, element): """ Speak the content of element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ self._visit(element, self._speak_normal) element.normalize()
Speak the content of element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement
def float(self, item, default=None): """ Return value of key as a float :param item: key of value to transform :param default: value to return if item does not exist :return: float of value """ try: item = self.__getattr__(item) except AttributeError ...
Return value of key as a float :param item: key of value to transform :param default: value to return if item does not exist :return: float of value
def FromArchive(cls, path, actions_dict, resources_dict, temp_dir=None): """Create a RecipeObject from a .ship archive. This archive should have been generated from a previous call to iotile-ship -a <path to yaml file> or via iotile-build using autobuild_shiparchive(). Args: ...
Create a RecipeObject from a .ship archive. This archive should have been generated from a previous call to iotile-ship -a <path to yaml file> or via iotile-build using autobuild_shiparchive(). Args: path (str): The path to the recipe file that we wish to load ...
def _six_fail_hook(modname): """Fix six.moves imports due to the dynamic nature of this class. Construct a pseudo-module which contains all the necessary imports for six :param modname: Name of failed module :type modname: str :return: An astroid module :rtype: nodes.Module """ ...
Fix six.moves imports due to the dynamic nature of this class. Construct a pseudo-module which contains all the necessary imports for six :param modname: Name of failed module :type modname: str :return: An astroid module :rtype: nodes.Module
def get_release_task_attachments(self, project, release_id, environment_id, attempt_id, plan_id, type): """GetReleaseTaskAttachments. [Preview API] :param str project: Project ID or project name :param int release_id: :param int environment_id: :param int attempt_id: ...
GetReleaseTaskAttachments. [Preview API] :param str project: Project ID or project name :param int release_id: :param int environment_id: :param int attempt_id: :param str plan_id: :param str type: :rtype: [ReleaseTaskAttachment]
def validate_event_and_assign_id(event): """ Ensure that the event has a valid time. Assign a random UUID based on the event time. """ event_time = event.get(TIMESTAMP_FIELD) if event_time is None: event[TIMESTAMP_FIELD] = event_time = epoch_time_to_kronos_time(time.time()) elif type(event_time) not ...
Ensure that the event has a valid time. Assign a random UUID based on the event time.
def cv(params, train_set, num_boost_round=100, folds=None, nfold=5, stratified=True, shuffle=True, metrics=None, fobj=None, feval=None, init_model=None, feature_name='auto', categorical_feature='auto', early_stopping_rounds=None, fpreproc=None, verbose_eval=None, show_stdv=True, seed=...
Perform the cross-validation with given paramaters. Parameters ---------- params : dict Parameters for Booster. train_set : Dataset Data to be trained on. num_boost_round : int, optional (default=100) Number of boosting iterations. folds : generator or iterator of (train...
def to_text(value): """Convert a DNS rdata class to text. @param value: the rdata class value @type value: int @rtype: string @raises ValueError: the rdata class value is not >= 0 and <= 65535 """ if value < 0 or value > 65535: raise ValueError("class must be between >= 0 and <= 655...
Convert a DNS rdata class to text. @param value: the rdata class value @type value: int @rtype: string @raises ValueError: the rdata class value is not >= 0 and <= 65535
def show_vertex(self, node_id, show_ce_ratio=True): """Plot the vicinity of a node and its ce_ratio. :param node_id: Node ID of the node to be shown. :type node_id: int :param show_ce_ratio: If true, shows the ce_ratio of the node, too. :type show_ce_ratio: bool, optional ...
Plot the vicinity of a node and its ce_ratio. :param node_id: Node ID of the node to be shown. :type node_id: int :param show_ce_ratio: If true, shows the ce_ratio of the node, too. :type show_ce_ratio: bool, optional
def _set_ovsdb_server(self, v, load=False): """ Setter method for ovsdb_server, mapped from YANG variable /ovsdb_server (list) If this variable is read-only (config: false) in the source YANG file, then _set_ovsdb_server is considered as a private method. Backends looking to populate this variable s...
Setter method for ovsdb_server, mapped from YANG variable /ovsdb_server (list) If this variable is read-only (config: false) in the source YANG file, then _set_ovsdb_server is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ovsdb_server() ...
def priority_compare(self, other): """ Compares the MIME::Type based on how reliable it is before doing a normal <=> comparison. Used by MIME::Types#[] to sort types. The comparisons involved are: 1. self.simplified <=> other.simplified (ensures that we don't try to co...
Compares the MIME::Type based on how reliable it is before doing a normal <=> comparison. Used by MIME::Types#[] to sort types. The comparisons involved are: 1. self.simplified <=> other.simplified (ensures that we don't try to compare different types) 2. IANA-registered defin...
def flash(self, partition, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK): """Flashes the last downloaded file to the given partition. Args: partition: Partition to flash. timeout_ms: Optional timeout in milliseconds to wait for it to finish. info_cb: See Download. Usually no messages. ...
Flashes the last downloaded file to the given partition. Args: partition: Partition to flash. timeout_ms: Optional timeout in milliseconds to wait for it to finish. info_cb: See Download. Usually no messages. Returns: Response to a download request, normally nothing.
def _error_repr(error): """A compact unique representation of an error.""" error_repr = repr(error) if len(error_repr) > 200: error_repr = hash(type(error)) return error_repr
A compact unique representation of an error.
def flush_buffers(self): """Default implementation, calls Read() until it blocks.""" while True: try: self.read(FLUSH_READ_SIZE, timeout_ms=10) except usb_exceptions.LibusbWrappingError as exception: if exception.is_timeout(): break raise
Default implementation, calls Read() until it blocks.
def get_wsgi_server( self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False ): """Get the WSGI server used to process requests.""" return wsgi.Server( sock, sock.getsockname(), wsgi_app, protocol=protocol, debug=debug, ...
Get the WSGI server used to process requests.
def c_ideal_gas(T, k, MW): r'''Calculates speed of sound `c` in an ideal gas at temperature T. .. math:: c = \sqrt{kR_{specific}T} Parameters ---------- T : float Temperature of fluid, [K] k : float Isentropic exponent of fluid, [-] MW : float Molecular weig...
r'''Calculates speed of sound `c` in an ideal gas at temperature T. .. math:: c = \sqrt{kR_{specific}T} Parameters ---------- T : float Temperature of fluid, [K] k : float Isentropic exponent of fluid, [-] MW : float Molecular weight of fluid, [g/mol] Retur...
def _anova(self, dv=None, between=None, detailed=False, export_filename=None): """Return one-way and two-way ANOVA.""" aov = anova(data=self, dv=dv, between=between, detailed=detailed, export_filename=export_filename) return aov
Return one-way and two-way ANOVA.
def _safemembers(members): """Check members of a tar archive for safety. Ensure that they do not contain paths or links outside of where we need them - this would only happen if the archive wasn't made by eqcorrscan. :type members: :class:`tarfile.TarFile` :param members: an open tarfile. "...
Check members of a tar archive for safety. Ensure that they do not contain paths or links outside of where we need them - this would only happen if the archive wasn't made by eqcorrscan. :type members: :class:`tarfile.TarFile` :param members: an open tarfile.
def wcs_pix_transform(ct, i, format=0): """Computes the WCS corrected pixel value given a coordinate transformation and the raw pixel value. Input: ct coordinate transformation. instance of coord_tran. i raw pixel intensity. format format string (optional). Returns: WCS cor...
Computes the WCS corrected pixel value given a coordinate transformation and the raw pixel value. Input: ct coordinate transformation. instance of coord_tran. i raw pixel intensity. format format string (optional). Returns: WCS corrected pixel value
def serializer(self, create=False, many=False): """ Decorator to mark a :class:`Serializer` subclass for a specific purpose, ie, to be used during object creation **or** for serializing lists of objects. :param create: Whether or not this serializer is for object creation. :para...
Decorator to mark a :class:`Serializer` subclass for a specific purpose, ie, to be used during object creation **or** for serializing lists of objects. :param create: Whether or not this serializer is for object creation. :param many: Whether or not this serializer is for lists of objects.
def check_payment_v2(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id): """ Verify that for a version-2 namespace (burn-to-creator), the nameop paid the right amount of BTC or Stacks. It can pay either through a preorder (for registers), or directly (for ren...
Verify that for a version-2 namespace (burn-to-creator), the nameop paid the right amount of BTC or Stacks. It can pay either through a preorder (for registers), or directly (for renewals) Return {'status': True, 'tokens_paid': ..., 'token_units': ...} if so Return {'status': False} if not.
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 command): ''' Execute a command and read the output as YAML ''' try: command = command.replace('%s', minion_id) output = __salt__['cmd.run_stdout'](command, python_shell=True...
Execute a command and read the output as YAML
def partial_update(self, index, doc_type, id, doc=None, script=None, params=None, upsert=None, querystring_args=None): """ Partially update a document with a script """ if querystring_args is None: querystring_args = {} if doc is None and scrip...
Partially update a document with a script
def import_simple_cookie(cls, simple_cookie): """ Create cookie jar from SimpleCookie object :param simple_cookie: cookies to import :return: WHTTPCookieJar """ cookie_jar = WHTTPCookieJar() for cookie_name in simple_cookie.keys(): cookie_attrs = {} for attr_name in WHTTPCookie.cookie_attr_value_comp...
Create cookie jar from SimpleCookie object :param simple_cookie: cookies to import :return: WHTTPCookieJar
def __get_view_tmpl(tag_key): ''' 根据分类uid的4位编码来找模板。如果4位的存在,则使用4位的;不然找其父类;再不然则使用通用模板 只有View需要,edit, list使用通用模板 :return String. ''' the_view_file_4 = './templates/tmpl_{0}/tpl_view_{1}.html'.format( KIND_DICS['kind_' + tag_key.split('_')[-1]], tag_key.split('_')[1] ) the_vi...
根据分类uid的4位编码来找模板。如果4位的存在,则使用4位的;不然找其父类;再不然则使用通用模板 只有View需要,edit, list使用通用模板 :return String.
def transition(self, duration, is_on=None, **kwargs): """ Transition to the specified state of the led. If another transition is already running, it is aborted. :param duration: The duration of the transition. :param is_on: The on-off state to transition to. :param kwar...
Transition to the specified state of the led. If another transition is already running, it is aborted. :param duration: The duration of the transition. :param is_on: The on-off state to transition to. :param kwargs: The state to transition to.
def pad(data, blocksize=16): """ Pads data to blocksize according to RFC 4303. Pad length field is included in output. """ padlen = blocksize - len(data) % blocksize return bytes(data + bytearray(range(1, padlen)) + bytearray((padlen - 1,)))
Pads data to blocksize according to RFC 4303. Pad length field is included in output.
def get_unique_gene_psms(self, genetable, fields, firstjoin): """Uniques the results from get_proteins_psms so each PSM as defined by gene ID / setname / psm_id will only occur once""" lastgene = None gpsms_out, gp_ids = [], [] for gpsm in self.get_proteins_psms(genetable, fields...
Uniques the results from get_proteins_psms so each PSM as defined by gene ID / setname / psm_id will only occur once
def prepare_output(d): """Clean pre-existing links in output directory.""" outDir = os.path.join(d, 'inorder') if not os.path.exists(outDir): os.mkdir(outDir) for f in os.listdir(outDir): f = os.path.join(outDir, f) if os.path.islink(f): os.remove(f) return outDir
Clean pre-existing links in output directory.
def remove_reader(self, fd): " Stop watching the file descriptor for read availability. " h = msvcrt.get_osfhandle(fd) if h in self._read_fds: del self._read_fds[h]
Stop watching the file descriptor for read availability.
def get_slab_regions(slab, blength=3.5): """ Function to get the ranges of the slab regions. Useful for discerning where the slab ends and vacuum begins if the slab is not fully within the cell Args: slab (Structure): Structure object modelling the surface blength (float, Ang): The bondl...
Function to get the ranges of the slab regions. Useful for discerning where the slab ends and vacuum begins if the slab is not fully within the cell Args: slab (Structure): Structure object modelling the surface blength (float, Ang): The bondlength between atoms. You generally want t...
def get_older_backup(self, encrypted=None, compressed=None, content_type=None, database=None, servername=None): """ Return the older backup's file name. :param encrypted: Filter by encrypted or not :type encrypted: ``bool`` or ``None`` :param compressed...
Return the older backup's file name. :param encrypted: Filter by encrypted or not :type encrypted: ``bool`` or ``None`` :param compressed: Filter by compressed or not :type compressed: ``bool`` or ``None`` :param content_type: Filter by media or database backup, must be ...
def parse(cls, string): """ Parse a string and create a metric """ match = re.match(r'^(?P<name>[A-Za-z0-9\.\-_]+)\s+' + '(?P<value>[0-9\.]+)\s+' + '(?P<timestamp>[0-9\.]+)(\n?)$', string) try: ...
Parse a string and create a metric
def make_command(self, ctx, name, info): """ make click sub-command from command info gotten from xbahn engineer """ @self.command() @click.option("--debug/--no-debug", default=False, help="Show debug information") @doc(info.get("description")) def func(...
make click sub-command from command info gotten from xbahn engineer
def create_connection(self, alias='default', **kwargs): """ Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias. """ kwargs.setdefault('serializer', serializer) conn = self._conns[alias] = Elasticsearch(**kwargs) return conn
Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias.
def authenticated_users(func): """ This decorator is used to abstract common authentication checking functionality out of permission checks. It determines which parameter is the request based on name. """ is_object_permission = "has_object" in func.__name__ @wraps(func) def func_wrapper(*ar...
This decorator is used to abstract common authentication checking functionality out of permission checks. It determines which parameter is the request based on name.
def version(self) -> str: '''Show the version number of Android Debug Bridge.''' output, _ = self._execute('version') return output.splitlines()[0].split()[-1]
Show the version number of Android Debug Bridge.
def get_orientation(width, height): # type: (int, int) -> Orientation """Get viewport orientation from given width and height. :type width: int :type height: int :return: viewport orientation enum :rtype: Orientation """ if width > height: return Orientation.LANDSCAPE elif w...
Get viewport orientation from given width and height. :type width: int :type height: int :return: viewport orientation enum :rtype: Orientation
def _Rforce(self,R,phi=0.,t=0.): """ NAME: _Rforce PURPOSE: evaluate the radial force for this potential INPUT: R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT: the radial force HISTORY:...
NAME: _Rforce PURPOSE: evaluate the radial force for this potential INPUT: R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT: the radial force HISTORY: 2017-10-16 - Written - Bovy (UofT)
def _forbidden_attributes(obj): """Return the object without the forbidden attributes.""" for key in list(obj.data.keys()): if key in list(obj.reserved_keys.keys()): obj.data.pop(key) return obj
Return the object without the forbidden attributes.
def hms2frame(hms, fps): """ :param hms: a string, e.g. "01:23:15" for one hour, 23 minutes 15 seconds :param fps: framerate :return: frame number """ import time t = time.strptime(hms, "%H:%M:%S") return (t.tm_hour * 60 * 60 + t.tm_min * 60 + t.tm_sec) ...
:param hms: a string, e.g. "01:23:15" for one hour, 23 minutes 15 seconds :param fps: framerate :return: frame number
def _hash_pair(first: bytes, second: bytes) -> bytes: """ Computes the hash of the items in lexicographic order """ if first is None: return second if second is None: return first if first > second: return keccak(second + first) else: return keccak(first + second)
Computes the hash of the items in lexicographic order
def is_classvar(tp): """Test if the type represents a class variable. Examples:: is_classvar(int) == False is_classvar(ClassVar) == True is_classvar(ClassVar[int]) == True is_classvar(ClassVar[List[T]]) == True """ if NEW_TYPING: return (tp is ClassVar or ...
Test if the type represents a class variable. Examples:: is_classvar(int) == False is_classvar(ClassVar) == True is_classvar(ClassVar[int]) == True is_classvar(ClassVar[List[T]]) == True
def min_row_dist_sum_idx(dists): """Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row wit...
Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row with min dist row sum
def generate_batch(cls, strategy, size, **kwargs): """Generate a batch of instances. The instances will be created with the given strategy (one of BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY). Args: strategy (str): the strategy to use for generating the instance. ...
Generate a batch of instances. The instances will be created with the given strategy (one of BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY). Args: strategy (str): the strategy to use for generating the instance. size (int): the number of instances to generate ...
def evaluate(self, path): """ This method evaluates attributes of the path. Returns the cause and result of matching. Both cause and result are returned from filters that this object contains. ``path`` specifies the path. """ result = False cause = None ...
This method evaluates attributes of the path. Returns the cause and result of matching. Both cause and result are returned from filters that this object contains. ``path`` specifies the path.
def replace_video(api_key, api_secret, local_video_path, video_key, **kwargs): """ Function which allows to replace the content of an EXISTING video object. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param local_video_path: <string> Path to med...
Function which allows to replace the content of an EXISTING video object. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param local_video_path: <string> Path to media on local machine. :param video_key: <string> Video's object ID. Can be found within ...
def _message_to_entity(msg, modelclass): """Recursive helper for _to_base_type() to convert a message to an entity. Args: msg: A Message instance. modelclass: A Model subclass. Returns: An instance of modelclass. """ ent = modelclass() for prop_name, prop in modelclass._properties.iteritems():...
Recursive helper for _to_base_type() to convert a message to an entity. Args: msg: A Message instance. modelclass: A Model subclass. Returns: An instance of modelclass.
def ReleaseClick(cls): ''' 释放按压操作 ''' element = cls._element() action = ActionChains(Web.driver) action.release(element) action.perform()
释放按压操作
def hard_reset(self): """Resets the iterator and ignore roll over data""" if self.seq is not None and self.shuffle: random.shuffle(self.seq) if self.imgrec is not None: self.imgrec.reset() self.cur = 0 self._allow_read = True self._cache_data = Non...
Resets the iterator and ignore roll over data
def resolveFilenameConflicts(self, dialog=True): """Goes through list of DPs to make sure that their destination names do not clash. Applies new names. Returns True if some conflicts were resolved. If dialog is True, shows confirrmation dialog.""" resolved = self.wdplv.resolveFilenameCon...
Goes through list of DPs to make sure that their destination names do not clash. Applies new names. Returns True if some conflicts were resolved. If dialog is True, shows confirrmation dialog.
def filehandles(path, openers_list=openers, pattern='', verbose=False): """Main function that iterates over list of openers and decides which opener to use. :param str path: Path. :param list openers_list: List of openers. :param str pattern: Regular expression pattern. :param verbose: Print additi...
Main function that iterates over list of openers and decides which opener to use. :param str path: Path. :param list openers_list: List of openers. :param str pattern: Regular expression pattern. :param verbose: Print additional information. :type verbose: :py:obj:`True` or :py:obj:`False` :ret...
def resize_img(fname, targ, path, new_path, fn=None): """ Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ. """ if fn is None: fn = resize_fn(targ) dest = os.path.join(path_for(path, new_path, targ), fname) if os.path.exis...
Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ.
def write_long(self, n, pack=Struct('>I').pack): """ Write an integer as an unsigned 32-bit value. """ if 0 <= n <= 0xFFFFFFFF: self._output_buffer.extend(pack(n)) else: raise ValueError('Long %d out of range 0..0xFFFFFFFF', n) return self
Write an integer as an unsigned 32-bit value.
def get_file_to_text( self, share_name, directory_name, file_name, encoding='utf-8', start_range=None, end_range=None, range_get_content_md5=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Downloads a file as unicode text...
Downloads a file as unicode text, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties, metadata, and content. :param str share_name: Name of existing share. :param str directory_name: The path to the directory....
def _get_prediction_feature_weights(lgb, X, n_targets): """ Return a list of {feat_id: value} dicts with feature weights, following ideas from http://blog.datadive.net/interpreting-random-forests/ """ if n_targets == 2: n_targets = 1 dump = lgb.booster_.dump_model() tree_info = ...
Return a list of {feat_id: value} dicts with feature weights, following ideas from http://blog.datadive.net/interpreting-random-forests/
def json_dumps(self, data): """ Standardized json.dumps function with separators and sorted keys set Args: data (dict or list): data to be dumped Returns: string: json """ return json.dumps( data, separators=(',', ':'), ...
Standardized json.dumps function with separators and sorted keys set Args: data (dict or list): data to be dumped Returns: string: json
def encode(cls, line): """Backslash escape line.value.""" if not line.encoded: encoding = getattr(line, 'encoding_param', None) if encoding and encoding.upper() == cls.base64string: line.value = b64encode(line.value).decode('utf-8') else: ...
Backslash escape line.value.
def utf8(value): """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value elif isinstance(value, u...
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
def save(self, fp=None): """Save to file. Parameters ---------- fp : `file`, optional Output file. """ self.storage.settings['markov'] = self.get_settings_json() self.storage.save(fp)
Save to file. Parameters ---------- fp : `file`, optional Output file.
def get_overs_summary(self, match_key): """ Calling Overs Summary API Arg: match_key: key of the match Return: json data """ overs_summary_url = self.api_path + "match/" + match_key + "/overs_summary/" response = self.get_response(overs_summ...
Calling Overs Summary API Arg: match_key: key of the match Return: json data
def create_pull(self, *args, **kwds): """ :calls: `POST /repos/:owner/:repo/pulls <http://developer.github.com/v3/pulls>`_ :param title: string :param body: string :param issue: :class:`github.Issue.Issue` :param base: string :param head: string :param mai...
:calls: `POST /repos/:owner/:repo/pulls <http://developer.github.com/v3/pulls>`_ :param title: string :param body: string :param issue: :class:`github.Issue.Issue` :param base: string :param head: string :param maintainer_can_modify: bool :rtype: :class:`github.Pu...
def match(self, other, psd=None, low_frequency_cutoff=None, high_frequency_cutoff=None): """ Return the match between the two TimeSeries or FrequencySeries. Return the match between two waveforms. This is equivelant to the overlap maximized over time and phase. By default, the oth...
Return the match between the two TimeSeries or FrequencySeries. Return the match between two waveforms. This is equivelant to the overlap maximized over time and phase. By default, the other vector will be resized to match self. This may remove high frequency content or the end of the v...
def render(self): """ Creates a composite ``struct`` format and the data to render with it. The format and data are prefixed with a 32-bit integer denoting the number of elements, after which each of the items in the array value are ``render()``-ed and added to the format and da...
Creates a composite ``struct`` format and the data to render with it. The format and data are prefixed with a 32-bit integer denoting the number of elements, after which each of the items in the array value are ``render()``-ed and added to the format and data as well.
def bellman_segmentation(self, x, states): """ Divide a univariate time-series, data_frame, into states contiguous segments, using Bellman k-segmentation algorithm on the peak prominences of the data. :param x: The time series to assess freeze of gait on. This could be x, y, z ...
Divide a univariate time-series, data_frame, into states contiguous segments, using Bellman k-segmentation algorithm on the peak prominences of the data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :para...
def _stats(arr, percentiles=(2, 98), **kwargs): """ Calculate array statistics. Attributes ---------- arr: numpy ndarray Input array data to get the stats from. percentiles: tuple, optional Tuple of Min/Max percentiles to compute. kwargs: dict, optional These will be...
Calculate array statistics. Attributes ---------- arr: numpy ndarray Input array data to get the stats from. percentiles: tuple, optional Tuple of Min/Max percentiles to compute. kwargs: dict, optional These will be passed to the numpy.histogram function. Returns --...
def set_writer_position(self, name, timestamp): """Insert a timestamp to keep track of the current writer position""" execute = self.cursor.execute execute('DELETE FROM gauged_writer_history WHERE id = %s', (name,)) execute('INSERT INTO gauged_writer_history (id, timestamp) ' ...
Insert a timestamp to keep track of the current writer position
def load_dataloader(self): """ Description : Setup the dataloader """ input_transform = transforms.Compose([transforms.ToTensor(), \ transforms.Normalize((0.7136, 0.4906, 0.3283), \ ...
Description : Setup the dataloader
def add_rectangle(self, north=None, west=None, south=None, east=None, **kwargs): """ Adds a rectangle dict to the Map.rectangles attribute The Google Maps API describes a rectangle using the La...
Adds a rectangle dict to the Map.rectangles attribute The Google Maps API describes a rectangle using the LatLngBounds object, which defines the bounds to be drawn. The bounds use the concept of 2 delimiting points, a northwest and a southeast points, were each coordinate is defined by ...
def get_messages(self, statuses=DEFAULT_MESSAGE_STATUSES, order="sent_at desc", offset=None, count=None, content=False): """Returns a list of messages your account sent. Messages are sorted by ``order``, starting at an optional integer...
Returns a list of messages your account sent. Messages are sorted by ``order``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items (in sorted order). Returned data includes various statistics about each message, e.g., ``total_opens``, ``open_rate``,...