code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def ignore_file_extension(self, extension): """ Configure a file extension to be ignored. :param extension: file extension to be ignored (ex. .less, .scss, etc) """ logger.info('Ignoring file extension: {}'.format(extension)) self.watcher.ignore...
Configure a file extension to be ignored. :param extension: file extension to be ignored (ex. .less, .scss, etc)
def pricing(sort='cost', **kwargs): ''' Print pricing tables for all enabled providers ''' for name, provider in env.providers.items(): print name provider.pricing(sort, **kwargs) print
Print pricing tables for all enabled providers
def nextstate(self, newstate, treenode=None, user_data=None): """ Manage transition of state. """ if newstate is None: return self if isinstance(newstate, State) and id(newstate) != id(self): return newstate elif isinstance(newstate, StateEvent): ...
Manage transition of state.
def validate_address(self, address_deets): """Validates a customer address and returns back a collection of address matches.""" request = self._post('addresses/validate', address_deets) return self.responder(request)
Validates a customer address and returns back a collection of address matches.
def send_cmd(self, command, connId='default'): """ Sends any command to FTP server. Returns server output. Parameters: - command - any valid command to be sent (invalid will result in exception). - connId(optional) - connection identifier. By default equals 'default' Exam...
Sends any command to FTP server. Returns server output. Parameters: - command - any valid command to be sent (invalid will result in exception). - connId(optional) - connection identifier. By default equals 'default' Example: | send cmd | HELP |
def get_proxies(self, quantity, type): ''' quantity: 数量 type: 类型 1.国内高匿代理 2.国内普通代理 3.国外高匿代理 4.国外普通代理 ''' url_queue = Queue() need_pages = int(math.ceil(quantity/15)) # 判断类型 if type == 1: # 国内高匿代理 ...
quantity: 数量 type: 类型 1.国内高匿代理 2.国内普通代理 3.国外高匿代理 4.国外普通代理
def _update_libdata(self, line): """Update the library meta data from the current line being parsed Args: line (str): The current line of the of the file being parsed """ #################################################### # parse MONA Comments line ########...
Update the library meta data from the current line being parsed Args: line (str): The current line of the of the file being parsed
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_sticker( # receiver, self.media, disable_notificati...
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
def update(self, callback=None, errback=None, parent=True, **kwargs): """ Update address configuration. Pass a list of keywords and their values to update. For the list of keywords available for address configuration, see :attr:`ns1.rest.ipam.Addresses.INT_FIELDS` and :attr:`ns1.rest.ipam.Addres...
Update address configuration. Pass a list of keywords and their values to update. For the list of keywords available for address configuration, see :attr:`ns1.rest.ipam.Addresses.INT_FIELDS` and :attr:`ns1.rest.ipam.Addresses.PASSTHRU_FIELDS`
def notify(self, data): """Notify this channel of inbound data""" string_channels = { ChannelIdentifiers.de_registrations, ChannelIdentifiers.registrations_expired } if data['channel'] in string_channels: message = {'device_id': data["value"], 'channe...
Notify this channel of inbound data
def add_type_struct_or_union(self, name, interp, node): """Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of the typedefd struct/union :node: the union/struct node :interp: the 010 interpreter """ self.add_type...
Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of the typedefd struct/union :node: the union/struct node :interp: the 010 interpreter
def show(ctx, project_id, backend): """ Shows the details of the given project id. """ try: project = ctx.obj['projects_db'].get(project_id, backend) except IOError: raise Exception("Error: the projects database file doesn't exist. " "Please run `taxi update` ...
Shows the details of the given project id.
def generation_time(self): """A :class:`datetime.datetime` instance representing the time of generation for this :class:`ObjectId`. The :class:`datetime.datetime` is timezone aware, and represents the generation time in UTC. It is precise to the second. """ times...
A :class:`datetime.datetime` instance representing the time of generation for this :class:`ObjectId`. The :class:`datetime.datetime` is timezone aware, and represents the generation time in UTC. It is precise to the second.
def effsnr(snr, reduced_x2, fac=250.): """Calculate the effective SNR statistic. See (S5y1 paper) for definition. """ snr = numpy.array(snr, ndmin=1, dtype=numpy.float64) rchisq = numpy.array(reduced_x2, ndmin=1, dtype=numpy.float64) esnr = snr / (1 + snr ** 2 / fac) ** 0.25 / rchisq ** 0.25 # ...
Calculate the effective SNR statistic. See (S5y1 paper) for definition.
def cli(env, name, public): """List images.""" image_mgr = SoftLayer.ImageManager(env.client) images = [] if public in [False, None]: for image in image_mgr.list_private_images(name=name, mask=image_mod.MASK): images.append(image) ...
List images.
def get_autoregressive_bias(max_length: int, dtype: str = C.DTYPE_FP32) -> mx.sym.Symbol: """ Returns bias/mask to ensure position i can only attend to positions <i. :param max_length: Sequence length. :param dtype: dtype of bias :return: Bias symbol of shape (1, max_length, max_length). """ ...
Returns bias/mask to ensure position i can only attend to positions <i. :param max_length: Sequence length. :param dtype: dtype of bias :return: Bias symbol of shape (1, max_length, max_length).
def touch(self, key, expire=0, noreply=None): """ The memcached "touch" command. Args: key: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cache, or zero for no expiry (the default). nor...
The memcached "touch" command. Args: key: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cache, or zero for no expiry (the default). noreply: optional bool, True to not wait for the reply (defaults to ...
def __CheckValid(self, value): "check for validity of value" val = self.__val self.is_valid = True try: val = set_float(value) if self.__min is not None and (val < self.__min): self.is_valid = False val = self.__min if s...
check for validity of value
def get_range(self, i): """ Check and retrieve range if value is a valid range. Here we are looking to see if the value is series or range. We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine). """ try: m = i.match(RE_INT_ITER) ...
Check and retrieve range if value is a valid range. Here we are looking to see if the value is series or range. We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine).
def _begin(self, retry_id=None): """Begin the transaction. Args: retry_id (Optional[bytes]): Transaction ID of a transaction to be retried. Raises: ValueError: If the current transaction has already begun. """ if self.in_progress: ...
Begin the transaction. Args: retry_id (Optional[bytes]): Transaction ID of a transaction to be retried. Raises: ValueError: If the current transaction has already begun.
def getfieldcomm(bunchdt, data, commdct, idfobject, fieldname): """get the idd comment for the field""" key = idfobject.obj[0].upper() keyi = data.dtls.index(key) fieldi = idfobject.objls.index(fieldname) thiscommdct = commdct[keyi][fieldi] return thiscommdct
get the idd comment for the field
def create_circuit(name, provider_id, circuit_type, description=None): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit name Name of the circuit provider_id The netbox id of the circuit provider circuit_type The name of the circuit type asn The ASN...
.. versionadded:: 2019.2.0 Create a new Netbox circuit name Name of the circuit provider_id The netbox id of the circuit provider circuit_type The name of the circuit type asn The ASN of the circuit provider description The description of the circuit ...
def render_select_site_form(self, request, context, form_url=''): """ Render the site choice form. """ app_label = self.opts.app_label context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': mark_safe(form_url), ...
Render the site choice form.
def _get_alpha(self, C, vs30, pga_rock): """ Returns the alpha, the linearised functional relationship between the site amplification and the PGA on rock. Equation 31. """ alpha = np.zeros(len(pga_rock)) idx = vs30 < C["k1"] if np.any(idx): af1 = pga_r...
Returns the alpha, the linearised functional relationship between the site amplification and the PGA on rock. Equation 31.
def headpart_types(self, method, input=True): """ Get a list of header I{parameter definitions} (pdefs) defined for the specified method. An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple, while an output I{pdef} is a L{xsd.sxbase.SchemaObject}. @param m...
Get a list of header I{parameter definitions} (pdefs) defined for the specified method. An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple, while an output I{pdef} is a L{xsd.sxbase.SchemaObject}. @param method: A service method. @type method: I{service.Method} ...
def _send_command(self, command, expected_bytes): """ Send an XID command to the device """ response = self.con.send_xid_command(command, expected_bytes) return response
Send an XID command to the device
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
def process_management_config_section(config, management_config): """ Processes the management section from a configuration data dict. :param config: The config reference of the object that will hold the configuration data from the config_data. :param management_config: Management section from a config...
Processes the management section from a configuration data dict. :param config: The config reference of the object that will hold the configuration data from the config_data. :param management_config: Management section from a config data dict.
def defUtilityFuncs(self): ''' Defines CRRA utility function for this period (and its derivatives), saving them as attributes of self for other methods to use. Parameters ---------- none Returns ------- none ''' self.u = lambda ...
Defines CRRA utility function for this period (and its derivatives), saving them as attributes of self for other methods to use. Parameters ---------- none Returns ------- none
def main(output): """Output the HBP knowledge graph to the desktop""" from hbp_knowledge import get_graph graph = get_graph() text = to_html(graph) print(text, file=output)
Output the HBP knowledge graph to the desktop
def run(self): """ Performs actual NWCHEM2FIESTA run """ init_folder = os.getcwd() os.chdir(self.folder) with zopen(self.log_file, 'w') as fout: subprocess.call([self._NWCHEM2FIESTA_cmd, self._nwcheminput_fn, self._nwchemoutput_f...
Performs actual NWCHEM2FIESTA run
def get_footnote_backreferences(text, markdown_obj): """Retrieves all footnote backreferences within the text. Fotnote backreferences can be defined anywhere in the text, and look like this: [^id]: text The corresponding footnote reference can then be placed anywhere in the text ...
Retrieves all footnote backreferences within the text. Fotnote backreferences can be defined anywhere in the text, and look like this: [^id]: text The corresponding footnote reference can then be placed anywhere in the text This is some text.[^id] Footnote IDs are case insensiti...
def update_payload(self, fields=None): """Wrap submitted data within an extra dict.""" payload = super(DiscoveryRule, self).update_payload(fields) if 'search_' in payload: payload['search'] = payload.pop('search_') return {u'discovery_rule': payload}
Wrap submitted data within an extra dict.
def state_get(self, block_id, addresses): '''Returns a list of address/data pairs (str, bytes)''' block = self._get_blocks([block_id.hex()])[0] block_header = BlockHeader() block_header.ParseFromString(block.header) try: state_view = self._state_view_factory.create_v...
Returns a list of address/data pairs (str, bytes)
def p_statement_expr(self, t): '''statement : node_expression PLUS node_expression | node_expression MINUS node_expression''' if len(t)<3 : self.accu.add(Term('input', [t[1]])) print('input', t[1]) else : #print(t[1], t[2], t[3] self.accu.add(Term('edge', ...
statement : node_expression PLUS node_expression | node_expression MINUS node_expression
def do_cli(ctx, host, port, template, env_vars, debug_port, debug_args, # pylint: disable=R0914 debugger_path, docker_volume_basedir, docker_network, log_file, layer_cache_basedir, skip_pull_image, force_image_build, parameter_overrides): """ Implementation of the ``cli`` method, just sep...
Implementation of the ``cli`` method, just separated out for unit testing purposes
def split_(self, col: str) -> "list(Ds)": """ Split the main dataframe according to a column's unique values and return a dict of dataswim instances :return: list of dataswim instances :rtype: list(Ds) :example: ``dss = ds.slit_("Col 1")`` """ try: ...
Split the main dataframe according to a column's unique values and return a dict of dataswim instances :return: list of dataswim instances :rtype: list(Ds) :example: ``dss = ds.slit_("Col 1")``
def show_rich_text(self, text, collapse=False, img_path=''): """Show text in rich mode""" self.switch_to_plugin() self.switch_to_rich_text() context = generate_context(collapse=collapse, img_path=img_path, css_path=self.css_path) self.rend...
Show text in rich mode
def _req_files_move(self, pid, fids): """ Move files or directories :param str pid: destination directory id :param list fids: a list of ids of files or directories to be moved """ url = self.web_api_url + '/move' data = {} data['pid'] = pid for i,...
Move files or directories :param str pid: destination directory id :param list fids: a list of ids of files or directories to be moved
def apply_raw(self): """ apply to the values as a numpy array """ try: result = reduction.reduce(self.values, self.f, axis=self.axis) except Exception: result = np.apply_along_axis(self.f, self.axis, self.values) # TODO: mixed type case if result.ndim ==...
apply to the values as a numpy array
def auth(**kwargs): ''' Authorize device synchronization. ''' """ kodrive auth <path> <device_id (client)> 1. make sure path has been added to config.xml, server 2. make sure path is not shared by someone 3. add device_id to folder in config.xml, server 4. add device to devices in config.xml, ...
Authorize device synchronization.
def getsinIm(alat): """Computes sinIm from modified apex latitude. Parameters ========== alat : array_like Modified apex latitude Returns ======= sinIm : ndarray or float """ alat = np.float64(alat) return 2*np.sin(np.radians(alat))/np.sqrt(4 - 3*np.cos(np.radians(al...
Computes sinIm from modified apex latitude. Parameters ========== alat : array_like Modified apex latitude Returns ======= sinIm : ndarray or float
def bulk_record_workunits(self, engine_workunits): """A collection of workunits from v2 engine part""" for workunit in engine_workunits: duration = workunit['end_timestamp'] - workunit['start_timestamp'] span = zipkin_span( service_name="pants", span_name=workunit['name'], d...
A collection of workunits from v2 engine part
def shape_offset_y(self): """Return y distance of shape origin from local coordinate origin. The returned integer represents the topmost extent of the freeform shape, in local coordinates. Note that the bounding box of the shape need not start at the local origin. """ mi...
Return y distance of shape origin from local coordinate origin. The returned integer represents the topmost extent of the freeform shape, in local coordinates. Note that the bounding box of the shape need not start at the local origin.
def to_decimal(alpha_number, alphabet=ALPHABET, default=_marker): """Converts an alphanumeric code (e.g AB12) to an integer :param alpha_number: representation of an alphanumeric code :param alphabet: alphabet to use when alpha_number is a non-int string :type number: int, string, Alphanumber, float ...
Converts an alphanumeric code (e.g AB12) to an integer :param alpha_number: representation of an alphanumeric code :param alphabet: alphabet to use when alpha_number is a non-int string :type number: int, string, Alphanumber, float :type alphabet: string
def set_children(self, child_ids): """Sets the children. arg: child_ids (osid.id.Id[]): the children``Ids`` raise: InvalidArgument - ``child_ids`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* ...
Sets the children. arg: child_ids (osid.id.Id[]): the children``Ids`` raise: InvalidArgument - ``child_ids`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
def create( cls, model, parent = None, uifile = '', commit = True ): """ Prompts the user to create a new record for the inputed table. :param model | <subclass of orb.Table> parent | <QWidget> :return <orb.Table> || None/ | instan...
Prompts the user to create a new record for the inputed table. :param model | <subclass of orb.Table> parent | <QWidget> :return <orb.Table> || None/ | instance of the inputed table class
def write_all_files(filename, data, wref_data=None, params=None): """ Creates an LCModel control file for processing the supplied MRSData, and optional water reference data, updating the default parameters with any values supplied through params. :param filename: the location where the control file...
Creates an LCModel control file for processing the supplied MRSData, and optional water reference data, updating the default parameters with any values supplied through params. :param filename: the location where the control file should be saved. :param data: MRSData to be processed. :param wref_da...
def get_average_record(self, n): """Returns a list of average current numbers, each representing the average over the last n data points. Args: n: Number of data points to average over. Returns: A list of average current values. """ history_deque...
Returns a list of average current numbers, each representing the average over the last n data points. Args: n: Number of data points to average over. Returns: A list of average current values.
def p_encaps_var_object_property(p): 'encaps_var : VARIABLE OBJECT_OPERATOR STRING' p[0] = ast.ObjectProperty(ast.Variable(p[1], lineno=p.lineno(1)), p[3], lineno=p.lineno(2))
encaps_var : VARIABLE OBJECT_OPERATOR STRING
def default_to_hashed_rows(self, default=None): """ Gets the current setting with no parameters, sets it if a boolean is passed in :param default: the value to set :return: the current value, or new value if default is set to True or False """ if default is not None: ...
Gets the current setting with no parameters, sets it if a boolean is passed in :param default: the value to set :return: the current value, or new value if default is set to True or False
def mk_examples_menu(text, root_dir=None, depth=0): """ :return: base_item, rel_paths """ # 3.12+ menus examples_dir = ide_utils.get_example_dir() if not examples_dir: return None, [] root_dir = root_dir or examples_dir file_actions = [] menu = Gio.Menu.new() b...
:return: base_item, rel_paths
def add_reporter(self, reporter): """Add a MetricReporter""" with self._lock: reporter.init(list(self.metrics.values())) self._reporters.append(reporter)
Add a MetricReporter
def orthogonal(name, shape, scale=1.1, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r"""Creates a tensor variable of which initial values are of an orthogonal ndarray. See [Saxe et al. 2014.](http://arxiv.org/pdf/1312.6120.pdf) Args: name: The name of new variable...
r"""Creates a tensor variable of which initial values are of an orthogonal ndarray. See [Saxe et al. 2014.](http://arxiv.org/pdf/1312.6120.pdf) Args: name: The name of new variable. shape: A tuple/list of integers. scale: A Python scalar. dtype: Either float32 or float64. ...
def get_init(self, filename="__init__.py"): """ Get various info from the package without importing them """ import ast with open(filename) as init_file: module = ast.parse(init_file.read()) itr = lambda x: (ast.literal_eval(node.value) for node in ast.walk(module) ...
Get various info from the package without importing them
def format_url(url: str, url_vars: Mapping[str, Any]) -> str: """Construct a URL for the GitHub API. The URL may be absolute or relative. In the latter case the appropriate domain will be added. This is to help when copying the relative URL directly from the GitHub developer documentation. The dic...
Construct a URL for the GitHub API. The URL may be absolute or relative. In the latter case the appropriate domain will be added. This is to help when copying the relative URL directly from the GitHub developer documentation. The dict provided in url_vars is used in URI template formatting.
def generate_method(service_module, service_name, method_name): """Generate a method for the given Thrift service. :param service_module: Thrift-generated service module :param service_name: Name of the Thrift service :param method_name: Method being called """ assert se...
Generate a method for the given Thrift service. :param service_module: Thrift-generated service module :param service_name: Name of the Thrift service :param method_name: Method being called
def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_func=None, ): """If the stacktrace originates within the elasticapm module, it will skip frames until som...
If the stacktrace originates within the elasticapm module, it will skip frames until some other module comes up.
def __setLock(self, command): """Set lock on requests.""" if command in (TURN_ON, TURN_OFF): self._operation = command elif command in INV_SOURCES: self._operation = SOURCE else: self._operation = ALL self._isLocked = True self._timer =...
Set lock on requests.
def _create_more_application(): """ Create an `Application` instance that displays the "--MORE--". """ from prompt_toolkit.shortcuts import create_prompt_application registry = Registry() @registry.add_binding(' ') @registry.add_binding('y') @registry.add_binding('Y') @registry.add_...
Create an `Application` instance that displays the "--MORE--".
def retrieveVals(self): """Retrieve values for graphs.""" name = 'diskspace' if self.hasGraph(name): for fspath in self._fslist: if self._statsSpace.has_key(fspath): self.setGraphVal(name, fspath, self._statsSp...
Retrieve values for graphs.
def argsort(self, axis=-1, kind='quicksort', order=None): """ Returns the indices that would sort an array. .. note:: This method wraps `numpy.argsort`. This documentation is modified from that of `numpy.argsort`. Perform an indirect sort along the gi...
Returns the indices that would sort an array. .. note:: This method wraps `numpy.argsort`. This documentation is modified from that of `numpy.argsort`. Perform an indirect sort along the given axis using the algorithm specified by the `kind` keyword. It ret...
def query_random(num=6, kind='1'): ''' Query wikis randomly. ''' return TabWiki.select().where( TabWiki.kind == kind ).order_by( peewee.fn.Random() ).limit(num)
Query wikis randomly.
def sign(self, value): """ :type value: any :rtype: bytes """ payload = struct.pack('>cQ', self.version, int(time.time())) payload += force_bytes(value) return payload + self.signature(payload).finalize()
:type value: any :rtype: bytes
def limits_hydrate(db, lims): """ Helper function to hydrate a list of limits. :param db: A database handle. :param lims: A list of limit strings, as retrieved from the database. """ return [limits.Limit.hydrate(db, lim) for lim in lims]
Helper function to hydrate a list of limits. :param db: A database handle. :param lims: A list of limit strings, as retrieved from the database.
def isdir(self, dirname): """Returns whether the path is a directory or not.""" client = boto3.client("s3") bucket, path = self.bucket_and_path(dirname) if not path.endswith("/"): path += "/" # This will now only retrieve subdir content r = client.list_objects(Bucket...
Returns whether the path is a directory or not.
def SplitMeta(meta): """Split and validate metacharacters. Example: '{}' -> ('{', '}') This is public so the syntax highlighter and other tools can use it. """ n = len(meta) if n % 2 == 1: raise ConfigurationError( '%r has an odd number of metacharacters' % meta) return meta[...
Split and validate metacharacters. Example: '{}' -> ('{', '}') This is public so the syntax highlighter and other tools can use it.
def cmd_link_add(self, args): '''add new link''' descriptor = args[0] print("Adding link %s" % descriptor) self.link_add(descriptor)
add new link
def concat_same_type(self, to_concat, placement=None): """ Concatenate list of single blocks of the same type. """ values = self._concatenator([blk.values for blk in to_concat], axis=self.ndim - 1) return self.make_block_same_class( ...
Concatenate list of single blocks of the same type.
def is_callable(instance, attribute, value): """Raises a :exc:`TypeError` if the value is not a callable.""" if not callable(value): raise TypeError("'{}' must be callable".format(attribute.name))
Raises a :exc:`TypeError` if the value is not a callable.
def initialize_communities_bucket(): """Initialize the communities file bucket. :raises: `invenio_files_rest.errors.FilesException` """ bucket_id = UUID(current_app.config['COMMUNITIES_BUCKET_UUID']) if Bucket.query.get(bucket_id): raise FilesException("Bucket with UUID {} already exists."...
Initialize the communities file bucket. :raises: `invenio_files_rest.errors.FilesException`
def _rd_dat_signals(file_name, dir_name, pb_dir, fmt, n_sig, sig_len, byte_offset, samps_per_frame, skew, sampfrom, sampto, smooth_frames): """ Read all signals from a WFDB dat file. Parameters ---------- file_name : str The name of the dat file * o...
Read all signals from a WFDB dat file. Parameters ---------- file_name : str The name of the dat file * other params See docstring for `_rd_segment`. Returns ------- signals : numpy array, or list See docstring for `_rd_segment`. Notes ----- See docstri...
def rest_api_url(self, *url_parts, **kwargs): """Join the URL of REST_API parameters: upl_parts: strings that are joined to the url by "/". a REST url like https://na1.salesforce.com/services/data/v44.0/ is usually added, but not if the first string starts w...
Join the URL of REST_API parameters: upl_parts: strings that are joined to the url by "/". a REST url like https://na1.salesforce.com/services/data/v44.0/ is usually added, but not if the first string starts with https:// api_ver: API version that shoul...
def _build_youtube_dl(worker, destdir, site): ''' Builds a `youtube_dl.YoutubeDL` for brozzling `site` with `worker`. The `YoutubeDL` instance does a few special brozzler-specific things: - keeps track of urls fetched using a `YoutubeDLSpy` - periodically updates `site.last_claimed` in rethinkdb ...
Builds a `youtube_dl.YoutubeDL` for brozzling `site` with `worker`. The `YoutubeDL` instance does a few special brozzler-specific things: - keeps track of urls fetched using a `YoutubeDLSpy` - periodically updates `site.last_claimed` in rethinkdb - if brozzling through warcprox and downloading segment...
def send_zipfile(request, fileList): """ Create a ZIP file on disk and transmit it in chunks of 8KB, without loading the whole file into memory. A similar approach can be used for large dynamic PDF files....
Create a ZIP file on disk and transmit it in chunks of 8KB, without loading the whole file into memory. A similar approach can be used for large dynamic PDF files.
def _cons(self, word, i): """cons(i) is TRUE <=> b[i] is a consonant.""" if word[i] in self.vowels: return False if word[i] == 'y': if i == 0: return True else: return (not self._cons(word, i - 1)) return True
cons(i) is TRUE <=> b[i] is a consonant.
def delete_relationship(self, session, data, api_type, obj_id, rel_key): """ Delete a resource or multiple resources from a to-many relationship. :param session: SQLAlchemy session :param data: JSON data provided with the request :param api_type: Type of the resource :pa...
Delete a resource or multiple resources from a to-many relationship. :param session: SQLAlchemy session :param data: JSON data provided with the request :param api_type: Type of the resource :param obj_id: ID of the resource :param rel_key: Key of the relationship to fetch
def draw_graph(graph_instance, map_coloring = None): """! @brief Draw graph. @param[in] graph_instance (graph): Graph that should be drawn. @param[in] map_coloring (list): List of color indexes for each vertex. Size of this list should be equal to size of graph (number of vertices). ...
! @brief Draw graph. @param[in] graph_instance (graph): Graph that should be drawn. @param[in] map_coloring (list): List of color indexes for each vertex. Size of this list should be equal to size of graph (number of vertices). If it's not specified (None) than grap...
def get_time_slice(time, z, zdot=None, timeStart=None, timeEnd=None): """ Get slice of time, z and (if provided) zdot from timeStart to timeEnd. Parameters ---------- time : ndarray array of time values z : ndarray array of z values zdot : ndarray, optional array of...
Get slice of time, z and (if provided) zdot from timeStart to timeEnd. Parameters ---------- time : ndarray array of time values z : ndarray array of z values zdot : ndarray, optional array of zdot (velocity) values. timeStart : float, optional time at which to ...
def push(self, files, run=None, entity=None, project=None, description=None, force=True, progress=False): """Uploads multiple files to W&B Args: files (list or dict): The filenames to upload run (str, optional): The run to upload to entity (str, optional): The entity...
Uploads multiple files to W&B Args: files (list or dict): The filenames to upload run (str, optional): The run to upload to entity (str, optional): The entity to scope this project to. Defaults to wandb models project (str, optional): The name of the project to ...
def remove_config(chassis_id=None, community=None, contact=None, location=None, test=False, commit=True, **kwargs): # pylint: disable=unused-argument ''' Removes a configuration element from the SNMP co...
Removes a configuration element from the SNMP configuration. :param chassis_id: (optional) Chassis ID :param community: (optional) A dictionary having the following optional keys: - acl (if any policy / ACL need to be set) - mode: rw or ro. Default: ro :param contact: Contact details :param...
def create(self, timeout=values.unset, priority=values.unset, task_channel=values.unset, workflow_sid=values.unset, attributes=values.unset): """ Create a new TaskInstance :param unicode timeout: The amount of time in seconds the task is allowed to live up to a max...
Create a new TaskInstance :param unicode timeout: The amount of time in seconds the task is allowed to live up to a maximum of 2 weeks. :param unicode priority: Override priority for the Task. :param unicode task_channel: When MultiTasking is enabled specify the type of the task by passing eith...
def run(dest, router, args, deadline=None, econtext=None): """ Run the command specified by `args` such that ``PATH`` searches for SSH by the command will cause its attempt to use SSH to execute a remote program to be redirected to use mitogen to execute that program using the context `dest` instead...
Run the command specified by `args` such that ``PATH`` searches for SSH by the command will cause its attempt to use SSH to execute a remote program to be redirected to use mitogen to execute that program using the context `dest` instead. :param list args: Argument vector. :param mitogen.co...
def set_resize_parameters( self, degrad=6, labels=None, resize_mm=None, resize_voxel_number=None, ): """ set_input_data() should be called before :param degrad: :param labels: :param resize_mm: :param resize...
set_input_data() should be called before :param degrad: :param labels: :param resize_mm: :param resize_voxel_number: :return:
def load_policy_config(filters=None, prepend=True, pillar_key='acl', pillarenv=None, saltenv=None, merge_pillar=True, only_lower_merge=False, revision_id=None,...
Generate and load the configuration of the whole policy. .. note:: The order of the filters and their terms is very important. The configuration loaded on the device respects the order defined in the ``filters`` and/or inside the pillar. When merging the ``filters`` with the pilla...
def promote(self, name): """Promote to a PartitionName by combining with a bundle Name.""" return PartitionName(**dict(list(name.dict.items()) + list(self.dict.items())))
Promote to a PartitionName by combining with a bundle Name.
def scheduled_status_delete(self, id): """ Deletes a scheduled status. """ id = self.__unpack_id(id) url = '/api/v1/scheduled_statuses/{0}'.format(str(id)) self.__api_request('DELETE', url)
Deletes a scheduled status.
def create_api_key(self, body, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html>`_ :arg body: The api key request to create an API key :arg refresh: If `true` (the default) then refresh the affected shards t...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html>`_ :arg body: The api key request to create an API key :arg refresh: If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait ...
async def process_ltd_doc(session, github_api_token, ltd_product_url, mongo_collection=None): """Ingest any kind of LSST document hosted on LSST the Docs from its source. Parameters ---------- session : `aiohttp.ClientSession` Your application's aiohttp client sess...
Ingest any kind of LSST document hosted on LSST the Docs from its source. Parameters ---------- session : `aiohttp.ClientSession` Your application's aiohttp client session. See http://aiohttp.readthedocs.io/en/stable/client.html. github_api_token : `str` A GitHub personal AP...
def add_header_callback(self, cb, port, channel, port_mask=0xFF, channel_mask=0xFF): """ Add a callback for a specific port/header callback with the possibility to add a mask for channel and port for multiple hits for same callback. """ self.cb...
Add a callback for a specific port/header callback with the possibility to add a mask for channel and port for multiple hits for same callback.
def _check_required_settings(batches): """Ensure that all settings required at genesis are set.""" required_settings = [ 'sawtooth.consensus.algorithm.name', 'sawtooth.consensus.algorithm.version'] for batch in batches: for txn in batch.transactions: txn_header = Transac...
Ensure that all settings required at genesis are set.
def kernel_command_line(self, kernel_command_line): """ Sets the kernel command line for this QEMU VM. :param kernel_command_line: QEMU kernel command line """ log.info('QEMU VM "{name}" [{id}] has set the QEMU kernel command line to {kernel_command_line}'.format(name=self._nam...
Sets the kernel command line for this QEMU VM. :param kernel_command_line: QEMU kernel command line
def get_plugin(self, service_provider=None, auth_url=None, plugins=None, **kwargs): """Authenticate using keystone to keystone federation. This plugin uses other v3 plugins to authenticate a user to a identity provider in order to authenticate the user to a service pr...
Authenticate using keystone to keystone federation. This plugin uses other v3 plugins to authenticate a user to a identity provider in order to authenticate the user to a service provider :param service_provider: service provider ID :param auth_url: Keystone auth url :p...
def v1(self): """Return voltage phasors at the "from buses" (bus1)""" Vm = self.system.dae.y[self.v] Va = self.system.dae.y[self.a] return polar(Vm[self.a1], Va[self.a1])
Return voltage phasors at the "from buses" (bus1)
def revoke_permission(user, permission_name): """ Revoke a specified permission from a user. Permissions are only revoked if they are in the scope any of the user's roles. If the permission is out of scope, a RolePermissionScopeException is raised. """ roles = get_user_roles(user) for ...
Revoke a specified permission from a user. Permissions are only revoked if they are in the scope any of the user's roles. If the permission is out of scope, a RolePermissionScopeException is raised.
def _downgrade_v4(op): """ Downgrades assets db by copying the `exchange_full` column to `exchange`, then dropping the `exchange_full` column. """ op.drop_index('ix_equities_fuzzy_symbol') op.drop_index('ix_equities_company_symbol') op.execute("UPDATE equities SET exchange = exchange_full")...
Downgrades assets db by copying the `exchange_full` column to `exchange`, then dropping the `exchange_full` column.
def Drop(self: Iterable, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ] """ con = tuple(self) n = len(con) - n if n <= 0: yield from con else: for i, e in enumerate(con): ...
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ]
def _gen_records(self, record, zone_id, creating=False): ''' Turns an octodns.Record into one or more `_Route53*`s ''' return _Route53Record.new(self, record, zone_id, creating)
Turns an octodns.Record into one or more `_Route53*`s
def plus_dora(tile, dora_indicators): """ :param tile: int 136 tiles format :param dora_indicators: array of 136 tiles format :return: int count of dora """ tile_index = tile // 4 dora_count = 0 for dora in dora_indicators: dora //= 4 # sou, pin, man if tile_ind...
:param tile: int 136 tiles format :param dora_indicators: array of 136 tiles format :return: int count of dora
def read_numpy_text (self, dfcols=None, **kwargs): """Read this path into a :class:`numpy.ndarray` as a text file using :func:`numpy.loadtxt`. In normal conditions the returned array is two-dimensional, with the first axis spanning the rows in the file and the second axis columns (but se...
Read this path into a :class:`numpy.ndarray` as a text file using :func:`numpy.loadtxt`. In normal conditions the returned array is two-dimensional, with the first axis spanning the rows in the file and the second axis columns (but see the *unpack* and *dfcols* keywords). If *dfcols* is...