code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def gen_centers(self): """Set the centre of the Gaussian basis functions be spaced evenly throughout run time""" '''x_track = self.cs.discrete_rollout() t = np.arange(len(x_track))*self.dt # choose the points in time we'd like centers to be at c_des = np.linspace(0, sel...
Set the centre of the Gaussian basis functions be spaced evenly throughout run time
def unregister_transformer(self, transformer): """Unregister a transformer instance.""" if transformer in self._transformers: self._transformers.remove(transformer)
Unregister a transformer instance.
def get_instance(self, payload): """ Build an instance of WorkerInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance """ ...
Build an instance of WorkerInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance :rtype: twilio.rest.taskrouter.v1.workspace.worker.WorkerInstance
def assess_content(member,file_filter): '''Determine if the filter wants the file to be read for content. In the case of yes, we would then want to add the content to the hash and not the file object. ''' member_path = member.name.replace('.','',1) if len(member_path) == 0: return False...
Determine if the filter wants the file to be read for content. In the case of yes, we would then want to add the content to the hash and not the file object.
def _validate_isvalid_quantity(self, isvalid_quantity, field, value): """Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. ...
Checks for valid given value and appropriate units. Args: isvalid_quantity (`bool`): flag from schema indicating quantity to be checked. field (`str`): property associated with quantity in question. value (`list`): list whose first element is a string representing a value wi...
def rsub(self, other, axis="columns", level=None, fill_value=None): """Subtract a DataFrame/Series/scalar from this DataFrame. Args: other: The object to use to apply the subtraction to this. axis: The axis to apply the subtraction over. level: Mutlilevel index...
Subtract a DataFrame/Series/scalar from this DataFrame. Args: other: The object to use to apply the subtraction to this. axis: The axis to apply the subtraction over. level: Mutlilevel index level to subtract over. fill_value: The value to fill NaNs with. ...
def set_wizard_step_description(self): """Set the text for description.""" subcategory = self.parent.step_kw_subcategory.selected_subcategory() field = self.parent.step_kw_field.selected_fields() is_raster = is_raster_layer(self.parent.layer) if is_raster: if self.la...
Set the text for description.
def create_identity(self, name, attrs=[]): """ Create an Identity :param: name identity name :param: attrs list of dict of attributes (zimsoap format) :returns: a zobjects.Identity object """ params = { 'name': name, 'a': attrs } r...
Create an Identity :param: name identity name :param: attrs list of dict of attributes (zimsoap format) :returns: a zobjects.Identity object
def _parse_status(self, status): """ Parses the status string found in the table and applies the corresponding values. Parameters ---------- status: :class:`str` The string containing the status. """ if "rented" in status: self.status = Ho...
Parses the status string found in the table and applies the corresponding values. Parameters ---------- status: :class:`str` The string containing the status.
def verify_weave_options(opt, parser): """Parses the CLI options, verifies that they are consistent and reasonable, and acts on them if they are Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes parser : ob...
Parses the CLI options, verifies that they are consistent and reasonable, and acts on them if they are Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes parser : object OptionParser instance.
def read(self): """Read a line of data from the input source at a time.""" line = self.trace_file.readline() if line == '': if self.loop: self._reopen_file() else: self.trace_file.close() self.trace_file = None ...
Read a line of data from the input source at a time.
def write_contents(self, filename, contents, directory=None): """ write_contents: Write contents to filename in zip Args: contents: (str) contents of file filename: (str) name of file in zip directory: (str) directory in zipfile to write file to (optio...
write_contents: Write contents to filename in zip Args: contents: (str) contents of file filename: (str) name of file in zip directory: (str) directory in zipfile to write file to (optional) Returns: path to file in zip
def gcpool(name, start, room, lenout=_default_len_out): """ Return the character value of a kernel variable from the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gcpool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :param start:...
Return the character value of a kernel variable from the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gcpool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :param start: Which component to start retrieving for name. :type start: int ...
def drum_in_pattern_rate(pianoroll, beat_resolution, tolerance=0.1): """Return the ratio of the number of drum notes that lie on the drum pattern (i.e., at certain time steps) to the total number of drum notes.""" if beat_resolution not in (4, 6, 8, 9, 12, 16, 18, 24): raise ValueError("Unsupported ...
Return the ratio of the number of drum notes that lie on the drum pattern (i.e., at certain time steps) to the total number of drum notes.
def find_data(folder): """ Include everything in the folder """ for (path, directories, filenames) in os.walk(folder): for filename in filenames: yield os.path.join('..', path, filename)
Include everything in the folder
def instantiate(self, **extra_args): """ Instantiate the model """ input_block = self.input_block.instantiate() policy_backbone = self.policy_backbone.instantiate(**extra_args) value_backbone = self.value_backbone.instantiate(**extra_args) return StochasticPolicyModelSeparate(in...
Instantiate the model
def invite_by_email(self, email, sender=None, request=None, **kwargs): """Creates an inactive user with the information we know and then sends an invitation email for that user to complete registration. If your project uses email in a different way then you should make to extend this me...
Creates an inactive user with the information we know and then sends an invitation email for that user to complete registration. If your project uses email in a different way then you should make to extend this method as it only checks the `email` attribute for Users.
def in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0, time_format=TIME_FORMAT): """ :param days: :param seconds: :param microseconds: :param milliseconds: :param minutes: :param hours: :param weeks: :param time_format: :retu...
:param days: :param seconds: :param microseconds: :param milliseconds: :param minutes: :param hours: :param weeks: :param time_format: :return: Formatet string
def update_sdb(self, sdb_id, owner=None, description=None, user_group_permissions=None, iam_principal_permissions=None): """ Update a safe deposit box. Keyword arguments: owner (string) -- AD group that owns the safe deposit box description (string) -...
Update a safe deposit box. Keyword arguments: owner (string) -- AD group that owns the safe deposit box description (string) -- Description of the safe deposit box user_group_permissions (list) -- list of dictionaries containing the key name and maybe role_id ia...
def _to_EC_KEY(self): """ Create a new OpenSSL EC_KEY structure initialized to use this curve. The structure is automatically garbage collected when the Python object is garbage collected. """ key = self._lib.EC_KEY_new_by_curve_name(self._nid) return _ffi.gc(key...
Create a new OpenSSL EC_KEY structure initialized to use this curve. The structure is automatically garbage collected when the Python object is garbage collected.
def _display_matches_gnu_readline(self, substitution: str, matches: List[str], longest_match_length: int) -> None: # pragma: no cover """Prints a match list using GNU readline's rl_display_match_list() This exists to print self.display_matches if it has data. Other...
Prints a match list using GNU readline's rl_display_match_list() This exists to print self.display_matches if it has data. Otherwise matches prints. :param substitution: the substitution written to the command line :param matches: the tab completion matches to display :param longest_mat...
def get(self, request, customer_uuid): """ Handle GET request - render linked learners list and "Link learner" form. Arguments: request (django.http.request.HttpRequest): Request instance customer_uuid (str): Enterprise Customer UUID Returns: django....
Handle GET request - render linked learners list and "Link learner" form. Arguments: request (django.http.request.HttpRequest): Request instance customer_uuid (str): Enterprise Customer UUID Returns: django.http.response.HttpResponse: HttpResponse
def get_upstream_fork_point(self): """Get the most recent ancestor of HEAD that occurs on an upstream branch. First looks at the current branch's tracking branch, if applicable. If that doesn't work, looks at every other branch to find the most recent ancestor of HEAD that occur...
Get the most recent ancestor of HEAD that occurs on an upstream branch. First looks at the current branch's tracking branch, if applicable. If that doesn't work, looks at every other branch to find the most recent ancestor of HEAD that occurs on a tracking branch. Returns: ...
def create_presenter(self, request, target_route): """ Create presenter from the given requests and target routes :param request: client request :param target_route: route to use :return: WWebPresenter """ presenter_name = target_route.presenter_name() if self.presenter_collection().has(presenter_name) i...
Create presenter from the given requests and target routes :param request: client request :param target_route: route to use :return: WWebPresenter
def update_lambda_configuration( self, lambda_arn, function_name, handler, description='Zappa Deployment', timeout=30...
Given an existing function ARN, update the configuration variables.
def cache_values(self, results): """ loads into DebugSession cache """ if results is None: # self.fn was probably only used to compute side effects. return elif isinstance(results,np.ndarray): # fn returns single np.ndarray. # re-format it into a list results=[results] # check validity of fn ...
loads into DebugSession cache
def upload_media(self, filename, progress=None): """Upload a file to be hosted on the target BMC This will upload the specified data to the BMC so that it will make it available to the system as an emulated USB device. :param filename: The filename to use, the basename of the p...
Upload a file to be hosted on the target BMC This will upload the specified data to the BMC so that it will make it available to the system as an emulated USB device. :param filename: The filename to use, the basename of the parameter will be given to the bmc. ...
def lfsr_next_one_seed(seed_iter, min_value_shift): """High-quality seeding for LFSR generators. The LFSR generator components discard a certain number of their lower bits when generating each output. The significant bits of their state must not all be zero. We must ensure that when seeding the gen...
High-quality seeding for LFSR generators. The LFSR generator components discard a certain number of their lower bits when generating each output. The significant bits of their state must not all be zero. We must ensure that when seeding the generator. In case generators are seeded from an incr...
def _condition_number(self): """Condition number of x; ratio of largest to smallest eigenvalue.""" ev = np.linalg.eig(np.matmul(self.xwins.swapaxes(1, 2), self.xwins))[0] return np.sqrt(ev.max(axis=1) / ev.min(axis=1))
Condition number of x; ratio of largest to smallest eigenvalue.
def index_worker_output(self, worker_name, md5, index_name, subfield): """ Index worker output with the Indexer. Args: worker_name: 'strings', 'pe_features', whatever md5: the md5 of the sample index_name: the name of the index subfield...
Index worker output with the Indexer. Args: worker_name: 'strings', 'pe_features', whatever md5: the md5 of the sample index_name: the name of the index subfield: index just this subfield (None for all) Returns: Noth...
def _get_orb_lobster(orb): """ Args: orb: string representation of orbital Returns: Orbital """ orb_labs = ["s", "p_y", "p_z", "p_x", "d_xy", "d_yz", "d_z^2", "d_xz", "d_x^2-y^2", "f_y(3x^2-y^2)", "f_xyz", "f_yz^2", "f_z^3", "f_xz^2", "f_z(x^2-y^2)", ...
Args: orb: string representation of orbital Returns: Orbital
def config2(self): """Read the second set of configuration variables and return as a dictionary. **NOTE: This method is supported by firmware v18+.** :rtype: dictionary :Example: >>> a.config2() { 'AMFanOnIdle': 0, 'AMIdleIntervalCount': 0, ...
Read the second set of configuration variables and return as a dictionary. **NOTE: This method is supported by firmware v18+.** :rtype: dictionary :Example: >>> a.config2() { 'AMFanOnIdle': 0, 'AMIdleIntervalCount': 0, 'AMMaxDataArraysInFil...
def _execute_xmpp(connected_callback): """Connects to the XMPP server and executes custom code :param connected_callback: function to execute after connecting :return: return value of the callback """ from indico_chat.plugin import ChatPlugin check_config() jid = ChatPlugin.settings.get('b...
Connects to the XMPP server and executes custom code :param connected_callback: function to execute after connecting :return: return value of the callback
def format_back( number: FormatArg, light: Optional[bool] = False, extended: Optional[bool] = False) -> str: """ Return an escape code for a back color, by number. This is a convenience method for handling the different code types all in one shot. It also handles some...
Return an escape code for a back color, by number. This is a convenience method for handling the different code types all in one shot. It also handles some validation.
def offset(self, offset): """ Move all the intervals in the list by the given ``offset``. :param offset: the shift to be applied :type offset: :class:`~aeneas.exacttiming.TimeValue` :raises TypeError: if ``offset`` is not an instance of ``TimeValue`` """ self.lo...
Move all the intervals in the list by the given ``offset``. :param offset: the shift to be applied :type offset: :class:`~aeneas.exacttiming.TimeValue` :raises TypeError: if ``offset`` is not an instance of ``TimeValue``
def _update_proxy(self, change): """ An observer which sends the state change to the proxy. """ if change['type'] == 'container': #: Only update what's needed self.proxy.update_points(change) else: super(MapPolyline, self)._update_proxy(change)
An observer which sends the state change to the proxy.
def save(self, filename, compressed=True): """ Save a tensor to disk. """ # check for data if not self.has_data: return False # read ext and save accordingly _, file_ext = os.path.splitext(filename) if compressed: if file_ext != COMPRESSED_TENSOR_...
Save a tensor to disk.
def _process(self, word: str) -> List[str]: """ Process a word into a list of strings representing the syllables of the word. This method describes rules for consonant grouping behaviors and then iteratively applies those rules the list of letters that comprise the word, until all the le...
Process a word into a list of strings representing the syllables of the word. This method describes rules for consonant grouping behaviors and then iteratively applies those rules the list of letters that comprise the word, until all the letters are grouped into appropriate syllable groups. ...
def detect_keep_boundary(start, end, namespaces): """a helper to inspect a link and see if we should keep the link boundary """ result_start, result_end = False, False parent_start = start.getparent() parent_end = end.getparent() if parent_start.tag == "{%s}p" % namespaces['text']: # mo...
a helper to inspect a link and see if we should keep the link boundary
def get_from(input_file, property_names): ''' Reads a geojson and returns a list of value tuples, each value corresponding to a property in property_names. Args: input_file (str): File name. property_names: List of strings; each string is a property name. Returns: List ...
Reads a geojson and returns a list of value tuples, each value corresponding to a property in property_names. Args: input_file (str): File name. property_names: List of strings; each string is a property name. Returns: List of value tuples.
def itemconfigure(self, iid, rectangle_options, text_options): """ Configure options of items drawn on the Canvas Low-level access to the individual elements of markers and other items drawn on the timeline Canvas. All modifications are overwritten when the TimeLine is redrawn. ...
Configure options of items drawn on the Canvas Low-level access to the individual elements of markers and other items drawn on the timeline Canvas. All modifications are overwritten when the TimeLine is redrawn.
def import_pyfiles(path): """ Import all *.py files in specified directory. """ n = 0 for pyfile in glob.glob(os.path.join(path, '*.py')): m = import_file(pyfile) IMPORTED_BUILD_SOURCES.append(m) n += 1 return n
Import all *.py files in specified directory.
def dependencies(self): """ Read the contents of the rpm itself :return: """ cpio = self.rpm.gzip_file.read() content = cpio.read() return []
Read the contents of the rpm itself :return:
def set_axis_options(self, row, column, text): """Set additionnal options as plain text.""" subplot = self.get_subplot_at(row, column) subplot.set_axis_options(text)
Set additionnal options as plain text.
def get_stack_info(self, stack): """ Get the template and parameters of the stack currently in AWS Returns [ template, parameters ] """ stack_name = stack['StackId'] try: template = self.cloudformation.get_template( StackName=stack_name)['TemplateBod...
Get the template and parameters of the stack currently in AWS Returns [ template, parameters ]
def top(self, sort_by): """Get the best results according to your custom sort method.""" sort = sorted(self.results, key=sort_by) return sort
Get the best results according to your custom sort method.
def get_slot_nio_bindings(self, slot_number): """ Returns slot NIO bindings. :param slot_number: slot number :returns: list of NIO bindings """ nio_bindings = yield from self._hypervisor.send('vm slot_nio_bindings "{name}" {slot_number}'.format(name=self._name, ...
Returns slot NIO bindings. :param slot_number: slot number :returns: list of NIO bindings
def imagetransformer_b12l_4h_b256_uncond_dr03_tpu(): """works very well on 4x4.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.block_length =...
works very well on 4x4.
def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', token_uri=oauth2client.GOOGLE_TOKEN_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI): """Factory constructor from JSON keyfile. Arg...
Factory constructor from JSON keyfile. Args: service_account_email: string, The email associated with the service account. filename: string, The location of the PKCS#12 keyfile. private_key_password: string, (Optional) Password for PKCS#12 ...
def schedule(self, duration, at=None, delay=None, callback=None): """ schedules the measurement (to execute asynchronously). :param duration: how long to run for. :param at: the time to start at. :param delay: the time to wait til starting (use at or delay). :param callba...
schedules the measurement (to execute asynchronously). :param duration: how long to run for. :param at: the time to start at. :param delay: the time to wait til starting (use at or delay). :param callback: a callback. :return: nothing.
def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result
Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise.
def _do_ffts(detector, stream, Nc): """ Perform ffts on data, detector and denominator boxcar :type detector: eqcorrscan.core.subspace.Detector :param detector: Detector object for doing detecting :type stream: list of obspy.core.stream.Stream :param stream: List of streams processed according ...
Perform ffts on data, detector and denominator boxcar :type detector: eqcorrscan.core.subspace.Detector :param detector: Detector object for doing detecting :type stream: list of obspy.core.stream.Stream :param stream: List of streams processed according to detector :type Nc: int :param Nc: Num...
def load_feather(protein_feather, length_filter_pid=None, copynum_scale=False, copynum_df=None): """Load a feather of amino acid counts for a protein. Args: protein_feather (str): path to feather file copynum_scale (bool): if counts should be multiplied by protein copy number copynum_df...
Load a feather of amino acid counts for a protein. Args: protein_feather (str): path to feather file copynum_scale (bool): if counts should be multiplied by protein copy number copynum_df (DataFrame): DataFrame of copy numbers Returns: DataFrame: of counts with some aggregated ...
def make_plot( self, count, plot=None, show=False, plottype='probability', bar=dict(alpha=0.15, color='b', linewidth=1.0, edgecolor='b'), errorbar=dict(fmt='b.'), gaussian=dict(ls='--', c='r') ): """ Convert histogram counts in array ``count`` into a plot. Args: ...
Convert histogram counts in array ``count`` into a plot. Args: count (array): Array of histogram counts (see :meth:`PDFHistogram.count`). plot (plotter): :mod:`matplotlib` plotting window. If ``None`` uses the default window. Default is ``None``. ...
def type_id(self): """ Shortcut to retrieving the ContentType id of the model. """ try: return ContentType.objects.get_for_model(self.model, for_concrete_model=False).id except DatabaseError as e: raise DatabaseError("Unable to fetch ContentType object, is...
Shortcut to retrieving the ContentType id of the model.
def send_email(Source=None, Destination=None, Message=None, ReplyToAddresses=None, ReturnPath=None, SourceArn=None, ReturnPathArn=None, Tags=None, ConfigurationSetName=None): """ Composes an email message based on input data, and then immediately queues the message for sending. There are several important p...
Composes an email message based on input data, and then immediately queues the message for sending. There are several important points to know about SendEmail : See also: AWS API Documentation Examples The following example sends a formatted email: Expected Output: :example: response =...
def collect_static_files(src_map, dst): """ Collect all static files and move them into a temporary location. This is very similar to the ``collectstatic`` command. """ for rel_src, abs_src in src_map.iteritems(): abs_dst = os.path.join(dst, rel_src) copy_file(abs_src, abs_dst)
Collect all static files and move them into a temporary location. This is very similar to the ``collectstatic`` command.
def dbus_readBytesTwoFDs(self, fd1, fd2, byte_count): """ Reads byte_count from fd1 and fd2. Returns concatenation. """ result = bytearray() for fd in (fd1, fd2): f = os.fdopen(fd, 'rb') result.extend(f.read(byte_count)) f.close() retur...
Reads byte_count from fd1 and fd2. Returns concatenation.
def knock_out(self): """Knockout gene by marking it as non-functional and setting all associated reactions bounds to zero. The change is reverted upon exit if executed within the model as context. """ self.functional = False for reaction in self.reactions: ...
Knockout gene by marking it as non-functional and setting all associated reactions bounds to zero. The change is reverted upon exit if executed within the model as context.
def replace_url_query_values(url, replace_vals): """Replace querystring values in a url string. >>> url = 'http://helloworld.com/some/path?test=5' >>> replace_vals = {'test': 10} >>> replace_url_query_values(url=url, replace_vals=replace_vals) 'http://helloworld.com/some/path?test=10' """ i...
Replace querystring values in a url string. >>> url = 'http://helloworld.com/some/path?test=5' >>> replace_vals = {'test': 10} >>> replace_url_query_values(url=url, replace_vals=replace_vals) 'http://helloworld.com/some/path?test=10'
def get_answers(self): """ Get answers either from inner_hits already present or by searching elasticsearch. """ if 'inner_hits' in self.meta and 'answer' in self.meta.inner_hits: return self.meta.inner_hits.answer.hits return list(self.search_answers())
Get answers either from inner_hits already present or by searching elasticsearch.
def dump_to_store(dataset, store, writer=None, encoder=None, encoding=None, unlimited_dims=None): """Store dataset contents to a backends.*DataStore object.""" if writer is None: writer = ArrayWriter() if encoding is None: encoding = {} variables, attrs = conventions....
Store dataset contents to a backends.*DataStore object.
def fastqtransform(transform, fastq1, fastq2, fastq3, fastq4, keep_fastq_tags, separate_cb, demuxed_cb, cores, fastq1out, fastq2out, min_length): ''' Transform input reads to the tagcounts compatible read layout using regular expressions as defined in a transform file. Outp...
Transform input reads to the tagcounts compatible read layout using regular expressions as defined in a transform file. Outputs new format to stdout.
def load_creditscoring2(cost_mat_parameters=None): """Load and return the credit scoring PAKDD 2009 competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-lik...
Load and return the credit scoring PAKDD 2009 competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-like object, optional (default=None) If not None, mus...
def get_template_loader_for_path(self, path, use_cache=True): ''' Returns a template loader object for the given directory path. For example, get_template_loader('/var/mytemplates/') will return a loader for that specific directory. Normally, you should not have to call this met...
Returns a template loader object for the given directory path. For example, get_template_loader('/var/mytemplates/') will return a loader for that specific directory. Normally, you should not have to call this method. Django automatically adds request.dmp.render() and request.dmp.rende...
def demonize(self): """ do the double fork magic """ # check if a process is already running if access(self.pid_file_name, F_OK): # read the pid file pid = self.read_pid() try: kill(pid, 0) # check if process is running ...
do the double fork magic
def generateAPIRootBody(self): ''' Generates the root library api file's body text. The method calls :func:`~exhale.graph.ExhaleRoot.gerrymanderNodeFilenames` first to enable proper internal linkage between reStructuredText documents. Afterward, it calls :func:`~exhale.graph.Ex...
Generates the root library api file's body text. The method calls :func:`~exhale.graph.ExhaleRoot.gerrymanderNodeFilenames` first to enable proper internal linkage between reStructuredText documents. Afterward, it calls :func:`~exhale.graph.ExhaleRoot.generateViewHierarchies` followed by ...
async def handler(event): """#docs or #ref query: Like #search but shows the query.""" q1 = event.pattern_match.group(1) q2 = urllib.parse.quote(q1) await asyncio.wait([ event.delete(), event.respond(DOCS.format(q1, q2), reply_to=event.reply_to_msg_id) ])
#docs or #ref query: Like #search but shows the query.
def _ipopo_setup_callback(cls, context): # type: (type, FactoryContext) -> None """ Sets up the class _callback dictionary :param cls: The class to handle :param context: The factory class context """ assert inspect.isclass(cls) assert isinstance(context, FactoryContext) if context...
Sets up the class _callback dictionary :param cls: The class to handle :param context: The factory class context
def cookie_name_check(cookie_name): """ Check cookie name for validity. Return True if name is valid :param cookie_name: name to check :return: bool """ cookie_match = WHTTPCookie.cookie_name_non_compliance_re.match(cookie_name.encode('us-ascii')) return len(cookie_name) > 0 and cookie_match is None
Check cookie name for validity. Return True if name is valid :param cookie_name: name to check :return: bool
def check_solution(self, tx_context, flags=None, traceback_f=None): """ tx_context: information about the transaction that the VM may need flags: gives the VM hints about which additional constraints to check """ for t in self.puzzle_and_solution_iterator(tx_context, flags=flags...
tx_context: information about the transaction that the VM may need flags: gives the VM hints about which additional constraints to check
def add_positional_embedding_nd(x, max_length, name=None): """Adds n-dimensional positional embedding. The embeddings add to all positional dimensions of the tensor. Args: x: Tensor with shape [batch, p1 ... pn, depth]. It has n positional dimensions, i.e., 1 for text, 2 for images, 3 for video, etc. ...
Adds n-dimensional positional embedding. The embeddings add to all positional dimensions of the tensor. Args: x: Tensor with shape [batch, p1 ... pn, depth]. It has n positional dimensions, i.e., 1 for text, 2 for images, 3 for video, etc. max_length: int representing static maximum size of any dime...
def modify_calendar_resource(self, calres, attrs): """ :param calres: a zobjects.CalendarResource :param attrs: a dictionary of attributes to set ({key:value,...}) """ attrs = [{'n': k, '_content': v} for k, v in attrs.items()] self.request('ModifyCalendarResource', { ...
:param calres: a zobjects.CalendarResource :param attrs: a dictionary of attributes to set ({key:value,...})
def keypair_from_seed(seed, index=0): """ Generates a deterministic keypair from `seed` based on `index` :param seed: bytes value of seed :type seed: bytes :param index: offset from seed :type index: int :return: dict of the form: { 'private': private_key 'public': public_...
Generates a deterministic keypair from `seed` based on `index` :param seed: bytes value of seed :type seed: bytes :param index: offset from seed :type index: int :return: dict of the form: { 'private': private_key 'public': public_key }
def add_edge(self, a, b): """Used to add edges to the graph. 'a' and 'b' are vertexes and if 'a' or 'b' doesn't exisit then the vertex is created Args: a (hash): is one vertex of the edge b (hash): is another vertext of the edge """ neighbors_of_a = sel...
Used to add edges to the graph. 'a' and 'b' are vertexes and if 'a' or 'b' doesn't exisit then the vertex is created Args: a (hash): is one vertex of the edge b (hash): is another vertext of the edge
def query_requests(cls, admin, eager=False): """Get all pending group requests.""" # Get direct pending request if hasattr(admin, 'is_superadmin') and admin.is_superadmin: q1 = GroupAdmin.query.with_entities( GroupAdmin.group_id) else: q1 = GroupAd...
Get all pending group requests.
def xrange(self, start, stop=None, step=1): """ Get an iterator for this threads chunk of work. This corresponds to using the OpenMP 'dynamic' schedule. """ self._assert_active() if stop is None: start, stop = 0, start with self._queuelock: ...
Get an iterator for this threads chunk of work. This corresponds to using the OpenMP 'dynamic' schedule.
def signalize_extensions(): """DB API 2.0 extension are reported by warnings at run-time.""" warnings.warn("DB-API extension cursor.rownumber used", SalesforceWarning) warnings.warn("DB-API extension connection.<exception> used", SalesforceWarning) # TODO warnings.warn("DB-API extension cursor.connecti...
DB API 2.0 extension are reported by warnings at run-time.
def _assert_struct_type(self, struct, name, types, path=None, extra_info=None): """Asserts that given structure is of any of given types. Args: struct: structure to check name: displayable name of the checked structure (e.g. "run_foo" for section run_foo) types: list...
Asserts that given structure is of any of given types. Args: struct: structure to check name: displayable name of the checked structure (e.g. "run_foo" for section run_foo) types: list/tuple of types that are allowed for given struct path: list with a source file...
def transform_field(instance, source_field_name, destination_field_name, transformation): ''' Does an image transformation on a instance. It will get the image from the source field attribute of the instnace, then call the transformation function with that instance, and finally save that transformed...
Does an image transformation on a instance. It will get the image from the source field attribute of the instnace, then call the transformation function with that instance, and finally save that transformed image into the destination field attribute of the instance. .. note:: If the source...
def update(self, size): """ Update object size to be showed. This method called while uploading :param size: Object size to be showed. The object size should be in bytes. """ if not isinstance(size, int): raise ValueError('{} type can not be displayed. ' ...
Update object size to be showed. This method called while uploading :param size: Object size to be showed. The object size should be in bytes.
def assert_valid_schema(schema: GraphQLSchema) -> None: """Utility function which asserts a schema is valid. Throws a TypeError if the schema is invalid. """ errors = validate_schema(schema) if errors: raise TypeError("\n\n".join(error.message for error in errors))
Utility function which asserts a schema is valid. Throws a TypeError if the schema is invalid.
def visit_Expr(self, node: ast.Expr) -> Optional[ast.Expr]: """Eliminate no-op constant expressions which are in the tree as standalone statements.""" if isinstance( node.value, ( ast.Constant, # type: ignore ast.Name, ast....
Eliminate no-op constant expressions which are in the tree as standalone statements.
def _write_local_schema_file(self, cursor): """ Takes a cursor, and writes the BigQuery schema for the results to a local file system. :return: A dictionary where key is a filename to be used as an object name in GCS, and values are file handles to local files that ...
Takes a cursor, and writes the BigQuery schema for the results to a local file system. :return: A dictionary where key is a filename to be used as an object name in GCS, and values are file handles to local files that contains the BigQuery schema fields in .json format.
def visitor_show(self, visitor_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/visitors#get-a-visitor" api_path = "/api/v2/visitors/{visitor_id}" api_path = api_path.format(visitor_id=visitor_id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/chat/visitors#get-a-visitor
def cli(self, *args, **kwargs): """Defines a CLI function that should be routed by this API""" kwargs['api'] = self.api return cli(*args, **kwargs)
Defines a CLI function that should be routed by this API
def remove(self): """ remove this object from Ariane server :return: null if successfully removed else self """ LOGGER.debug("Cluster.remove - " + self.name) if self.id is None: return None else: params = SessionService.complete_transaction...
remove this object from Ariane server :return: null if successfully removed else self
def add_model_string(self, model_str, position=1, file_id=None): """Add a kappa model given in a string to the project.""" if file_id is None: file_id = self.make_unique_id('inlined_input') ret_data = self.file_create(File.from_string(model_str, position, ...
Add a kappa model given in a string to the project.
def get_info(self): ''' :rtype: dictionary :return: field information ''' info = { 'name': self.name if self.name else '<no name>', 'path': self.name if self.name else '<no name>', 'field_type': type(self).__name__, 'value': { ...
:rtype: dictionary :return: field information
def scale(self, image, size, crop, options): """ Wrapper for ``engine_scale``, checks if the scaling factor is below one or that scale_up option is set to True before calling ``engine_scale``. :param image: :param size: :param crop: :param options: :retur...
Wrapper for ``engine_scale``, checks if the scaling factor is below one or that scale_up option is set to True before calling ``engine_scale``. :param image: :param size: :param crop: :param options: :return:
def reindex_all(self, batch_size=1000): """ Reindex all the records. By default, this method use Model.objects.all() but you can implement a method `get_queryset` in your subclass. This can be used to optimize the performance (for example with select_related or prefetch_related)...
Reindex all the records. By default, this method use Model.objects.all() but you can implement a method `get_queryset` in your subclass. This can be used to optimize the performance (for example with select_related or prefetch_related).
def rbridge_id(self, **kwargs): """Configures device's rbridge ID. Setting this property will need a switch reboot Args: rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric. get (bool): Get config instead of edit...
Configures device's rbridge ID. Setting this property will need a switch reboot Args: rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric. get (bool): Get config instead of editing config. (True, False) callb...
def scrape_args(self, records, executable='raxmlHPC-AVX', partition_files=None, model=None, outfiles=None, threads=1, parsimony=False, fast_tree=False, n_starts=1): """ Examine a list of records and generate RAxML command line arguments for tree inference. ...
Examine a list of records and generate RAxML command line arguments for tree inference. :param records: list of `Alignment` records :param executable: name of the RAxML executable on the system to use. Must be in the user's path. :param partition_files: List of RAxML partition files used to desc...
def ParseFileObject(self, parser_mediator, file_object): """Parses a Firefox cache file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: ...
Parses a Firefox cache file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
def summary_data_from_transaction_data( transactions, customer_id_col, datetime_col, monetary_value_col=None, datetime_format=None, observation_period_end=None, freq="D", freq_multiplier=1, ): """ Return summary data from transactions. This transforms a DataFrame of transact...
Return summary data from transactions. This transforms a DataFrame of transaction data of the form: customer_id, datetime [, monetary_value] to a DataFrame of the form: customer_id, frequency, recency, T [, monetary_value] Parameters ---------- transactions: :obj: DataFrame ...
def get(self, sid): """ Constructs a ConnectAppContext :param sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppContext :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppContext """ return...
Constructs a ConnectAppContext :param sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.connect_app.ConnectAppContext :rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppContext
def delete_keys(d: Dict[Any, Any], keys_to_delete: List[Any], keys_to_keep: List[Any]) -> None: """ Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are d...
Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are deleted... keys_to_keep: ... unless they are present in this list.
def assert_no_selector(self, *args, **kwargs): """ Asserts that a given selector is not on the page or a descendant of the current node. Usage is identical to :meth:`assert_selector`. Query options such as ``count``, ``minimum``, and ``between`` are considered to be an integral ...
Asserts that a given selector is not on the page or a descendant of the current node. Usage is identical to :meth:`assert_selector`. Query options such as ``count``, ``minimum``, and ``between`` are considered to be an integral part of the selector. This will return True, for example, if a page...
def data_filler_user_agent(self, number_of_rows, pipe): '''creates keys with user agent data ''' try: for i in range(number_of_rows): pipe.hmset('user_agent:%s' % i, { 'id': rnd_id_generator(self), 'ip': self.faker.ipv4(), ...
creates keys with user agent data
def _force_disconnect_action(self, action): """Forcibly disconnect a device. Args: action (ConnectionAction): the action object describing what we are forcibly disconnecting """ conn_key = action.data['id'] if self._get_connection_state(conn_key) == ...
Forcibly disconnect a device. Args: action (ConnectionAction): the action object describing what we are forcibly disconnecting