text
stringlengths
78
104k
score
float64
0
0.18
def bool_env(key, default=False): """Parse an environment variable as a boolean switch `True` is returned if the variable value matches one of the following: - ``'1'`` - ``'y'`` - ``'yes'`` - ``'true'`` The match is case-insensitive (so ``'Yes'`` will match as `True`) Parameters ...
0.000963
def optimize(thumbnail_file, jpg_command=None, png_command=None, gif_command=None): """ A post processing function to optimize file size. Accepts commands to optimize JPG, PNG and GIF images as arguments. Example: THUMBNAILS = { # Other options... 'POST_PROCESSORS': [ ...
0.000635
def damping(temp, relhum, freq, pres=101325): """ Calculates the damping factor for sound in dB/m depending on temperature, humidity and sound frequency. Source: http://www.sengpielaudio.com/LuftdaempfungFormel.htm temp: Temperature in degrees celsius relhum: Relative humidity as percentage, e....
0.003823
def _resolve_memory_references(self, expression: Expression) -> Union[float, int]: """ Traverse the given Expression, and replace any Memory References with whatever values have been so far provided by the user for those memory spaces. Declared memory defaults to zero. :param ex...
0.007365
def infer_format(filename:str) -> str: """Return extension identifying format of given filename""" _, ext = os.path.splitext(filename) return ext
0.012739
def _extract_stats_from_line(self, txt, stats_delim=' ', val_delim=':'): """ extracts the stats from a line of text to the class params STR:7 AGI:9 STA:5 INT:5 Health:21 CON:8 max_health:21 """ result = {} stats_txt = txt.split(stats_delim) for s in stats_txt: ...
0.007692
def _setup_root_filesystem(self, root_dir): """Setup the filesystem layout in the given root directory. Create a copy of the existing proc- and dev-mountpoints in the specified root directory. Afterwards we chroot into it. @param root_dir: The path of the root directory that is used to ...
0.006162
def _dtype(cls, tensor: tf.Tensor) -> tf.Tensor: '''Converts `tensor` to tf.float32 datatype if needed.''' if tensor.dtype != tf.float32: tensor = tf.cast(tensor, tf.float32) return tensor
0.008929
def plot_phens(phen_grid, **kwargs): """ Plots circles colored according to the values in phen_grid. -1 serves as a sentinel value, indicating that a circle should not be plotted in that location. """ denom, palette = get_kwargs(phen_grid, kwargs, True) grid = color_grid(phen_grid, palette...
0.001543
def get_netconf_client_capabilities_output_session_host_ip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_netconf_client_capabilities = ET.Element("get_netconf_client_capabilities") config = get_netconf_client_capabilities output = ET.SubEle...
0.00495
def _function_contents(func): """ The signature is as follows (should be byte/chars): < _code_contents (see above) from func.__code__ > ,( comma separated _object_contents for function argument defaults) ,( comma separated _object_contents for any closure contents ) See also: https://docs.pyth...
0.002978
def get_parent_var(name, global_ok=False, default=None, skip_frames=0): """ Directly gets a variable from a parent frame-scope. Returns -------- Any The content of the variable found by the given name, or None. """ scope = get_parent_scope_from_var(name, global_ok=global_ok, skip_f...
0.003953
def _set_env_from_extras(self, extras): """ Sets the environment variable `GOOGLE_APPLICATION_CREDENTIALS` with either: - The path to the keyfile from the specified connection id - A generated file's path if the user specified JSON in the connection id. The file is assumed t...
0.004702
def _from_dict(cls, _dict): """Initialize a Conversions object from a json dictionary.""" args = {} if 'pdf' in _dict: args['pdf'] = PdfSettings._from_dict(_dict.get('pdf')) if 'word' in _dict: args['word'] = WordSettings._from_dict(_dict.get('word')) if '...
0.002646
def predictions(dev_dataset, all_results, tokenizer, max_answer_length=64, null_score_diff_threshold=0.0, n_best_size=10, version_2=False): """Get prediction results Parameters ---------- dev_dataset: datase...
0.001226
def notify_admin_of_new_comment(comID): """ Sends an email to the admin with details regarding comment with ID = comID """ comment = query_get_comment(comID) if len(comment) > 0: (comID2, id_bibrec, id_user, body, date_creation, star_score, nb_vot...
0.00135
def dump_environment(self): """ Try to dump memory Not currently implemented feature :return: None """ # Dump the Alignak configuration to a temporary ini file path = os.path.join(tempfile.gettempdir(), 'dump-env-%s-%s-%d.ini' % (self.type, s...
0.006623
def _dissociate_gene(self, cobra_gene): """Dissociates a cobra.Gene object with a cobra.Reaction. Parameters ---------- cobra_gene : cobra.core.Gene.Gene """ self._genes.discard(cobra_gene) cobra_gene._reaction.discard(self)
0.007092
def factory(ec, code=None, token=None, refresh=None, **kwargs): """ Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance """ TTYPE = {'code': 'A', 'token': 'T', 'refresh': 'R'} args = {} if code: args['code_handler'] = init_...
0.005051
def hash(value, chars=None): 'Get N chars (default: all) of secure hash hexdigest of value.' value = hash_func(value).hexdigest() if chars: value = value[:chars] return mark_safe(value)
0.031746
def reinforce_grid(self): """ Performs grid reinforcement measures for all MV and LV grids Args: Returns: """ # TODO: Finish method and enable LV case for grid_district in self.mv_grid_districts(): # reinforce MV grid grid_district.mv_grid.rein...
0.003205
def gene_id_check(genes, errors, columns, row_number): """ Validate gene identifiers against a known set. Parameters ---------- genes : set The known set of gene identifiers. errors : Passed by goodtables. columns : Passed by goodtables. row_number : Pass...
0.001085
def get_shell(self): """ Return shell which is currently bound to Help, or another running shell if it has been terminated """ if (not hasattr(self.shell, 'get_doc') or (hasattr(self.shell, 'is_running') and not self.shell.is_running())): ...
0.002861
def _get_list(self, value, context=None): """ Get a configuration value. The result is None if "value" is None, otherwise the result is a list. "value" may be a list, dict, or str value. If a list, each element of the list may be a list, dict, or str value, and the val...
0.001362
def bothify(self, text='## ??', letters=string.ascii_letters): """ Replaces all placeholders with random numbers and letters. :param text: string to be parsed :returns: string with all numerical and letter placeholders filled in """ return self.lexify(self.numerify(text)...
0.005917
def _load_script(self): """Loads the script from the filesystem :raises exceptions.IOError: if the script file could not be opened """ script_text = filesystem.read_file(self.path, self.filename) if not script_text: raise IOError("Script file could not be opened or ...
0.004484
def team_players(self, team): """Store output of team players to a CSV file""" headers = ['Jersey Number', 'Name', 'Position', 'Nationality', 'Date of Birth'] result = [headers] result.extend([player['shirtNumber'], player['name'], ...
0.003846
def SetCacheMode(mode): """Set the Configure cache mode. mode must be one of "auto", "force", or "cache".""" global cache_mode if mode == "auto": cache_mode = AUTO elif mode == "force": cache_mode = FORCE elif mode == "cache": cache_mode = CACHE else: raise Va...
0.002646
def position(self): """ Returns the current position of the motor in pulses of the rotary encoder. When the motor rotates clockwise, the position will increase. Likewise, rotating counter-clockwise causes the position to decrease. Writing will set the position to that value. ...
0.004695
def get_number_of_partitions_for(self, ar): """Return the number of selected partitions """ # fetch the number of partitions from the request uid = api.get_uid(ar) num = self.request.get("primary", {}).get(uid) if num is None: # get the number of partitions f...
0.002994
def set_logfile(path, instance): """Specify logfile path""" global logfile logfile = os.path.normpath(path) + '/hfos.' + instance + '.log'
0.006623
def update_payload(self, fields=None): """Wrap submitted data within an extra dict.""" payload = super(JobTemplate, self).update_payload(fields) effective_user = payload.pop(u'effective_user', None) if effective_user: payload[u'ssh'] = {u'effective_user': effective_user} ...
0.005602
def split(self, spike_ids=None, spike_clusters_rel=0): """Split the selected spikes.""" if spike_ids is None: spike_ids = self.emit('request_split', single=True) spike_ids = np.asarray(spike_ids, dtype=np.int64) assert spike_ids.dtype == np.int64 assert sp...
0.002601
def channel(self, rpc_timeout=60, lazy=False): """Open Channel. :param int rpc_timeout: Timeout before we give up waiting for an RPC response from the server. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel...
0.001721
def _kill(self, variable, code_loc): # pylint:disable=no-self-use """ Kill previous defs. addr_list is a list of normalized addresses. """ # Case 1: address perfectly match, we kill # Case 2: a is a subset of the original address # Case 3: a is a superset of the origina...
0.003995
def query(self, time_indices): """Query the values at given time indices. Args: time_indices: 0-based time indices to query, as a `list` of `int`. Returns: Values as a list of `numpy.ndarray` (for time indices in memory) or `None` (for time indices discarded). """ if self._dispos...
0.007442
def row_contributions(self, X): """Returns the row contributions towards each principal component. Each row contribution towards each principal component is equivalent to the amount of inertia it contributes. This is calculated by dividing the squared row coordinates by the eigenvalue a...
0.009766
def iMath_propagate_labels_through_mask(image, labels, stopping_value=100, propagation_method=0): """ >>> import ants >>> wms = ants.image_read('~/desktop/wms.nii.gz') >>> thal = ants.image_read('~/desktop/thal.nii.gz') >>> img2 = ants.iMath_propagate_labels_through_mask(wms, thal, 500, 0) """ ...
0.007212
def remove_observer(self, callback): """Remove an observer from this event. Args: callback: A function or coroutine callback to remove from this event. Raises: ValueError: If the callback is not an observer of this event. """ if callback ...
0.004024
def _get_params_for_optimizer(self, prefix, named_parameters): """Parse kwargs configuration for the optimizer identified by the given prefix. Supports param group assignment using wildcards: optimizer__lr=0.05, optimizer__param_groups=[ ('rnn*.period', {'lr': 0....
0.001965
def _pack_prms(): """if you introduce new 'save-able' parameter dictionaries, then you have to include them here""" config_dict = { "Paths": prms.Paths.to_dict(), "FileNames": prms.FileNames.to_dict(), "Db": prms.Db.to_dict(), "DbCols": prms.DbCols.to_dict(), "DataSe...
0.001565
def get_links(self, request=None): """ Return a dictionary containing all the links that should be included in the API schema. """ links = LinkNode() # Generate (path, method, view) given (path, method, callback). paths = [] view_endpoints = [] fo...
0.002309
def add_resource(self, resource): '''Perform an atomic prepend for a new resource''' resource.validate() self.update(__raw__={ '$push': { 'resources': { '$each': [resource.to_mongo()], '$position': 0 } ...
0.004338
def phrase_contains_special_keys(expansion: model.Expansion) -> bool: """ Determine if the expansion contains any special keys, including those resulting from any processed macros (<script>, <file>, etc). If any are found, the phrase cannot be undone. Python Zen: »In the face of ambigui...
0.007282
def datetime2unix(T): """ converts datetime to UT1 unix epoch time """ T = atleast_1d(T) ut1_unix = empty(T.shape, dtype=float) for i, t in enumerate(T): if isinstance(t, (datetime, datetime64)): pass elif isinstance(t, str): try: ut1_unix...
0.001253
def sign(self, keys: list) -> None: """ Sign the current document. Warning : current signatures will be replaced with the new ones. :param keys: List of libnacl key instances :return: """ if not isinstance(self.identity, Identity): raise MalformedDocu...
0.006791
def _generate_ascii(self, matrix, foreground, background): """ Generates an identicon "image" in the ASCII format. The image will just output the matrix used to generate the identicon. Arguments: matrix - Matrix describing which blocks in the identicon should be pai...
0.003755
def time_series( self, start_date='-30d', end_date='now', precision=None, distrib=None, tzinfo=None): """ Returns a generator yielding tuples of ``(<datetime>, <value>)``. The data points will start at ``start_date``, and b...
0.003774
def share(self, plotters, keys=None, draw=None, auto_update=False): """ Share the formatoptions of this plotter with others This method shares the formatoptions of this :class:`Plotter` instance with others to make sure that, if the formatoption of this changes, those of the oth...
0.001321
def hangup(self): """ End the phone call. Does nothing if the call is already inactive. """ if self.active: self._gsmModem.write('ATH') self.answered = False self.active = False if self.id in self._gsmModem.activeCalls: del...
0.008427
def _cnvkit_segment(cnr_file, cov_interval, data, items, out_file=None, detailed=False): """Perform segmentation and copy number calling on normalized inputs """ if not out_file: out_file = "%s.cns" % os.path.splitext(cnr_file)[0] if not utils.file_uptodate(out_file, cnr_file): with file...
0.004262
def received_raw(self): """ Return a list of all received headers in raw format """ output = [] for i in self.message.get_all("received", []): output.append(decode_header_part(i)) return output
0.007905
def OnRefreshSelectedCells(self, event): """Event handler for refreshing the selected cells via menu""" self.grid.actions.refresh_selected_frozen_cells() self.grid.ForceRefresh() event.Skip()
0.008889
def add_state_segments(self, *args, **kwargs): """DEPRECATED: use :meth:`Plot.add_segments_bar` """ warnings.warn('add_state_segments() was renamed add_segments_bar(), ' 'this warning will result in an error in the future', DeprecationWarning) ...
0.005479
def alwaysCalledWith(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is always called with partial args/kwargs Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.alwaysCalledWith(*args, **kwargs)): raise cls.fail...
0.011696
def create_tar (archive, compression, cmd, verbosity, interactive, filenames): """Create a TAR archive with the tarfile Python module.""" mode = get_tar_mode(compression) try: with tarfile.open(archive, mode) as tfile: for filename in filenames: tfile.add(filename) ex...
0.004454
def GET(self, url): """returns text content of HTTP GET response.""" r = requests.get(url) if self.verbose: sys.stdout.write("%s %s\n" % (r.status_code, r.encoding)) sys.stdout.write(str(r.headers) + "\n") self.encoding = r.encoding return r.text
0.006452
def request_help(self, req, msg): """Return help on the available requests. Return a description of the available requests using a sequence of #help informs. Parameters ---------- request : str, optional The name of the request to return help for (the defaul...
0.001213
def mean_interval(data, alpha=_alpha): """ Interval assuming gaussian posterior. """ mean =np.mean(data) sigma = np.std(data) scale = scipy.stats.norm.ppf(1-alpha/2.) return interval(mean,mean-scale*sigma,mean+scale*sigma)
0.016
def clear(self): """ Clear any existing values from this queue. """ logger.debug('Clearing queue: "%s"', self.name) return self.redis.delete(self.name)
0.011429
def _create_session( self, alias, url, headers, cookies, auth, timeout, max_retries, backoff_factor, proxies, verify, debug, disable_warnings): """ Create S...
0.004305
def show_ordering_diagram(analyser, amount_clusters = None): """! @brief Display cluster-ordering (reachability-plot) diagram. @param[in] analyser (ordering_analyser): cluster-ordering analyser whose ordering diagram should be displayed. @param[in] amount_clusters (uint): i...
0.018465
def resize(im, short, max_size): """ only resize input image to target size and return scale :param im: BGR image input by opencv :param short: one dimensional size (the short side) :param max_size: one dimensional max size (the long side) :return: resized image (NDArray) and scale (float) "...
0.002639
def _windows_system_appdata(): """ Return the path to the Windows Common App Data folder. On Windows 7, for example, this is C:\\ProgramData :return: String reprsentation the path to the Windows Common App Data folder """ # Could also use os.environ['ALLUSERSPROFILE'] - maybe? ...
0.001214
def set_webhook_handler(self, scope, callback): """ Allows adding a webhook_handler as an alternative to the decorators """ scope = scope.lower() if scope == 'after_send': self._after_send = callback return if scope not in Page.WEBHOOK_ENDPOINTS:...
0.006342
def list_logdir(self, id, filter=None, sort=None): # pylint: disable=invalid-name,redefined-builtin """Get a list of logdir files. :param id: Result ID as an int. :param filter: Filter to apply as string. :param sort: Sort field to apply as string. :return: :class:`results.LogDi...
0.007449
async def execute_async(self, operation, op_type, message, timeout=0): """Execute a request and wait on a response asynchronously. :param operation: The type of operation to be performed. This value will be service-specific, but common values include READ, CREATE and UPDATE. This valu...
0.004887
def buy_market_order(self, amount): """Place a buy order at market price. :param amount: Amount of major currency to buy at market price. :type amount: int | float | str | unicode | decimal.Decimal :return: Order details. :rtype: dict """ amount = str(amount) ...
0.003802
def cudnnGetConvolution2dDescriptor(convDesc): """" Get a convolution descriptor. This function queries a previously initialized 2D convolution descriptor object. Parameters ---------- convDesc : cudnnConvolutionDescriptor Handle to a previously created convolution descriptor. Ret...
0.006565
def combine_comments(comments): ''' Given a list of comments, or a comment submitted as a string, return a single line of text containing all of the comments. ''' if isinstance(comments, list): for idx in range(len(comments)): if not isinstance(comments[idx], six.string_types): ...
0.001727
async def viewers_js(request): ''' Viewers determines the viewers installed based on settings, then uses the conversion infrastructure to convert all these JS files into a single JS bundle, that is then served. As with media, it will simply serve a cached version if necessary. ''' # Generate...
0.000647
def approximation(self, latitude, longitude): """ Dummy approximation with nearest points. The nearest the neighbour the more important will be its elevation. """ d = 1. / self.square_side d_meters = d * mod_utils.ONE_DEGREE # Since the less the distance => the m...
0.011444
def menu_callback(m): '''called on menu selection''' if m.returnkey.startswith('# '): cmd = m.returnkey[2:] if m.handler is not None: if m.handler_result is None: return cmd += m.handler_result process_stdin(cmd) elif m.returnkey == 'menuSettin...
0.001736
def _construct_regex(cls, fmt): """Given a format string, construct the regex with class attributes.""" return re.compile(fmt.format(**vars(cls)), flags=re.U)
0.011494
def AddNEP5Token(self, token): """ Add a NEP-5 compliant token to the wallet. Args: token (NEP5Token): an instance of type neo.Wallets.NEP5Token. Note: Prints a warning to the console if the token already exists in the wallet. """ if token.Script...
0.006173
def pop(self): """ Removes the last traversal path node from this traversal path. """ node = self.nodes.pop() self.__keys.remove(node.key)
0.011236
def get_version(): """Return the version of the Sparser executable on the path. Returns ------- version : str The version of Sparser that is found on the Sparser path. """ assert sparser_path is not None, "Sparser path is not defined." with open(os.path.join(sparser_path, 'version.t...
0.002564
def initialize_time(self, control_freq): """ Initializes the time constants used for simulation. """ self.cur_time = 0 self.model_timestep = self.sim.model.opt.timestep if self.model_timestep <= 0: raise XMLError("xml model defined non-positive time step") ...
0.003591
def lock_retention_policy(self, client=None): """Lock the bucket's retention policy. :raises ValueError: if the bucket has no metageneration (i.e., new or never reloaded); if the bucket has no retention policy assigned; if the bucket's retention policy is already loc...
0.004039
def createPen(self, altStyle=None, altWidth=None): """ Creates a pen from the config values with the style overridden by altStyle if the None-option is selected in the combo box. """ pen = self.configValue if pen is not None: style = self.findByNodePath('style')....
0.005926
def run(self): """Run command.""" for ext in ['*.so', '*.pyd']: for file in glob.glob('./pybase64/' + ext): log.info("removing '%s'", file) if self.dry_run: continue os.remove(file)
0.00722
def register_group(self, name, policies=None, mount_point=DEFAULT_MOUNT_POINT): """Register a new group and maps a set of policies to it. Supported methods: POST: /auth/{mount_point}/groups/{name}. Produces: 204 (empty body) :param name: The name of the group. :type name: s...
0.003119
def save_dispatcher(dsp, path): """ Write Dispatcher object in Python pickle format. Pickles are a serialized byte stream of a Python object. This format will preserve Python objects used as nodes or edges. :param dsp: A dispatcher that identifies the model adopted. :type dsp: schedula...
0.001068
def get(self, key, *, encoding=_NOTSET): """Get the value of a key.""" return self.execute(b'GET', key, encoding=encoding)
0.014493
def construct_datapipeline(env='', generated=None, previous_env=None, region='us-east-1', settings=None, pipeline_data=None): """Create the Pipeline JSON from template. This ha...
0.001134
def bitsBitOp(self, other, op, getVldFn, reduceCheckFn): """ :attention: If other is Bool signal, convert this to bool (not ideal, due VHDL event operator) """ other = toHVal(other) iamVal = isinstance(self, Value) otherIsVal = isinstance(other, Value) if iamVal and otherIsVal: ...
0.000949
def store(self, transient_file, persistent_file): '''Makes PersistentFile from TransientFile''' #for i in range(5): # persistent_file = PersistentFile(self.persistent_root, # persistent_name, self) # if not os.path.exists(persistent_file....
0.006192
def get_version_naive(cls, name, ignore=''): """ Checks a string for a possible version of an object (no prefix, no suffix) without filtering date out Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(...
0.00613
def randombytes(n): """Return n random bytes.""" # Use /dev/urandom if it is available. Fall back to random module # if not. It might be worthwhile to extend this function to use # other platform-specific mechanisms for getting random bytes. if os.path.exists("/dev/urandom"): f = open("/de...
0.002058
def _database_from_key(self, key): """ gets the database name for the given key. Should ensure a uniform spread of keys over the databases in order to minimize waiting times. Since the database has to be locked for updates and multiple processes want to write, each process has to...
0.006573
def _sqlfile_to_statements(sql): """ Takes a SQL string containing 0 or more statements and returns a list of individual statements as strings. Comments and empty statements are ignored. """ statements = (sqlparse.format(stmt, strip_comments=True).strip() for stmt in sqlparse.split(sql)) re...
0.008287
def print_minized_help(self, *, no_pager=False): """Return the formatted help text. Override default ArgumentParser to just include the usage and the description. The `help` action is used for provide more detail. """ formatter = self._get_formatter() formatter.add_usage...
0.003436
def get_loc(self, key, method=None, tolerance=None): """Adapted from pandas.tseries.index.DatetimeIndex.get_loc""" if isinstance(key, str): return self._get_string_slice(key) else: return pd.Index.get_loc(self, key, method=method, toler...
0.00597
def clicks(times=None, frames=None, sr=22050, hop_length=512, click_freq=1000.0, click_duration=0.1, click=None, length=None): """Returns a signal with the signal `click` placed at each specified time Parameters ---------- times : np.ndarray or None times to place clicks, in seconds ...
0.000707
def create_key_id(vault, name, version=None): """ :param vault: The vault uri. :type vault: str :param name: The key name. :type name: str :param version: The key version. :type version: str :rtype: KeyVaultId """ return KeyId(vault=vault, ...
0.005764
def downsample(time_series: DataFrame, freq: str) -> DataFrame: """ Downsample the given route, stop, or feed time series, (outputs of :func:`.routes.compute_route_time_series`, :func:`.stops.compute_stop_time_series`, or :func:`.miscellany.compute_feed_time_series`, respectively) to the given P...
0.000944
def get_lb_pkgs(self): """Retrieves the local load balancer packages. :returns: A dictionary containing the load balancer packages """ _filter = {'items': {'description': utils.query_filter('*Load Balancer*')}} packages = self.prod_pkg.getItems(id=...
0.003922
def check_service_windows(pfeed, *, as_df=False, include_warnings=False): """ Analog of :func:`check_frequencies` for ``pfeed.service_windows`` """ table = 'service_windows' problems = [] # Preliminary checks if pfeed.service_windows is None: problems.append(['error', 'Missing table...
0.003425
def main(): """ This is the main body of the process that does the work. Summary: - load the raw data - read in rules list - create log events for AIKIF according to rules [map] - create new facts / reports based on rules [report] OUTPUT = AIKIF mapping : Date_of_...
0.010708
def _output_current_byte(self): """ Prints out the ASCII value of the current byte """ if self.tape[self.pointer] is None: print "{}".format(chr(0)), else: print "{}".format(chr(int(self.tape[self.pointer]))),
0.007326