text
stringlengths
78
104k
score
float64
0
0.18
def _check_remote_option(self, option): """Test the status of remote negotiated Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() return self.telnet_opt_dict[option].remote_option
0.010909
def update(m, k, f, *args): """Updates the value for key k in associative data structure m with the return value from calling f(old_v, *args). If m is None, use an empty map. If k is not in m, old_v will be None.""" if m is None: return lmap.Map.empty().assoc(k, f(None, *args)) if isinstance...
0.005618
def delaunay3D(dataset, alpha=0, tol=None, boundary=True): """Create 3D Delaunay triangulation of input points.""" deln = vtk.vtkDelaunay3D() deln.SetInputData(dataset) deln.SetAlpha(alpha) if tol: deln.SetTolerance(tol) deln.SetBoundingTriangulation(boundary)...
0.005348
def hdf5_storable(type_or_storable, *args, **kwargs): '''Registers a `Storable` instance in the global service.''' if not isinstance(type_or_storable, Storable): type_or_storable = default_storable(type_or_storable) hdf5_service.registerStorable(type_or_storable, *args, **kwargs)
0.003333
def find_path(self, node_source, node_target, type='nodes'): """Determines shortest path Determines the shortest path from `node_source` to `node_target` in _graph using networkx' shortest path algorithm. Args ---- node_source: GridDing0 source node,...
0.005105
def publishApp(self, app_info, map_info=None, fsInfo=None): """Publishes apps to AGOL/Portal Args: app_info (list): A list of JSON configuration apps to publish. map_info (list): Defaults to ``None``. fsInfo (list): Defaults to ``None``. Returns: ...
0.00807
def modifyDatastream(self, pid, dsID, dsLabel=None, mimeType=None, logMessage=None, dsLocation=None, altIDs=None, versionable=None, dsState=None, formatURI=None, checksumType=None, checksum=None, content=None, force=False): '''Modify an existing datastream, similar to :meth:`addDatastraem`. ...
0.002483
def _parse_team_abbreviation(self, stats): """ Parse the team abbreviation. The team abbreviation is embedded within the team name tag and should be special-parsed to extract it. Parameters ---------- stats : PyQuery object A PyQuery object containin...
0.00277
def refresh_config(self): ''' __NB__ This *must* be called from a *different* thread than the GUI/Gtk thread. ''' from gi.repository import Clutter, Gst, GstVideo, ClutterGst from path_helpers import path from .warp import bounding_box_from_allocation if self.con...
0.001338
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. ...
0.009267
def on_failure(self, exc, task_id, args, kwargs, einfo): """ If the task fails, persist a record of the task. """ if not FailedTask.objects.filter(task_id=task_id, datetime_resolved=None).exists(): FailedTask.objects.create( task_name=_truncate_to_field(Failed...
0.007634
def translate(self, address): """ Translates the given address to another address specific to network or service. :param address: (:class:`~hazelcast.core.Address`), private address to be translated :return: (:class:`~hazelcast.core.Address`), new address if given address is known, othe...
0.008292
def send(self, jlink): """Starts the SWD transaction. Steps for a Write Transaction: 1. First phase in which the request is sent. 2. Second phase in which an ACK is received. This phase consists of three bits. An OK response has the value ``1``. 3. Everyt...
0.001597
def set_payload(self, payload): """Set stanza payload to a single item. All current stanza content of will be dropped. Marks the stanza dirty. :Parameters: - `payload`: XML element or stanza payload object to use :Types: - `payload`: :etree:`ElementTree....
0.009449
def from_node(index, value): """ >>> h = TimelineHistory.from_node(1, 2) >>> h.lines [] """ try: lines = json.loads(value) except (TypeError, ValueError): lines = None if not isinstance(lines, list): lines = [] r...
0.005525
def points(self): """ returns a pointer to the points as a numpy object """ # Get grid dimensions nx, ny, nz = self.dimensions nx -= 1 ny -= 1 nz -= 1 # get the points and convert to spacings dx, dy, dz = self.spacing # Now make the cell arrays ...
0.006154
def set_custom(sld, tld, nameservers): ''' Sets domain to use custom DNS servers. returns True if the custom nameservers were set successfully sld SLD of the domain name tld TLD of the domain name nameservers array of strings List of nameservers to be associated with...
0.003322
def run_(self): """ DEPRECATED """ all_records = [] for k in range(self.num_classes): simulated_records = self.alf_params[k + 1].run() names = ['class{0}_{1:0>{2}}'.format(k + 1, i, len(str(self.class_list[k]))) for i in ra...
0.00646
def escape(s, fold_newlines=True): """Escapes a string to make it usable in LaTeX text mode. Will replace special characters as well as newlines. Some problematic characters like ``[`` and ``]`` are escaped into groups (e.g. ``{[}``), because they tend to cause problems when mixed with ``\\`` newli...
0.001136
def insertAfter(self, child, afterChild): ''' insertAfter - Inserts a child after #afterChild @param child <AdvancedTag/str> - Child block to insert @param afterChild <AdvancedTag/str> - Child block to insert after. if None, will be appended @return -...
0.006216
def render_text(self, request, instance, context): """ Custom rendering function for HTML output """ render_template = self.get_render_template(request, instance, email_format='text') if not render_template: # If there is no TEXT variation, create it by removing the H...
0.006431
def get_environment_config(): """ Returns all the Turi Create configuration variables that can only be set via environment variables. - *TURI_FILEIO_WRITER_BUFFER_SIZE*: The file write buffer size. - *TURI_FILEIO_READER_BUFFER_SIZE*: The file read buffer size. - *OMP_NUM_THREADS*: The maximum n...
0.003559
def add_string(self, name, help, required=True, default=None): """ Add a new option with a type of String. :param str name: The name of the option, how it will be referenced. :param str help: The string returned as help to describe how the option is used. :param bool required: Whether to require that this op...
0.021622
def julian2sidereal(Jdate: float) -> float: """ Convert Julian time to sidereal time D. Vallado Ed. 4 Parameters ---------- Jdate: float Julian centuries from J2000.0 Results ------- tsr : float Sidereal time """ jdate = np.atleast_1d(Jdate) assert ...
0.001242
def _get_tmp_account_id(cls, writer_spec): """Returns the account id to use with tmp bucket.""" # pick tmp id iff tmp bucket is set explicitly if cls.TMP_BUCKET_NAME_PARAM in writer_spec: return writer_spec.get(cls._TMP_ACCOUNT_ID_PARAM, None) return cls._get_account_id(writer_spec)
0.006557
def set_params(self, deep=False, force=False, **parameters): """ sets an object's paramters Parameters ---------- deep : boolean, default: False when True, also sets non-user-facing paramters force : boolean, default: False when True, also sets pa...
0.004981
def _freq_parser(self, freq): """Parse timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() valid_keywords = [ "day...
0.001663
def _prepare_controller(self, controller, template): """ Wraps the controller wether to render a jinja template or to return a json response (if template is None) Args: controller (coroutine): the coroutine to be wrapped template (str): the name of the template or None ...
0.005059
def hover_on_element(driver, selector, by=By.CSS_SELECTOR): """ Fires the hover event for the specified element by the given selector. @Params driver - the webdriver object (required) selector - the locator (css selector) that is used (required) by - the method to search for the locator (Default...
0.002079
def report_message(message, level='error', request=None, extra_data=None, payload_data=None): """ Reports an arbitrary string message to Rollbar. message: the string body of the message level: level to report at. One of: 'critical', 'error', 'warning', 'info', 'debug' request: the request object fo...
0.008208
def export_to_dom(self): """ Exports this model to a DOM. """ namespaces = 'xmlns="http://www.neuroml.org/lems/%s" ' + \ 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + \ 'xsi:schemaLocation="http://www.neuroml.org/lems/%s %s"' ...
0.010771
def _updated_cb(self, downtotal, downdone, uptotal, updone): """ Emit update signal, including transfer status metadata. """ self.emit('updated', downtotal, downdone, uptotal, updone)
0.01005
def get_messages(self, limit=25, *, query=None, order_by=None, batch=None, download_attachments=False): """ Downloads messages from this folder :param int limit: limits the result set. Over 999 uses batch. :param query: applies a filter to the request such as ...
0.001782
def uisetup(ui): """Setup pre-/post- hooks""" for hooktype in PREPOST_HOOKS: ui.setconfig("hooks", "pre-" + hooktype + ".autohooks", autohook) ui.setconfig("hooks", "post-" + hooktype + ".autohooks", autohook)
0.004292
def copy_traj_attributes(target, origin, start): """ Inserts certain attributes of origin into target :param target: target trajectory object :param origin: origin trajectory object :param start: :py:obj:`origin` attributes will be inserted in :py:obj:`target` starting at this index :return: target:...
0.003764
def parse_select(cls, text: str) -> Set: """ get columns from select text :param text: col1, col2 :return: ALL_COLUMNS or ['col1', 'col2'] """ if text == '*': return ALL_COLUMNS # None means ALL selected_columns = set(filter(lambda x: x, map(str.strip...
0.006494
def build_table_schema(data, index=True, primary_key=None, version=True): """ Create a Table schema from ``data``. Parameters ---------- data : Series, DataFrame index : bool, default True Whether to include ``data.index`` in the schema. primary_key : bool or None, default True ...
0.000397
def aggregate_history(slugs, granularity="daily", since=None, with_data_table=False): """Template Tag to display history for multiple metrics. * ``slug_list`` -- A list of slugs to display * ``granularity`` -- the granularity: seconds, minutes, hourly, daily, weekly, monthly, yearl...
0.001464
def clip_or_fit_solutions(self, pop, idx): """make sure that solutions fit to sample distribution, this interface will probably change. In particular the frequency of long vectors appearing in pop[idx] - self.mean is limited. """ for k in idx: self.repair_genotype(pop[k])
0.012579
def render_to_string(self, env, **kwargs): """Render this template. :param dict env: The WSGI environment associated with the request causing this template to be rendered :param any kwargs: The keyword arguments to be supplied to the Jninja template render method :return: The rendered t...
0.004898
def cmd_layout(self, args): '''handle layout command''' from MAVProxy.modules.lib import win_layout if len(args) < 1: print("usage: layout <save|load>") return if args[0] == "load": win_layout.load_layout(self.mpstate.settings.vehicle_name) eli...
0.004866
def handle_new_events(self, events): """Add each new events to the event queue.""" for event in events: self.events.append( self.create_event_object( event[0], event[1], int(event[2])))
0.00692
def __proxy_password(self): """Returning the password and immediately destroying it""" passwd = copy(self._inp_proxy_password.value) self._inp_proxy_password.value = '' return passwd
0.009346
def ping(): ''' Is the chassis responding? :return: Returns False if the chassis didn't respond, True otherwise. ''' r = __salt__['dracr.system_info'](host=DETAILS['host'], admin_username=DETAILS['admin_username'], admin_p...
0.001876
def getRegularAnalyses(self): """ Return the analyses assigned to the current worksheet that are directly associated to an Analysis Request but are not QC analyses. This is all analyses that implement IRoutineAnalysis :return: List of regular analyses :rtype: List of Refe...
0.003752
def _load_nnp(self, rel_name, rel_url): ''' Args: rel_name: relative path to where donwloaded nnp is saved. rel_url: relative url path to where nnp is downloaded from. ''' from nnabla.utils.download import download path_nnp = os.path.join(...
0.002398
def validate_arguments_type_of_function(param_type=None): """ Decorator to validate the <type> of arguments in the calling function are of the `param_type` class. if `param_type` is None, uses `param_type` as the class where it is used. Note: Use this decorator on the functions of the class. "...
0.000959
def items(self, obj): """ Items are the published entries of the tag. """ return TaggedItem.objects.get_by_model( Entry.published.all(), obj)[:self.limit]
0.010101
def _request(self, lat_min, lon_min, lat_max, lon_max, start, end, picture_size=None, set_=None, map_filter=None): """ Internal method to send requests to the Panoramio data API. :param lat_min: Minimum latitude of the bounding box :type lat_min: float :param lon_min...
0.005432
def market_snapshot(self, prefix=False): """return all market quotation snapshot :param prefix: if prefix is True, return quotation dict's stock_code key start with sh/sz market flag """ return self.get_stock_data(self.stock_list, prefix=prefix)
0.006873
def micro_calc(TP, item): """ Calculate PPV_Micro and TPR_Micro. :param TP: true positive :type TP:dict :param item: FN or FP :type item : dict :return: PPV_Micro or TPR_Micro as float """ try: TP_sum = sum(TP.values()) item_sum = sum(item.values()) return TP...
0.002564
def learn(self, spiro, iterations=1): '''Train short term memory with given spirograph. :param spiro: :py:class:`SpiroArtifact` object ''' for i in range(iterations): self.stmem.train_cycle(spiro.obj.flatten())
0.007491
def printer(self): """ Returns a printer that was defined in the config, or throws an exception. This method loads the default config if one hasn't beeen already loaded. """ if not self._has_loaded: self.load() if not self._printer_name: raise e...
0.006309
def _find_files(self, entries, root, relative_path, file_name_regex): """ Return the elements in entries that 1. are in ``root/relative_path``, and 2. match ``file_name_regex``. :param list entries: the list of entries (file paths) in the container :param string root: t...
0.001369
def quantiles(x, num_quantiles, axis=None, interpolation=None, keep_dims=False, validate_args=False, name=None): """Compute quantiles of `x` along `axis`. The quantiles of a distribution are cut points dividing the range into int...
0.002321
def load_all(path, include_core=True, subfolders=None, path_in_arc=None): """ Loads a full IO system with all extension in path Parameters ---------- path : pathlib.Path or string Path or path with para file name for the data to load. This must either point to the directory containing t...
0.000436
def save_function_effect(module): """ Recursively save function effect for pythonic functions. """ for intr in module.values(): if isinstance(intr, dict): # Submodule case save_function_effect(intr) else: fe = FunctionEffects(intr) IntrinsicArgumentEffects[in...
0.002336
def getStateIndex(self,state): """ Returns the index of a state by calculating the state code and searching for this code a sorted list. Can be called on multiple states at once. """ statecodes = self.getStateCode(state) return np.searchsorted(self.codes,statecodes).astyp...
0.015337
def hz2cents(freq_hz, base_frequency=10.0): """Convert an array of frequency values in Hz to cents. 0 values are left in place. Parameters ---------- freq_hz : np.ndarray Array of frequencies in Hz. base_frequency : float Base frequency for conversion. (Default value = 1...
0.001441
def language_contents(instance): """Ensure keys in Language Content's 'contents' dictionary are valid language codes, and that the keys in the sub-dictionaries match the rules for object property names. """ if instance['type'] != 'language-content' or 'contents' not in instance: return ...
0.002203
def _read_triplets_dataframe(filename): """ Reads the original dataset TSV as a pandas dataframe """ # delay importing this to avoid another dependency import pandas # read in triples of user/artist/playcount from the input dataset # get a model based off the input params start = time.time() ...
0.002789
def get_timeout(self, callback=None): """ Get the visibility timeout for the queue. :rtype: int :return: The number of seconds as an integer. """ def got_timeout(a): if callable(callback): callback(int(a['VisibilityTimeout'])) ...
0.007853
def build_response(headers: Headers, key: str) -> None: """ Build a handshake response to send to the client. ``key`` comes from :func:`check_request`. """ headers["Upgrade"] = "websocket" headers["Connection"] = "Upgrade" headers["Sec-WebSocket-Accept"] = accept(key)
0.003356
def update_file(filename, result, content, indent): """Updates a Jekyll file to contain the counts form an object This just converts the results to YAML and adds to the Jekyll frontmatter. Args: filename: the Jekyll file to update result: the results object from `wc` content: the c...
0.000911
def sys_chdir(self, path): """ chdir - Change current working directory :param int path: Pointer to path """ path_str = self.current.read_string(path) logger.debug(f"chdir({path_str})") try: os.chdir(path_str) return 0 except OSErro...
0.00565
def getChild(self, path, request): """ This is necessary because the parent class would call proxy.ReverseProxyResource instead of CacheProxyResource """ return CacheProxyResource( self.host, self.port, self.path + '/' + urlquote(path, safe=""), self.react...
0.006024
def get_in(keys, coll, default=None, no_default=False): """ NB: This is a straight copy of the get_in implementation found in the toolz library (https://github.com/pytoolz/toolz/). It works with persistent data structures as well as the corresponding datastructures from the stdlib. ...
0.000636
def v1_tag_suggest(request, tags, prefix, parent=''): '''Provide fast suggestions for tag components. This yields suggestions for *components* of a tag and a given prefix. For example, given the tags ``foo/bar/baz`` and ``fob/bob``, here are some example completions (ordering may be different): ...
0.000864
def disk_xml(identifier, pool_xml, base_volume_xml, cow): """Clones volume_xml updating the required fields. * name * target path * backingStore """ pool = etree.fromstring(pool_xml) base_volume = etree.fromstring(base_volume_xml) pool_path = pool.find('.//path').text base_path ...
0.001156
def collection(self, code): """ Retrieve the collection ids according to the given 3 letters acronym """ result = None result = self.dispatcher( 'get_collection', code=code ) if not result: logger.info('Collection not found for...
0.005277
def get_readonly_fields(self, request, obj=None): """ This is required a subclass of VersionedAdmin has readonly_fields ours won't be undone """ if obj: return list(self.readonly_fields) + ['id', 'identity', 'is_current...
0.005587
def _robust_rmtree(path, logger=None, max_retries=5): """Try to delete paths robustly . Retries several times (with increasing delays) if an OSError occurs. If the final attempt fails, the Exception is propagated to the caller. Taken from https://github.com/hashdist/hashdist/pull/116 """ for i...
0.001479
def add_menu(self, menu): '''add a new menu''' self.menu.add(menu) self.mpstate.console.set_menu(self.menu, self.menu_callback)
0.013245
def convolve_stack(data, kernel, rot_kernel=False, method='scipy'): r"""Convolve stack of data with stack of kernels This method convolves the input data with a given kernel using FFT and is the default convolution used for all routines Parameters ---------- data : np.ndarray Input dat...
0.000611
def _K(m): """ matrix K_m from Wiktorsson2001 """ M = m*(m - 1)//2 K = np.zeros((M, m**2), dtype=np.int64) row = 0 for j in range(1, m): col = (j - 1)*m + j s = m - j K[row:(row+s), col:(col+s)] = np.eye(s) row += s return K
0.003571
def choice_voters_changed_update_cache( sender, instance, action, reverse, model, pk_set, **kwargs): """Update cache when choice.voters changes.""" if action not in ('post_add', 'post_remove', 'post_clear'): # post_clear is not handled, because clear is called in # django.db.models.field...
0.000994
def match(self, path_pattern): """ Return True if this path matches the given pattern. """ cf = self._flavour.casefold path_pattern = cf(path_pattern) drv, root, pat_parts = self._flavour.parse_parts((path_pattern,)) if not pat_parts: raise ValueError(...
0.002296
def index_by_id(cls, target_id, resources): """Helper method to fetch the index of a resource by its id or address Args: resources (list of objects): The resources to be paginated target_id (string): The address or header_signature of the resource Returns: i...
0.003241
def remove_node(self, node, stop=False): """Removes a node from the cluster. By default, it doesn't also stop the node, just remove from the known hosts of this cluster. :param node: node to remove :type node: :py:class:`Node` :param stop: Stop the node :type s...
0.003306
def metadata(func): """Add metadata to an item. Decorator that adds metadata to a given item such as the gelk revision used. """ @functools.wraps(func) def decorator(self, *args, **kwargs): eitem = func(self, *args, **kwargs) metadata = { 'metadata__gelk_version': s...
0.001802
def toString(self, format_='fasta-ss', structureSuffix=':structure'): """ Convert the read to a string in PDB format (sequence & structure). This consists of two FASTA records, one for the sequence then one for the structure. @param format_: Either 'fasta-ss' or 'fasta'. In the ...
0.0018
def get_filepath_findex_from_user(self, wildcard, message, style, filterindex=0): """Opens a file dialog and returns filepath and filterindex Parameters ---------- wildcard: String \tWildcard string for file dialog message: String ...
0.002788
def has_job(self, job): """ Checks whether there exists another job which has the same job key. :param job: The job to check. :return: True if there exists another job with the same key, False otherwise. """ job_key = self._job_key(job) return job_key in self....
0.009146
def init_module(path): """Attempt to import a Python module located at path. If successful, and if the newly imported module has an init() function, then set the global PATH in order to simplify the add_bundle() interface and call init() on the module, passing the current global namespace, conveni...
0.002591
def _get_hashed_params(self, page_text): """Get hashed params which will be used when you login, see issue#10""" soup = BeautifulSoup(page_text, 'html.parser') return [tag['name'] for tag in soup.find_all('input', class_='sl')]
0.007968
def parse_header_line(self, line): """docstring for parse_header_line""" self.header = line[1:].rstrip().split('\t') if len(self.header) < 9: self.header = line[1:].rstrip().split() self.individuals = self.header[9:]
0.007692
def __merge_clusters(self, cluster1, cluster2): """! @brief Merges two clusters and returns new merged cluster. Representation points and mean points are calculated for the new cluster. @param[in] cluster1 (cure_cluster): Cluster that should be merged. @param[in] cluster2 (...
0.011418
def start_check (aggregate, out): """Start checking in background and write encoded output to out.""" # check in background t = threading.Thread(target=director.check_urls, args=(aggregate,)) t.start() # time to wait for new data sleep_seconds = 2 # current running time run_seconds = 0 ...
0.003425
def _get_credentials(vcap_services, service_name=None): """Retrieves the credentials of the VCAP Service of the specified `service_name`. If `service_name` is not specified, it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment variable. Args: vcap_services (dict): A dict ...
0.005181
def from_path(cls, conn, path): """Create container from path.""" path = path.strip(SEP) full_path = os.path.join(conn.abs_root, path) return cls(conn, path, 0, os.path.getsize(full_path))
0.009091
def _GetArgs(self): """ Parse plusargs. """ parser = argparse.ArgumentParser() parser.add_argument('-s', '--src', help='override database source directory') parser.add_argument('-d', '--dst', help='override database destination directory') parser.add_argument('-e', '--extract', help='enable extract...
0.012211
def from_mult_iters(cls, name=None, idx=None, **kwargs): """Load values from multiple iters Parameters ---------- name : string, default None Name of the data set. If None (default), the name will be set to ``'table'``. idx: string, default None ...
0.00131
def make_key(table_name, objid): """Create an object key for storage.""" key = datastore.Key() path = key.path_element.add() path.kind = table_name path.name = str(objid) return key
0.004878
def convert_timestamp(timestamp): """ Converts bokehJS timestamp to datetime64. """ datetime = dt.datetime.utcfromtimestamp(timestamp/1000.) return np.datetime64(datetime.replace(tzinfo=None))
0.004717
def resolve_remove_symbols(self, r, target_group_ids, rgroups): """Resolve the resources security groups that need be modified. Specifically handles symbolic names that match annotations from policy filters for groups being removed. """ if 'matched' in target_group_ids: ...
0.004249
def remote(fn, name=None, types=None): """Decorator that adds a remote attribute to a function. fn -- function being decorated name -- aliased name of the function, used for remote proxies types -- a argument type specifier, can be used to ensure arguments are of the correct type """ ...
0.002358
def generate_tuple_zip(self, token_list, n=2): ''' Generate the N-gram. Args: token_list: The list of tokens. n N Returns: zip of Tuple(N-gram) ''' return zip(*[token_list[i:] for i in range(n)])
0.006452
async def geoadd(self, name, *values): """ Add the specified geospatial items to the specified key identified by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad latitude, longitude and ...
0.00361
def stop(self): """Stop all of the connections.""" _logger.debug("Emitting quit signal for connections.") self.__quit_ev.set() _logger.info("Waiting for connection manager to stop.") self.__manage_g.join()
0.008097
def get_web_auth_url(self): """ The user must open this page, and you first, then call get_web_auth_session_key(url) after that. """ token = self._get_web_auth_token() url = "{homepage}/api/auth/?api_key={api}&token={token}".format( homepage=self.network.hom...
0.006865