text
stringlengths
78
104k
score
float64
0
0.18
def sigterm(self) -> None: '''Handle SIGTERM from the system by stopping tasks gracefully. Repeated signals will be ignored while waiting for tasks to finish.''' if self.stop_attempts < 1: Log.info('received SIGTERM, gracefully stopping tasks') self.stop_attempts += 1 ...
0.004662
def calc_el_lz_v1(self): """Calculate lake evaporation. Required control parameters: |NmbZones| |ZoneType| |TTIce| Required derived parameters: |RelZoneArea| Required fluxes sequences: |TC| |EPC| Updated state sequence: |LZ| Basic equa...
0.000464
def QA_util_if_tradetime( _time=datetime.datetime.now(), market=MARKET_TYPE.STOCK_CN, code=None ): '时间是否交易' _time = datetime.datetime.strptime(str(_time)[0:19], '%Y-%m-%d %H:%M:%S') if market is MARKET_TYPE.STOCK_CN: if QA_util_if_trade(str(_time.date())[0:10]): i...
0.008904
def extractall(archive, filename, dstdir): """ extract zip or tar content to dstdir""" if zipfile.is_zipfile(archive): z = zipfile.ZipFile(archive) for name in z.namelist(): targetname = name # directories ends with '/' (on Windows as well) if targetname....
0.002974
def properties_operator(cls, name): """Wraps a container operator to ensure container class is maintained""" def wrapper(self, *args, **kwargs): """Perform operation and cast to container class""" output = getattr(super(cls, self), name)(*args, **kwargs) return cls(output) wrapped ...
0.002288
def _setup_stats_plugins(self): ''' Sets up the plugin stats collectors ''' self.stats_dict['plugins'] = {} for key in self.plugins_dict: plugin_name = self.plugins_dict[key]['instance'].__class__.__name__ temp_key = 'stats:redis-monitor:{p}'.format(p=plug...
0.008299
def with_wait_cursor(func): """ Show a wait cursor while the wrapped function is running. The cursor is restored as soon as the function exits. :param func: wrapped function """ @functools.wraps(func) def wrapper(*args, **kwargs): QApplication.setOverrideCursor( QCursor(...
0.002
def start_raylet(redis_address, node_ip_address, raylet_name, plasma_store_name, worker_path, temp_dir, num_cpus=None, num_gpus=None, resources=None, object_manager_po...
0.000152
def get_temperature(self): """Get current temperature in celsius.""" try: request = requests.get( '{}/temp'.format(self.resource), timeout=self.timeout, allow_redirects=False) self.temperature = request.json()['compensated'] return self.temperature ...
0.005917
def describe_consumer_groups(self, group_ids, group_coordinator_id=None): """Describe a set of consumer groups. Any errors are immediately raised. :param group_ids: A list of consumer group IDs. These are typically the group names as strings. :param group_coordinator_id: Th...
0.001811
def checkformat(self): """************************************************************************************************************************************************************ Task: checks the format of the bed file. The only requirements checked are that each line presents at least 3 tab separat...
0.004898
def get_executor(self, create=1): """Fetch the action executor for this node. Create one if there isn't already one, and requested to do so.""" try: executor = self.executor except AttributeError: if not create: raise try: ...
0.003472
def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None): """Validate an RRset against a single signature rdata The owner name of the rrsig is assumed to be the same as the owner name of the rrset. @param rrset: The RRset to validate @type rrset: dns.rrset.RRset or (dns.name.Name, dns.rdatas...
0.002097
def _get_data(filenames): """Read data from file(s) or STDIN. Args: filenames (list): List of files to read to get data. If empty or None, read from STDIN. """ if filenames: data = "" for filename in filenames: with open(filename, "rb") as f: ...
0.002506
def create_normal_matrix(self, modelview): """ Creates a normal matrix from modelview matrix Args: modelview: The modelview matrix Returns: A 3x3 Normal matrix as a :py:class:`numpy.array` """ normal_m = Matrix33.from_matrix44(modelview) ...
0.004866
def get_collection(self, path): """To get pagewise data.""" while True: items = self.get(path) req = self.req for item in items: yield item if req.links and req.links['next'] and\ req.links['next']['rel'] == 'next': ...
0.004963
def bind(self, func: Callable[[Any], IO]) -> IO: """IO a -> (a -> IO b) -> IO b""" g = self._value return Get(lambda text: g(text).bind(func))
0.011976
def access_SUSY_dataset_format_file(filename): """ This function accesses a CSV file containing data of the form of the [SUSY dataset](https://archive.ics.uci.edu/ml/datasets/SUSY), i.e. with the first column being class labels and other columns being features. """ # Load the CSV file to a list....
0.007886
def _parse_samples(self, io_bytes): """ _parse_samples: binary data in XBee IO data format -> [ {"dio-0":True, "dio-1":False, "adc-0":100"}, ...] _parse_samples reads binary data from an XBee device in the IO ...
0.001988
def _get_parser(self, env): """ Creates base argument parser. `env` Runtime ``Environment`` instance. * Raises ``HelpBanner`` exception when certain conditions apply. Returns ``FocusArgumentParser`` object. """ version_str = 'focus vers...
0.000725
def scan(self, M): """ LML, fixed-effect sizes, and scale of the candidate set. Parameters ---------- M : array_like Fixed-effects set. Returns ------- lml : float Log of the marginal likelihood. effsizes0 : ndarray ...
0.001273
def get_matching_multiplex_port(self,name): """ Given a name, figure out if a multiplex port prefixes this name and return it. Otherwise return none. """ # short circuit: if the attribute name already exists return none # if name in self._portnames: return None # if no...
0.009459
def port_profile_vlan_profile_switchport_mode_vlan_mode(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, "name")...
0.004082
def verify_token_string(self, token_string, action=None, timeout=None, current_time=None): """Generate a hash of the given token contents that can be verified. :param token_string: ...
0.007771
def get_file_extension(filepath): """ Copy if anyconfig.utils.get_file_extension is not available. >>> get_file_extension("/a/b/c") '' >>> get_file_extension("/a/b.txt") 'txt' >>> get_file_extension("/a/b/c.tar.xz") 'xz' """ _ext = os.path.splitext(filepath)[-1] if _ext: ...
0.002571
def get_app_template_dir(app_name): """Get the template directory for an application Uses apps interface available in django 1.7+ Returns a full path, or None if the app was not found. """ if app_name in _cache: return _cache[app_name] template_dir = None for app in apps.get_app_co...
0.00202
def render_value(self, value, **options): """Render value""" renderer = self.renderers.get(type(value), lambda value, **options: value) return renderer(value, **options)
0.015544
def _repeat(self, index, stage, stop): """ Repeat a stage. :param index: Stage index. :param stage: Stage object to repeat. :param iterations: Number of iterations (default infinite). :param stages: Stages back to repeat (default 1). """ times = None if '...
0.002307
def cache_func(func, duration=conf.GOSCALE_CACHE_DURATION, cache_key=None): """Django cache decorator for functions Basic ideas got from: - http://djangosnippets.org/snippets/492/ - http://djangosnippets.org/snippets/564/ Example usage: Example 1: - providing a cache key and a duratio...
0.005548
def _backsearch(self): """ Inspect previous peaks from the last detected qrs peak (if any), using a lower threshold """ if self.last_qrs_peak_num is not None: for peak_num in range(self.last_qrs_peak_num + 1, self.peak_num + 1): if self._is_qrs(peak_n...
0.007092
def bin(self, n_bins=1, pixels_per_bin=None, wave_min=None, wave_max=None): """ Break the filter up into bins and apply a throughput to each bin, useful for G141, G102, and other grisms Parameters ---------- n_bins: int The number of bins to dice the throughp...
0.002256
def _expand(self, normalization, csphase, **kwargs): """Expand the grid into real spherical harmonics.""" if normalization.lower() == '4pi': norm = 1 elif normalization.lower() == 'schmidt': norm = 2 elif normalization.lower() == 'unnorm': norm = 3 ...
0.001996
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
0.019305
def buildSources(self, sourceTime=None): """ Return a dictionary of date/time tuples based on the keys found in self.re_sources. The current time is used as the default and any specified item found in self.re_sources is inserted into the value and the generated dictionar...
0.006098
def Sample(self, operation, description, data_size, compressed_data_size): """Takes a sample of data read or written for profiling. Args: operation (str): operation, either 'read' or 'write'. description (str): description of the data read. data_size (int): size of the data read in bytes. ...
0.001669
def lipd_to_df(metadata, csvs): """ Create an organized collection of data frames from LiPD data :param dict metadata: LiPD data :param dict csvs: Csv data :return dict: One data frame per table, organized in a dictionary by name """ dfs = {} logger_dataframes.info("enter lipd_to_df") ...
0.003341
def get_settings(self, index): """Get settings for index. :param index: index name """ settings = self.es.indices.get_settings(index=index) return next(iter(settings.values()))
0.009217
def get_recipe_env(self, arch, with_flags_in_cc=True): """ Add libgeos headers to path """ env = super(ShapelyRecipe, self).get_recipe_env(arch, with_flags_in_cc) libgeos_dir = Recipe.get_recipe('libgeos', self.ctx).get_build_dir(arch.arch) env['CFLAGS'] += " -I{}/dist/include".format(li...
0.008596
def _escape_filterargs(self, filterargs): """ Escapes values in filterargs. filterargs is a value suitable for Django's string formatting operator (%), which means it's either a tuple or a dict. This return a new tuple or dict with all values escaped for use in filter strings. ...
0.003731
def compute_Pi_J(self, CDR3_seq, J_usage_mask): """Compute Pi_J. This function returns the Pi array from the model factors of the J genomic contributions, P(delJ|J). This corresponds to J(D)^{x_4}. For clarity in parsing the algorithm implementation, we include which ...
0.012873
def scale_and_shift(self, scale_pct, shift_pct, callback=True): """Stretch and/or shrink the color map via altering the shift map. """ maxlen = self.maxc + 1 self.sarr = np.arange(maxlen) # limit shrinkage to 5% of original size scale = max(scale_pct, 0.050) self...
0.001508
def revokeSystemPermission(self, login, user, perm): """ Parameters: - login - user - perm """ self.send_revokeSystemPermission(login, user, perm) self.recv_revokeSystemPermission()
0.00463
def build_acl_port(self, port, enabled=True): "Build the acl for L4 Ports. " if port is not None: if ':' in port: range = port.replace(':', ' ') acl = "range %(range)s " % {'range': range} else: acl = "eq %(port)s " % {'port': port}...
0.004843
def get_copy(dict_, key, default=None): """ Looks for a key in a dictionary, if found returns a deepcopied value, otherwise returns default value """ value = dict_.get(key, default) if value: return deepcopy(value) return value
0.00678
async def kick_chat_member(self, chat_id: typing.Union[base.Integer, base.String], user_id: base.Integer, until_date: typing.Union[base.Integer, None] = None) -> base.Boolean: """ Use this method to kick a user from a group, a supergroup or a channel. In the case o...
0.006207
async def resolution(self): """Get the resolution voted on. Returns ------- awaitable of :class:`aionationstates.ResolutionAtVote` The resolution voted for. Raises ------ aionationstates.NotFound If the resolution has since been passed or...
0.002797
def user_role_add(user_id=None, user=None, tenant_id=None, tenant=None, role_id=None, role=None, profile=None, project_id=None, project_name=None, **connection_args): ''' Add role for user in tenant (keystone user-role-add) CLI Examples: .. code-block:: bash ...
0.000466
def load_image(name): """Load an image""" image = pyglet.image.load(name).texture verify_dimensions(image) return image
0.007407
def clean_value(self, value): ''' Additional clean action to preprocess value before :meth:`to_python` method. Subclasses may define own clean_value method to allow additional clean actions like html cleanup, etc. ''' # We have to clean before checking min/max le...
0.003289
def to_python(self, value): ''' Coerce data from primitive form to native Python types. Returns the default type (if exists) ''' try: if value is None and self._default is not None: return self.default self._check_required(value) ...
0.003788
def tofits(outfilename, pixelarray, hdr = None, verbose = True): """ Takes a 2D numpy array and write it into a FITS file. If you specify a header (pyfits format, as returned by fromfits()) it will be used for the image. You can give me boolean numpy arrays, I will convert them into 8 bit integers. ...
0.016615
def from_warc(warc_record): """ Extracts relevant information from a WARC record. This function does not invoke scrapy but only uses the article extractor. :return: """ html = str(warc_record.raw_stream.read()) url = warc_record.rec_headers.get_header('WARC-Target...
0.007937
def OauthAuthorizeApplication(self, oauth_duration = 'hour'): """ Authorize an application using oauth. If this function returns True, the obtained oauth token can be retrieved using getResponse and will be in url-parameters format. TODO: allow the option to ask the user himself for p...
0.011059
def _set_where(self): """ Set the where clause for the relation query. :return: self :rtype: BelongsToMany """ foreign = self.get_foreign_key() self._query.where(foreign, "=", self._parent.get_key()) return self
0.007194
def __git_tag_push(): """ Push all tags. The function call will return 0 if the command success. """ command = ['git', 'push', 'origin', '--tags'] Shell.msg('Pushing tags...') if APISettings.DEBUG: Git.__debug(command, True) if not call(comma...
0.00542
def download_file(self, filename): """Download a file from device to local filesystem""" res = self.__exchange('send("{filename}")'.format(filename=filename)) if ('unexpected' in res) or ('stdin' in res): log.error('Unexpected error downloading file: %s', res) raise Excep...
0.006237
def hide_samples(portal): """Removes samples views from everywhere, related indexes, etc. """ logger.info("Removing Samples from navbar ...") if "samples" in portal: portal.manage_delObjects(["samples"]) def remove_samples_action(content_type): type_info = content_type.getTypeInfo()...
0.000765
def get_joke(): """Return a Ron Swanson quote. Returns None if unable to retrieve a quote. """ page = requests.get("http://ron-swanson-quotes.herokuapp.com/v2/quotes") if page.status_code == 200: jokes = [] jokes = json.loads(page.content.decode(page.encoding)) return ...
0.005391
def upsert(self, conflict_target: List, fields: Dict, index_predicate: str=None) -> int: """Creates a new record or updates the existing one with the specified data. Arguments: conflict_target: Fields to pass into the ON CONFLICT clause. fields: ...
0.009449
def sparse_grid_from_unmasked_sparse_grid(unmasked_sparse_grid, sparse_to_unmasked_sparse): """Use the central arc-second coordinate of every unmasked pixelization grid's pixels and mapping between each pixelization pixel and unmasked pixelization pixel to compute the central arc-second coordinate of every mask...
0.006938
def _expand_error_codes(code_parts): """Return an expanded set of error codes to ignore.""" codes = set(ErrorRegistry.get_error_codes()) expanded_codes = set() try: for part in code_parts: # Dealing with split-lined configurations; The part might begin ...
0.002148
def add_to_group(self, devices): """Add device(s) to the group.""" ids = {d.id for d in self.devices_in_group()} ids.update(self._device_ids(devices)) self._set_group(ids)
0.009852
def show_description(self): """ Prints the formatted response for the matching return type """ def print_missing(c, v): resp = self.responses[v["type"]] name = "[%s] %s" % (resp.label, dr.get_name(c)) self.print_header(name, 3) print(file=self.stream) ...
0.002378
def load_datafile(name, search_path=('.'), codecs=get_codecs(), **kwargs): """ find datafile and load them from codec TODO only does the first one kwargs: default = if passed will return that on failure instead of throwing """ mod = find_datafile(name, search_path, codecs) if not mod: ...
0.005505
def user_sentiments_most_frequent( self, username = None, single_most_frequent = True ): """ This function returns the most frequent calculated sentiments expressed in tweets of a specified user. By default, the single most frequent sentiment i...
0.011848
def parse_record(self, raw, indx=0): """Parse raw data (that is retrieved by "request") and return pandas.DataFrame. Returns tuple (data, metadata) data - pandas.DataFrame with retrieved data. metadata - pandas.DataFrame with info about symbol, currency, frequency, ...
0.003011
def prettyPrintSequence(self, sequence, verbosity=1): """ Pretty print a sequence. @param sequence (list) Sequence @param verbosity (int) Verbosity level @return (string) Pretty-printed text """ text = "" for i in xrange(len(sequence)): pattern = sequence[i] if pattern ...
0.010345
def find_all(soup, name=None, attrs=None, recursive=True, text=None, limit=None, **kwargs): """The `find` and `find_all` methods of `BeautifulSoup` don't handle the `text` parameter combined with other parameters. This is necessary for e.g. finding links containing a string or pattern. This me...
0.002252
def maybe_store_highlights(file_id, data, tfidf, kvlclient): '''wrapper around :func:`create_highlights` that stores the response payload in the `kvlayer` table called `highlights` as a stored value if data['store'] is `False`. This allows error values as well as successful responses from :func:`create...
0.001479
def load_config(filename): ''' Read contents of config file. ''' try: with open(filename, 'r') as config_file: return json.loads(config_file.read()) except IOError: pass
0.004608
def _get_worker_id(self, conn): """Get the worker ID, using a preestablished connection.""" if self._worker_id is None: self._worker_id = conn.incr(self._key_worker()) return self._worker_id
0.00885
def export_agg_risk_csv(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ writer = writers.CsvWriter(fmt=writers.FIVEDIGITS) path = '%s.%s' % (sanitize(ekey[0]), ekey[1]) fname = dstore.export_path(path) writer.save(dstore['a...
0.002762
def column_summary_data(self): '''Returns a dictionary of column name -> value, for cluster-level results''' assembled_summary = self._to_cluster_summary_assembled() pct_id, read_depth = self._pc_id_and_read_depth_of_longest() columns = { 'assembled': self._to_cluster_summar...
0.006897
def ignore_exception(exception_class): """A decorator that ignores `exception_class` exceptions""" def _decorator(func): def newfunc(*args, **kwds): try: return func(*args, **kwds) except exception_class: pass return newfunc return _dec...
0.003067
def create_filehandlers(self, filenames, fh_kwargs=None): """Organize the filenames into file types and create file handlers.""" filenames = list(OrderedDict.fromkeys(filenames)) logger.debug("Assigning to %s: %s", self.info['name'], filenames) self.info.setdefault('filenames', []).exte...
0.002155
def update(self): """Calulate the auxilary term. >>> from hydpy.models.llake import * >>> parameterstep('1d') >>> simulationstep('12h') >>> n(3) >>> v(0., 1e5, 1e6) >>> q(_1=[0., 1., 2.], _7=[0., 2., 5.]) >>> maxdt('12h') >>> derived.seconds.updat...
0.002717
def project_activity(index, start, end): """Compute the metrics for the project activity section of the enriched git index. Returns a dictionary containing a "metric" key. This key contains the metrics for this section. :param index: index object :param start: start date to get the data from ...
0.00177
def AddColumn(self, column, default="", col_index=-1): """Appends a new column to the table. Args: column: A string, name of the column to add. default: Default value for entries. Defaults to ''. col_index: Integer index for where to insert new column. Raises: TableError: Colum...
0.00246
def _fetch_xml(self, url): """Fetch a url and parse the document's XML.""" with contextlib.closing(urlopen(url)) as f: return xml.etree.ElementTree.parse(f).getroot()
0.010309
def predict_percentile(self, X, ancillary_X=None, p=0.5): """ Returns the median lifetimes for the individuals, by default. If the survival curve of an individual does not cross 0.5, then the result is infinity. http://stats.stackexchange.com/questions/102986/percentile-loss-functions ...
0.003971
def _send_size(self): " Report terminal size to server. " rows, cols = _get_size(sys.stdout.fileno()) self._send_packet({ 'cmd': 'size', 'data': [rows, cols] })
0.009259
def _make_repr(class_name, *args, **kwargs): """ Generate a repr string. Positional arguments should be the positional arguments used to construct the class. Keyword arguments should consist of tuples of the attribute value and default. If the value is the default, then it won't be rendered in ...
0.001235
def get_index_labels(self, targets): """Get the labels(known target/not) mapped to indices. :param targets: List of known targets :return: Dictionary of index-label mappings """ target_ind = self.graph.vs.select(name_in=targets).indices rest_ind = self.graph.vs.select(na...
0.004141
def agent_url(self): """ This method returns the agent's url. :return: """ try: if self._data_from_search: agent = self._data_from_search.find('ul', {'class': 'links'}) links = agent.find_all('a') return links[1]['href']...
0.004886
def transformer_image_decoder(targets, encoder_output, ed_attention_bias, hparams, name=None): """Transformer image decoder over targets with local attention. Args: targets: Tensor of shape [...
0.001632
def post_state(self, name, state): """Asynchronously try to update the state for a service. If the update fails, nothing is reported because we don't wait for a response from the server. This function will return immmediately and not block. Args: name (string): The...
0.00381
def create_database(self, name, owner=None): """ Create a new MapD database Parameters ---------- name : string Database name """ statement = ddl.CreateDatabase(name, owner=owner) self._execute(statement)
0.007168
def check_exists(path, type='file'): """ Check if a file or a folder exists """ if type == 'file': if not os.path.isfile(path): raise RuntimeError('The file `%s` does not exist.' % path) else: if not os.path.isdir(path): raise RuntimeError('The folder `%s` does not e...
0.002849
def reduce(self): """Reduce to a canonical form.""" support = frozenset(range(1, self.nvars+1)) new_clauses = set() for clause in self.clauses: vs = list(support - {abs(uniqid) for uniqid in clause}) if vs: for num in range(1 << len(vs)): ...
0.00335
def valueFromString(self, value, context=None): """ Converts the inputted string text to a value that matches the type from this column type. :param value | <str> extra | <variant> """ if value in ('today', 'now'): return datetime.dat...
0.00237
def translate_input(translator, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, **kwargs): ''' Translate CLI/SLS input into the format the API expects. The ``translator`` argument must be a module containin...
0.000519
def _connect(self, host, port, proc, timeout_seconds): """Connect to the websocket, retrying as needed. Returns the socket.""" if ":" in host and not host.startswith("["): # Support ipv6 addresses. host = "[%s]" % host url = "ws://%s:%s/sc2api" % (host, port) was_running = False for i in ran...
0.010135
def _merge_dicts(dics, container=dict): """ :param dics: [<dict/-like object must not have same keys each other>] :param container: callble to make a container object :return: <container> object >>> _merge_dicts(({}, )) {} >>> _merge_dicts(({'a': 1}, )) {'a': 1} >>> sorted(kv for kv...
0.001887
def to_camel_case(text): """Convert to camel case. :param str text: :rtype: str :return: """ split = text.split('_') return split[0] + "".join(x.title() for x in split[1:])
0.004975
def get_ratefactor(self, base, code): """ Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError Yahoo currently uses USD as base currency, but here we detect it with get_baserate """ raise RuntimeError("%s Deprecated: API withdrawn ...
0.006878
def enqueue(self, priority: int, item: TItem) -> bool: """Adds an entry to the priority queue. If drop_duplicate_entries is set and there is already a (priority, item) entry in the queue, then the enqueue is ignored. Check the return value to determine if an enqueue was kept or dropped....
0.001873
def write(_filename, _long, enter=True): """Write the call info to file""" def method(*arg, **kw): # pylint: disable=W0613 """Reference to the advice in order to facilitate argument support.""" def get_short(_fname): """Get basename of the file. If file is __init__.py, get its direc...
0.00278
def count_words(pattern): """ Count the number of words in a pattern as well as the total length of those words :param pattern: The pattern to parse :type pattern: str :return: The word count first, then the total length of all words :rtype : tuple of (int, int) ...
0.00678
def build_api_struct(self): """ Calls the clean method of the class and returns the info in a structure that Atlas API is accepting. """ self.clean() r = { "type": self._type, "requested": self._requested, "value": self._value }...
0.005051
def status(name='all'): ''' Using drbdadm to show status of the DRBD devices, available in the latest drbd9. Support multiple nodes, multiple volumes. :type name: str :param name: Resource name. :return: drbd status of resource. :rtype: list(dict(res)) CLI Example: .....
0.002423