code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def set_attrs(obj, attrs): """ Applies a collection of attributes C{attrs} to object C{obj} in the most generic way possible. @param obj: An instance implementing C{__setattr__}, or C{__setitem__} @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict ...
Applies a collection of attributes C{attrs} to object C{obj} in the most generic way possible. @param obj: An instance implementing C{__setattr__}, or C{__setitem__} @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict
def complete(self, match, subject_graph): """Check the completeness of a ring match""" size = len(match) # check whether we have an odd strong ring if match.forward[size-1] in subject_graph.neighbors[match.forward[size-2]]: # we have an odd closed cycle. check if this is a st...
Check the completeness of a ring match
async def eap_options(request: web.Request) -> web.Response: """ Get request returns the available configuration options for WPA-EAP. Because the options for connecting to WPA-EAP secured networks are quite complex, to avoid duplicating logic this endpoint returns a json object describing the structure...
Get request returns the available configuration options for WPA-EAP. Because the options for connecting to WPA-EAP secured networks are quite complex, to avoid duplicating logic this endpoint returns a json object describing the structure of arguments and options for the eap_config arg to /wifi/configu...
def description(pokemon): """Return a description of the given Pokemon.""" r = requests.get('http://pokeapi.co/' + (pokemon.descriptions.values()[0])) desc = eval(r.text)['description'].replace('Pokmon', 'Pokémon') return desc
Return a description of the given Pokemon.
def versionok_for_gui(): ''' Return True if running Python is suitable for GUI Event Integration and deeper IPython integration ''' # We require Python 2.6+ ... if sys.hexversion < 0x02060000: return False # Or Python 3.2+ if sys.hexversion >= 0x03000000 and sys.hexversion < 0x03020000: ...
Return True if running Python is suitable for GUI Event Integration and deeper IPython integration
def transform(self, X, y=None): """Transform the columns in ``X`` according to ``self.categories_``. Parameters ---------- X : pandas.DataFrame or dask.DataFrame y : ignored Returns ------- X_trn : pandas.DataFrame or dask.DataFrame Same type...
Transform the columns in ``X`` according to ``self.categories_``. Parameters ---------- X : pandas.DataFrame or dask.DataFrame y : ignored Returns ------- X_trn : pandas.DataFrame or dask.DataFrame Same type as the input. The columns in ``self.catego...
def subtract_months(self, months: int) -> datetime: """ Subtracts a number of months from the current value """ self.value = self.value - relativedelta(months=months) return self.value
Subtracts a number of months from the current value
def take_at_least_n_seconds(time_s): """A context manager which ensures it takes at least time_s to execute. Example: with take_at_least_n_seconds(5): do.Something() do.SomethingElse() # if Something and SomethingElse took 3 seconds, the with block with sleep # for 2 seconds before exiting....
A context manager which ensures it takes at least time_s to execute. Example: with take_at_least_n_seconds(5): do.Something() do.SomethingElse() # if Something and SomethingElse took 3 seconds, the with block with sleep # for 2 seconds before exiting. Args: time_s: The number of seconds...
def encrypt(self, s, mac_bytes=10): """ Encrypt `s' for this pubkey. """ if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") out = BytesIO() with se...
Encrypt `s' for this pubkey.
def enable(self, cmd="enable", pattern=r"#", re_flags=re.IGNORECASE): """Enable mode on MRV uses no password.""" output = "" if not self.check_enable_mode(): self.write_channel(self.normalize_cmd(cmd)) output += self.read_until_prompt_or_pattern( pattern=p...
Enable mode on MRV uses no password.
def update_repodata(self, channels=None): """Update repodata from channels or use condarc channels if None.""" norm_channels = self.conda_get_condarc_channels(channels=channels, normalize=True) repodata_urls = self._set_repo_urls_from_chann...
Update repodata from channels or use condarc channels if None.
def gifs_trending_get(self, api_key, **kwargs): """ Trending GIFs Endpoint Fetch GIFs currently trending online. Hand curated by the GIPHY editorial team. The data returned mirrors the GIFs showcased on the <a href = \"http://www.giphy.com\">GIPHY homepage</a>. Returns 25 results by default. ...
Trending GIFs Endpoint Fetch GIFs currently trending online. Hand curated by the GIPHY editorial team. The data returned mirrors the GIFs showcased on the <a href = \"http://www.giphy.com\">GIPHY homepage</a>. Returns 25 results by default. This method makes a synchronous HTTP request by default. To mak...
def get_package_info(self, name): # type: (str) -> dict """ Return the package information given its name. The information is returned from the cache if it exists or retrieved from the remote server. """ if self._disable_cache: return self._get_package_info(...
Return the package information given its name. The information is returned from the cache if it exists or retrieved from the remote server.
def t_offset(self, s): r'[+]\d+' pos = self.pos self.add_token('OFFSET', s) self.pos = pos + len(s)
r'[+]\d+
def move(self, auth, resource, destinationresource, options={"aliases": True}, defer=False): """ Moves a resource from one parent client to another. Args: auth: <cik> resource: Identifed resource to be moved. destinationresource: resource of client resource is being ...
Moves a resource from one parent client to another. Args: auth: <cik> resource: Identifed resource to be moved. destinationresource: resource of client resource is being moved to.
def in_nested_list(nested_list, obj): """return true if the object is an element of <nested_list> or of a nested list """ for elmt in nested_list: if isinstance(elmt, (list, tuple)): if in_nested_list(elmt, obj): return True elif elmt == obj: retur...
return true if the object is an element of <nested_list> or of a nested list
def dump(self, validate=True): """ Create bencoded :attr:`metainfo` (i.e. the content of a torrent file) :param bool validate: Whether to run :meth:`validate` first :return: :attr:`metainfo` as bencoded :class:`bytes` """ if validate: self.validate() ...
Create bencoded :attr:`metainfo` (i.e. the content of a torrent file) :param bool validate: Whether to run :meth:`validate` first :return: :attr:`metainfo` as bencoded :class:`bytes`
def parse(response): """check for errors""" if response.status_code == 400: try: msg = json.loads(response.content)['message'] except (KeyError, ValueError): msg = '' raise ApiError(msg) return response
check for errors
def stop_request(self, stop_now=False): """Send a stop request to the daemon :param stop_now: stop now or go to stop wait mode :type stop_now: bool :return: the daemon response (True) """ logger.debug("Sending stop request to %s, stop now: %s", self.name, stop_now) ...
Send a stop request to the daemon :param stop_now: stop now or go to stop wait mode :type stop_now: bool :return: the daemon response (True)
def install_var(instance, clear_target, clear_all): """Install required folders in /var""" _check_root() log("Checking frontend library and cache directories", emitter='MANAGE') uid = pwd.getpwnam("hfos").pw_uid gid = grp.getgrnam("hfos").gr_gid join = os.path.join # If these nee...
Install required folders in /var
def train(self, s, path="spelling.txt"): """ Counts the words in the given string and saves the probabilities at the given path. This can be used to generate a new model for the Spelling() constructor. """ model = {} for w in re.findall("[a-z]+", s.lower()): model...
Counts the words in the given string and saves the probabilities at the given path. This can be used to generate a new model for the Spelling() constructor.
def unique_append(self, value): """ function for only appending unique items to a list. #! consider the possibility of item using this to a set """ if value not in self: try: super(self.__class__, self).append(Uri(value)) except AttributeError as err: if isinstanc...
function for only appending unique items to a list. #! consider the possibility of item using this to a set
def _command(self, sock_info, command, slave_ok=False, read_preference=None, codec_options=None, check=True, allowable_errors=None, read_concern=None, write_concern=None, collation=None, session=None, ...
Internal command helper. :Parameters: - `sock_info` - A SocketInfo instance. - `command` - The command itself, as a SON instance. - `slave_ok`: whether to set the SlaveOkay wire protocol bit. - `codec_options` (optional) - An instance of :class:`~bson.codec_o...
def usePointsForInterpolation(self,cNrm,mNrm,interpolator): ''' Constructs a basic solution for this period, including the consumption function and marginal value function. Parameters ---------- cNrm : np.array (Normalized) consumption points for interpolatio...
Constructs a basic solution for this period, including the consumption function and marginal value function. Parameters ---------- cNrm : np.array (Normalized) consumption points for interpolation. mNrm : np.array (Normalized) corresponding market resourc...
def _validate_authority_uri_abs_path(host, path): """Ensure that path in URL with authority starts with a leading slash. Raise ValueError if not. """ if len(host) > 0 and len(path) > 0 and not path.startswith("/"): raise ValueError( "Path in a URL with author...
Ensure that path in URL with authority starts with a leading slash. Raise ValueError if not.
def _run_command(argv): # type: (typing.List[str]) -> typing.Any """Run the command with the given CLI options and exit. Command functions are expected to have a __doc__ string that is parseable by docopt. Args: argv: The list of command line arguments supplied for a command. The ...
Run the command with the given CLI options and exit. Command functions are expected to have a __doc__ string that is parseable by docopt. Args: argv: The list of command line arguments supplied for a command. The first argument is expected to be the name of the command to be run. ...
def post(self, text=None, attachments=None, source_guid=None): """Post a direct message to the user. :param str text: the message content :param attachments: message attachments :param str source_guid: a client-side unique ID for the message :return: the message sent :rt...
Post a direct message to the user. :param str text: the message content :param attachments: message attachments :param str source_guid: a client-side unique ID for the message :return: the message sent :rtype: :class:`~groupy.api.messages.DirectMessage`
def _mmComputeSequenceRepresentationData(self): """ Calculates values for the overlap distance matrix, stability within a sequence, and distinctness between sequences. These values are cached so that they do need to be recomputed for calls to each of several accessor methods that use these values. ...
Calculates values for the overlap distance matrix, stability within a sequence, and distinctness between sequences. These values are cached so that they do need to be recomputed for calls to each of several accessor methods that use these values.
def predefinedEntity(name): """Check whether this name is an predefined entity. """ ret = libxml2mod.xmlGetPredefinedEntity(name) if ret is None:raise treeError('xmlGetPredefinedEntity() failed') return xmlEntity(_obj=ret)
Check whether this name is an predefined entity.
def get_work_items_batch(self, work_item_get_request, project=None): """GetWorkItemsBatch. Gets work items for a list of work item ids (Maximum 200) :param :class:`<WorkItemBatchGetRequest> <azure.devops.v5_0.work_item_tracking.models.WorkItemBatchGetRequest>` work_item_get_request: :par...
GetWorkItemsBatch. Gets work items for a list of work item ids (Maximum 200) :param :class:`<WorkItemBatchGetRequest> <azure.devops.v5_0.work_item_tracking.models.WorkItemBatchGetRequest>` work_item_get_request: :param str project: Project ID or project name :rtype: [WorkItem]
def _finish(self, update_ops, name_scope): """Updates beta_power variables every n batches and incrs counter.""" iter_ = self._get_iter_variable() beta1_power, beta2_power = self._get_beta_accumulators() with tf.control_dependencies(update_ops): with tf.colocate_with(iter_): def update_be...
Updates beta_power variables every n batches and incrs counter.
def grant_client(self, client_id, read=True, write=True): """ Grant the given client id all the scopes and authorities needed to work with the timeseries service. """ scopes = ['openid'] authorities = ['uaa.resource'] if write: for zone in self.servic...
Grant the given client id all the scopes and authorities needed to work with the timeseries service.
def get_data_excel_xml(file_name, file_contents=None, on_demand=False): ''' Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents o...
Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents of file_name. If left as None, then file_name is directly loaded. ...
def event_notify(self, event): """ Notify all subscribers of an event. event -- the event that occurred """ if event.name not in self.available_events: return message = json.dumps({ 'messageType': 'event', 'data': event.as_event_descr...
Notify all subscribers of an event. event -- the event that occurred
def has_event(self, event, cameo_code): """ Test whether there is an "event2" or "event3" entry for the given cameo code Args: event: cameo_code: Returns: """ if self.has_cameo_code(cameo_code): entry = self.mapping.get(cameo_code) ...
Test whether there is an "event2" or "event3" entry for the given cameo code Args: event: cameo_code: Returns:
def add_call(self, func): """Add a call to the trace.""" self.trace.append("{} ({}:{})".format( object_name(func), inspect.getsourcefile(func), inspect.getsourcelines(func)[1])) return self
Add a call to the trace.
def app_size(self): "Return the total apparent size, including children." if self._nodes is None: return self._app_size return sum(i.app_size() for i in self._nodes)
Return the total apparent size, including children.
def to_dict(self): """Convert attribute definition into a dictionary. Returns ------- dict Json-like dictionary representation of the attribute definition """ obj = { 'id' : self.identifier, 'name' : self.name, 'description...
Convert attribute definition into a dictionary. Returns ------- dict Json-like dictionary representation of the attribute definition
async def _buffer_body(self, reader): """ Buffers the body of the request """ remaining = int(self.headers.get('Content-Length', 0)) if remaining > 0: try: self.data = await reader.readexactly(remaining) except asyncio.IncompleteReadError: ...
Buffers the body of the request
def _get_default_arg(args, defaults, arg_index): """ Method that determines if an argument has default value or not, and if yes what is the default value for the argument :param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg'] :param defaults: array of default values, eg: (42, 'so...
Method that determines if an argument has default value or not, and if yes what is the default value for the argument :param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg'] :param defaults: array of default values, eg: (42, 'something') :param arg_index: index of the argument in ...
def draw_simple_elevation(world, sea_level, target): """ This function can be used on a generic canvas (either an image to save on disk or a canvas part of a GUI) """ e = world.layers['elevation'].data c = numpy.empty(e.shape, dtype=numpy.float) has_ocean = not (sea_level is None or world.l...
This function can be used on a generic canvas (either an image to save on disk or a canvas part of a GUI)
def _index_param_value(num_samples, v, indices): """Private helper function for parameter value indexing. This determines whether a fit parameter `v` to a SearchCV.fit should be indexed along with `X` and `y`. Note that this differs from the scikit-learn version. They pass `X` and compute num_samples. ...
Private helper function for parameter value indexing. This determines whether a fit parameter `v` to a SearchCV.fit should be indexed along with `X` and `y`. Note that this differs from the scikit-learn version. They pass `X` and compute num_samples. We pass `num_samples` instead.
async def request(self, command, payload, retry=3): """Request data.""" # pylint: disable=too-many-return-statements if self._token is None: _LOGGER.error("No token") return None _LOGGER.debug(command, payload) nonce = ''.join(random.choice(string.ascii...
Request data.
def update_firmware(filename, host=None, admin_username=None, admin_password=None): ''' Updates firmware using local firmware file .. code-block:: bash salt dell dracr.update_firmware firmware.exe This executes the following command...
Updates firmware using local firmware file .. code-block:: bash salt dell dracr.update_firmware firmware.exe This executes the following command on your FX2 (using username and password stored in the pillar data) .. code-block:: bash racadm update –f firmware.exe -u user –p pass
def format(sql, args=None): """ Resolve variable references in a query within an environment. This computes and resolves the transitive dependencies in the query and raises an exception if that fails due to either undefined or circular references. Args: sql: query to format. args: a dictio...
Resolve variable references in a query within an environment. This computes and resolves the transitive dependencies in the query and raises an exception if that fails due to either undefined or circular references. Args: sql: query to format. args: a dictionary of values to use in variable ex...
def _by_columns(self, columns): """ Allow select.group and select.order accepting string and list """ return columns if self.isstr(columns) else self._backtick_columns(columns)
Allow select.group and select.order accepting string and list
def read_pipe(pipe_out): """Read data on a pipe Used to capture stdout data produced by libiperf :param pipe_out: The os pipe_out :rtype: unicode string """ out = b'' while more_data(pipe_out): out += os.read(pipe_out, 1024) return out.decode('utf-8')
Read data on a pipe Used to capture stdout data produced by libiperf :param pipe_out: The os pipe_out :rtype: unicode string
def _bounds_dist(self, p): """Get the lower and upper bound distances. Negative is bad.""" prob = self.problem lb_dist = (p - prob.variable_bounds[0, ]).min() ub_dist = (prob.variable_bounds[1, ] - p).min() if prob.bounds.shape[0] > 0: const = prob.inequalities.dot(...
Get the lower and upper bound distances. Negative is bad.
def update_received_packet(self, received_pkt_size_bytes): """Update received packet metrics""" self.update_count(self.RECEIVED_PKT_COUNT) self.update_count(self.RECEIVED_PKT_SIZE, incr_by=received_pkt_size_bytes)
Update received packet metrics
def get(self, id, **options): '''Get a single item with the given ID''' if not self._item_path: raise AttributeError('get is not available for %s' % self._item_name) target = self._item_path % id json_data = self._redmine.get(target, **options) data = self._redmine.un...
Get a single item with the given ID
def _dy_shapelets(self, shapelets, beta): """ computes the derivative d/dx of the shapelet coeffs :param shapelets: :param beta: :return: """ num_n = len(shapelets) dy = np.zeros((num_n+1, num_n+1)) for n1 in range(num_n): for n2 in ran...
computes the derivative d/dx of the shapelet coeffs :param shapelets: :param beta: :return:
def disable_share(cookie, tokens, shareid_list): '''取消分享. shareid_list 是一个list, 每一项都是一个shareid ''' url = ''.join([ const.PAN_URL, 'share/cancel?channel=chunlei&clienttype=0&web=1', '&bdstoken=', tokens['bdstoken'], ]) data = 'shareid_list=' + encoder.encode_uri(json.dump...
取消分享. shareid_list 是一个list, 每一项都是一个shareid
def getAceTypeBit(self, t): ''' returns the acetype bit of a text value ''' try: return self.validAceTypes[t]['BITS'] except KeyError: raise CommandExecutionError(( 'No ACE type "{0}". It should be one of the following: {1}' ...
returns the acetype bit of a text value
def logs(self, pod=None): """ Logs from a worker pod You can get this pod object from the ``pods`` method. If no pod is specified all pod logs will be returned. On large clusters this could end up being rather large. Parameters ---------- pod: kubernetes.client...
Logs from a worker pod You can get this pod object from the ``pods`` method. If no pod is specified all pod logs will be returned. On large clusters this could end up being rather large. Parameters ---------- pod: kubernetes.client.V1Pod The pod from which ...
def latitude(self): '''Latitude in signed degrees (python float)''' sd = dm_to_sd(self.lat) if self.lat_dir == 'N': return +sd elif self.lat_dir == 'S': return -sd else: return 0.
Latitude in signed degrees (python float)
def __calculate_bu_dfs_recursively(u, b, dfs_data): """Calculates the b(u) lookup table with a recursive DFS.""" first_time = True for v in dfs_data['adj'][u]: if a(v, dfs_data) == u: if first_time: b[v] = b[u] else: b[v] = D(u, dfs_data) ...
Calculates the b(u) lookup table with a recursive DFS.
def _get_unitary(self): """Return the current unitary in JSON Result spec format""" unitary = np.reshape(self._unitary, 2 * [2 ** self._number_of_qubits]) # Expand complex numbers unitary = np.stack((unitary.real, unitary.imag), axis=-1) # Truncate small values unitary[ab...
Return the current unitary in JSON Result spec format
def estimate_K_knee(self, th=.015, maxK=12): """Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC.""" # Sweep K-means if self.X.shape[0] < maxK: maxK = self.X.shape[0] if maxK < 2: maxK = 2 K = np.arange(...
Estimates the K using K-means and BIC, by sweeping various K and choosing the optimal BIC.
def validate_query(self, using=None, **kwargs): """ Validate a potentially expensive query without executing it. Any additional keyword arguments will be passed to ``Elasticsearch.indices.validate_query`` unchanged. """ return self._get_connection(using).indices.validate...
Validate a potentially expensive query without executing it. Any additional keyword arguments will be passed to ``Elasticsearch.indices.validate_query`` unchanged.
def jprecess(ra, dec, mu_radec=None, parallax=None, rad_vel=None, epoch=None): """ NAME: JPRECESS PURPOSE: Precess astronomical coordinates from B1950 to J2000 EXPLANATION: Calculate the mean place of a star at J2000.0 on the FK5 system from the mean place at B1950.0 o...
NAME: JPRECESS PURPOSE: Precess astronomical coordinates from B1950 to J2000 EXPLANATION: Calculate the mean place of a star at J2000.0 on the FK5 system from the mean place at B1950.0 on the FK4 system. Use BPRECESS for the reverse direction J2000 ==> B1950 ...
def equals(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when t...
Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when they have different lengths.
def _remove_code(site): """ Delete project files @type site: Site """ def handle_error(function, path, excinfo): click.secho('Failed to remove path ({em}): {p}'.format(em=excinfo.message, p=path), err=True, fg='red') if os.path.exists(site.root): shutil.rmtree(site.root, one...
Delete project files @type site: Site
def _create_ucsm_host_to_service_profile_mapping(self): """Reads list of Service profiles and finds associated Server.""" # Get list of UCSMs without host list given in the config ucsm_ips = [ip for ip, ucsm in CONF.ml2_cisco_ucsm.ucsms.items() if not ucsm.ucsm_host_list] ...
Reads list of Service profiles and finds associated Server.
def calculate_lvgd_stats(nw): """ LV Statistics for an arbitrary network Parameters ---------- nw: :any:`list` of NetworkDing0 The MV grid(s) to be studied Returns ------- lvgd_stats : pandas.DataFrame Dataframe containing several statistical numbers about the LVGD ...
LV Statistics for an arbitrary network Parameters ---------- nw: :any:`list` of NetworkDing0 The MV grid(s) to be studied Returns ------- lvgd_stats : pandas.DataFrame Dataframe containing several statistical numbers about the LVGD
def update(self, name, **kwargs): """ Create a new node """ # These arguments are allowed self.allowed('update', kwargs, ['hostname', 'port', 'status', 'storage_hostname', 'volume_type_name', 'size']) # Remove parameters that are None kwargs =...
Create a new node
def refetch_for_update(obj): """Queries the database for the same object that is passed in, refetching its contents and runs ``select_for_update()`` to lock the corresponding row until the next commit. :param obj: Object to refetch :returns: Refreshed version of the object """ ...
Queries the database for the same object that is passed in, refetching its contents and runs ``select_for_update()`` to lock the corresponding row until the next commit. :param obj: Object to refetch :returns: Refreshed version of the object
def sendToTradepile(self, item_id, safe=True): """Send to tradepile (alias for __sendToPile__). :params item_id: Item id. :params safe: (optional) False to disable tradepile free space check. """ if safe and len( self.tradepile()) >= self.tradepile_size: # TODO?...
Send to tradepile (alias for __sendToPile__). :params item_id: Item id. :params safe: (optional) False to disable tradepile free space check.
def _convert_value(self, item): """ Handle different value types for XLS. Item is a cell object. """ # Types: # 0 = empty u'' # 1 = unicode text # 2 = float (convert to int if possible, then convert to string) # 3 = date (convert to unambiguous date/time s...
Handle different value types for XLS. Item is a cell object.
def command_max_run_time(self, event=None): """ CPU burst max running time - self.runtime_cfg.max_run_time """ try: max_run_time = self.max_run_time_var.get() except ValueError: max_run_time = self.runtime_cfg.max_run_time self.runtime_cfg.max_run_time = max_run_...
CPU burst max running time - self.runtime_cfg.max_run_time
def add_require(self, require): """ Add a require object if it does not already exist """ for p in self.requires: if p.value == require.value: return self.requires.append(require)
Add a require object if it does not already exist
def stop(self): """ Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None """ super(AggregateDependency, self).stop() if self.services: return [ (service, reference) for refe...
Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None
def _build_pools(self): """ Slow method, retrieve all the terms from the database. :return: """ if self.level >= Topic: # words self.topics_pool = set(self.topic() for i in range(self.pool_size)) if self.level >= Fact: # sentences ...
Slow method, retrieve all the terms from the database. :return:
def notify(self, correlation_id, args): """ Fires this event and notifies all registred listeners. :param correlation_id: (optional) transaction id to trace execution through call chain. :param args: the parameters to raise this event with. """ for listener in self._lis...
Fires this event and notifies all registred listeners. :param correlation_id: (optional) transaction id to trace execution through call chain. :param args: the parameters to raise this event with.
def get_pk(obj): """ Return primary key name by model class or instance. :Parameters: - `obj`: SQLAlchemy model instance or class. :Examples: >>> from sqlalchemy import Column, Integer >>> from sqlalchemy.ext.declarative import declarative_base >>> Base = declarative_base() >>> cl...
Return primary key name by model class or instance. :Parameters: - `obj`: SQLAlchemy model instance or class. :Examples: >>> from sqlalchemy import Column, Integer >>> from sqlalchemy.ext.declarative import declarative_base >>> Base = declarative_base() >>> class User(Base): ... ...
def copy(self, cursor, f): """ Defines copying JSON from s3 into redshift. """ logger.info("Inserting file: %s", f) cursor.execute(""" COPY %s from '%s' CREDENTIALS '%s' JSON AS '%s' %s %s ;""" % (self.table, f, self._credentials(), ...
Defines copying JSON from s3 into redshift.
def getVerifiers(self): """Returns the list of lab contacts that have verified at least one analysis from this Analysis Request """ contacts = list() for verifier in self.getVerifiersIDs(): user = api.get_user(verifier) contact = api.get_user_contact(user,...
Returns the list of lab contacts that have verified at least one analysis from this Analysis Request
def from_json(data): """ Convert JSON into a in memory file storage. Args: data (str): valid JSON with path and filenames and the base64 encoding of the file content. Returns: InMemoryFiles: in memory file storage """ memf...
Convert JSON into a in memory file storage. Args: data (str): valid JSON with path and filenames and the base64 encoding of the file content. Returns: InMemoryFiles: in memory file storage
def create_file_service(self): ''' Creates a FileService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.file.fileservice.FileService` ''' try: from azure.storage.file.fileservi...
Creates a FileService object with the settings specified in the CloudStorageAccount. :return: A service object. :rtype: :class:`~azure.storage.file.fileservice.FileService`
def add(self, elem): """ Adds _elem_ to the collection. # Parameters _elem_ : `object` > The object to be added """ if isinstance(elem, self._allowedTypes): self._collection.add(elem) self._collectedTypes.add(type(elem).__name__) else: ...
Adds _elem_ to the collection. # Parameters _elem_ : `object` > The object to be added
def _symbols(): """(Lazy)load list of all supported symbols (sorted) Look into `_data()` for all currency symbols, then sort by length and unicode-ord (A-Z is not as relevant as ֏). Returns: List[unicode]: Sorted list of possible currency symbols. """ global _SYMBOLS if _SYMBOLS is...
(Lazy)load list of all supported symbols (sorted) Look into `_data()` for all currency symbols, then sort by length and unicode-ord (A-Z is not as relevant as ֏). Returns: List[unicode]: Sorted list of possible currency symbols.
def joint_img(self, num_iid, pic_path, session, id=None, position=None, is_major=None): '''taobao.item.joint.img 商品关联子图 - 关联一张商品图片到num_iid指定的商品中 - 传入的num_iid所对应的商品必须属于当前会话的用户 - 商品图片关联在卖家身份和图片来源上的限制,卖家要是B卖家或订购了多图服务才能关联图片,并且图片要来自于卖家自己的图片空间才行 - 商品图片数量有限制。不管是上传的图片还是关联的图片,...
taobao.item.joint.img 商品关联子图 - 关联一张商品图片到num_iid指定的商品中 - 传入的num_iid所对应的商品必须属于当前会话的用户 - 商品图片关联在卖家身份和图片来源上的限制,卖家要是B卖家或订购了多图服务才能关联图片,并且图片要来自于卖家自己的图片空间才行 - 商品图片数量有限制。不管是上传的图片还是关联的图片,他们的总数不能超过一定限额
def create_notes_folder(self, title, parentid=""): """Create new folder :param title: The title of the folder to create :param parentid: The UUID of the parent folder """ if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication...
Create new folder :param title: The title of the folder to create :param parentid: The UUID of the parent folder
def required(wrapping_functions, patterns_rslt): ''' USAGE: from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required mypage_patterns = required( login_required, [ ... url patterns ... ] ...
USAGE: from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required mypage_patterns = required( login_required, [ ... url patterns ... ] ) staff_patterns = required( staff_member_requi...
def _exec_request(self, service, method=None, path_args=None, data=None, params=None): """Execute request.""" if path_args is None: path_args = [] req = { 'method': method or 'get', 'url': '/'.join(str(a).strip('/') for a in [ ...
Execute request.
def put(self, deviceId): """ Puts a new device into the device store :param deviceId: :return: """ device = request.get_json() logger.debug("Received /devices/" + deviceId + " - " + str(device)) self._deviceController.accept(deviceId, device) retur...
Puts a new device into the device store :param deviceId: :return:
def predict(self, log2_bayes_factors, reset_index=False): """Guess the most likely modality for each event For each event that has at least one non-NA value, if no modalilites have logsumexp'd logliks greater than the log Bayes factor threshold, then they are assigned the 'multimodal' m...
Guess the most likely modality for each event For each event that has at least one non-NA value, if no modalilites have logsumexp'd logliks greater than the log Bayes factor threshold, then they are assigned the 'multimodal' modality, because we cannot reject the null hypothesis that th...
def _wrap_tracebackexception_format(redact: Callable[[str], str]): """Monkey-patch TracebackException.format to redact printed lines. Only the last call will be effective. Consecutive calls will overwrite the previous monkey patches. """ original_format = getattr(TracebackException, '_original', No...
Monkey-patch TracebackException.format to redact printed lines. Only the last call will be effective. Consecutive calls will overwrite the previous monkey patches.
def _param_deprecation_warning(schema, deprecated, context): """Raises warning about using the 'old' names for some parameters. The new naming scheme just has two underscores on each end of the word for consistency """ for i in deprecated: if i in schema: msg = 'When matc...
Raises warning about using the 'old' names for some parameters. The new naming scheme just has two underscores on each end of the word for consistency
def xpath(request): """View for the route. Determines UUID and version from input request and determines the type of UUID (collection or module) and executes the corresponding method.""" ident_hash = request.params.get('id') xpath_string = request.params.get('q') if not ident_hash or not xpath_...
View for the route. Determines UUID and version from input request and determines the type of UUID (collection or module) and executes the corresponding method.
def telnet_sa_telnet_server_shutdown(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") telnet_sa = ET.SubElement(config, "telnet-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services") telnet = ET.SubElement(telnet_sa, "telnet") server = ET.SubElem...
Auto Generated Code
def _get_bases(cls, ab): """ Start Bases & End Bases :param ab: at bat object(type:Beautifulsoup) :param attribute_name: attribute name :return: start base, end base """ start_bases, end_bases = [], [] for base in ('1B', '2B', '3B'): if ab.find...
Start Bases & End Bases :param ab: at bat object(type:Beautifulsoup) :param attribute_name: attribute name :return: start base, end base
def create_app(): """Create the standard app for ``fleaker_config`` and register the two routes required. """ app = App.create_app(__name__) app.configure('.configs.settings') # yes, I should use blueprints; but I don't really care for such a small # toy app @app.route('/config') de...
Create the standard app for ``fleaker_config`` and register the two routes required.
def reply_sticker( self, sticker: str, quote: bool = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[ "pyrogram.InlineKeyboardMarkup", "pyrogram.ReplyKeyboardMarkup", "pyrogram.ReplyKeyboard...
Bound method *reply_sticker* of :obj:`Message <pyrogram.Message>`. Use as a shortcut for: .. code-block:: python client.send_sticker( chat_id=message.chat.id, sticker=sticker ) Example: .. code-block:: python ...
def exists_or_mkdir(path, verbose=True): """Check a folder by given name, if not exist, create the folder and return False, if directory exists, return True. Parameters ---------- path : str A folder path. verbose : boolean If True (default), prints results. Returns ---...
Check a folder by given name, if not exist, create the folder and return False, if directory exists, return True. Parameters ---------- path : str A folder path. verbose : boolean If True (default), prints results. Returns -------- boolean True if folder already...
def trace_min_buffer_capacity(self): """Retrieves the minimum capacity the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The minimum configurable capacity for the trace buffer. """ cmd = enums.JLinkTraceCommand.GET...
Retrieves the minimum capacity the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The minimum configurable capacity for the trace buffer.
def can_import(self, file_uris, current_doc=None): """ Check that the specified file looks like an image supported by PIL """ if len(file_uris) <= 0: return False for file_uri in file_uris: file_uri = self.fs.safe(file_uri) if not self.check_fi...
Check that the specified file looks like an image supported by PIL
def add_note(note, **kwargs): """ Add a new note """ note_i = Note() note_i.ref_key = note.ref_key note_i.set_ref(note.ref_key, note.ref_id) note_i.value = note.value note_i.created_by = kwargs.get('user_id') db.DBSession.add(note_i) db.DBSession.flush() return note_i
Add a new note
def _wait(self, generator, method, timeout=None, *args, **kwargs): """Wait until generator is paused before running 'method'.""" if self.debug: print("waiting for %s to pause" % generator) original_timeout = timeout while timeout is None or timeout > 0: last_time...
Wait until generator is paused before running 'method'.
def __run_git(cmd, path=None): """internal run git command :param cmd: git parameters as array :param path: path where command will be executed :return: tuple (<line>, <returncode>) """ exe = [__get_git_bin()] + cmd try: proc = subprocess.Popen(exe, cwd=path, stdout=subprocess.PIPE, ...
internal run git command :param cmd: git parameters as array :param path: path where command will be executed :return: tuple (<line>, <returncode>)
def bulk_modify(self, *filters_or_records, **kwargs): """Shortcut to bulk modify records .. versionadded:: 2.17.0 Args: *filters_or_records (tuple) or (Record): Either a list of Records, or a list of filters. Keyword Args: values (dict): Diction...
Shortcut to bulk modify records .. versionadded:: 2.17.0 Args: *filters_or_records (tuple) or (Record): Either a list of Records, or a list of filters. Keyword Args: values (dict): Dictionary of one or more 'field_name': 'new_value' pairs to update ...