text
stringlengths
78
104k
score
float64
0
0.18
def get_default_shell(environ=None, fallback=_UNSPECIFIED): """Get the user's default shell program.""" if environ is None: environ = os.environ # If the option is specified in the environment, respect it. if "PIAS_OPT_SHELL" in environ: return environ["PIAS_OPT_SHELL"] # Find all ca...
0.001002
def has_add_permission(self, request): """ Returns True if the given request has permission to add an object. Can be overriden by the user in subclasses. """ opts = self.opts return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission())
0.009967
def stop(self): """Stop the service. """ try: sh.systemctl.stop(self.name) except sh.ErrorReturnCode_5: self.logger.debug('Service not running.')
0.00995
def plotImagesWithNoise(suite, noise_values, plotPath): """ Plot Sample MNIST images with noise :param suite: The configured experiment suite. Must call `parse_opt` and ` parse_cfg` before calling this functions :param noise: list of noise values to plot """ datadir = suite.cfgparser.default...
0.015517
def should_filter(items): """Check if we should do damage filtering on somatic calling with low frequency events. """ return (vcfutils.get_paired(items) is not None and any("damage_filter" in dd.get_tools_on(d) for d in items))
0.007968
def calc_endpoint_from_percentile_abc(model_obj, init_vals, percentile, bias_correction, acceleration, std_error, ...
0.000218
def dp(**kwargs): """ Debugging print. Prints a list of labels and values, each on their own line. """ for label,value in kwargs.iteritems(): print "{0}\t{1}".format(label, value)
0.014218
def command(state, args): """Unregister watching regexp for an anime.""" args = parser.parse_args(args[1:]) if args.complete: query.files.delete_regexp_complete(state.db) else: if args.aid is None: parser.print_help() else: aid = state.results.parse_aid(ar...
0.002513
def process(self, senderKeyName, senderKeyDistributionMessage): """ :type senderKeyName: SenderKeyName :type senderKeyDistributionMessage: SenderKeyDistributionMessage """ senderKeyRecord = self.senderKeyStore.loadSenderKey(senderKeyName) senderKeyRecord.addSenderKeyState...
0.007184
def elasticsearch(line): ''' >>> import pprint >>> input_line = '[2017-08-30T06:27:19,158] [WARN ][o.e.m.j.JvmGcMonitorService] [Glsuj_2] [gc][296816] overhead, spent [1.2s] collecting in the last [1.3s]' >>> output_line = elasticsearch(input_line) >>> pprint.pprint(output_line) {'data': {'garba...
0.007087
def _hashkey(self, method, url, **kwa): '''Find a hash value for the linear combination of invocation methods. ''' to_hash = ''.join([str(method), str(url), str(kwa.get('data', '')), str(kwa.get('params', '')) ]) return hashlib.md5(to_hash.encode()).hexdigest()
0.006734
def distutils_servers(self): """Return a list of known distutils servers for collective.dist. If the config has an old pypi config, remove the default pypi server from the list. """ if not multiple_pypi_support(): return [] try: raw_index_servers ...
0.002157
def save_lost(self, service_name): """ Save an indicator that the given service is no longer data_ready. """ self._load_ready_file() self._ready.discard(service_name) self._save_ready_file()
0.008403
def map_midc_to_pvlib(variable_map, field_name): """A mapper function to rename Dataframe columns to their pvlib counterparts. Parameters ---------- variable_map: Dictionary A dictionary for mapping MIDC field name to pvlib name. See VARIABLE_MAP for default value and description of how...
0.001581
def download_encrypted_file(work_dir, url, key_path, name): """ Downloads encrypted file from S3 Input1: Working directory Input2: S3 URL to be downloaded Input3: Path to key necessary for decryption Input4: name of file to be downloaded """ file_path = os.path.join(work_dir, name) ...
0.004162
def update(self, dependency, svc, svc_ref, old_properties, new_value=False): # type: (Any, Any, ServiceReference, dict, bool) -> None """ Called by a dependency manager when the properties of an injected dependency have been updated. :param dependency: The dependency handler ...
0.004011
def get_user_balance(self, username): """ Get the user balance details from MAM. """ cmd = ["gbalance", "-u", username, "--raw"] results = self._read_output(cmd) if len(results) == 0: return None return results
0.007576
def setup_event_loop(self, actor): '''Set up the event loop for ``actor``. ''' actor.logger = self.cfg.configured_logger('pulsar.%s' % actor.name) try: loop = asyncio.get_event_loop() except RuntimeError: if self.cfg and self.cfg.concurrency == 'thread': ...
0.003295
def transition_to_execute_complete(self): """Transition to execute complate""" assert self.state in [AQStateMachineStates.execute] self.state = AQStateMachineStates.execute_complete
0.009756
def modify_order(self, modify_order_op, order_id, qty, price, adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0): """ 详细说明见基类接口说明,但有以下不同:不支持改单。 可撤单。删除订单是本地操作。 :param modify_order_op: :param order_id: :param qty: :param price: :param adjust_limit: ...
0.012865
def ordered_union(l1, l2): """ Return the union of l1 and l2, with a deterministic ordering. (Union of python sets does not necessarily have a consisten iteration order) :param l1: list of items :param l2: list of items :returns: list containing one copy of each item that is in l1 or in l2 """ out = [...
0.01519
def _split_path(self, path): """ Splits a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. The hive handle is always one of the ...
0.004598
def get_meta_data_editor(self, for_gaphas=True): """Returns the editor for the specified editor This method should be used instead of accessing the meta data of an editor directly. It return the meta data of the editor available (with priority to the one specified by `for_gaphas`) and converts ...
0.008165
def pelican_init(pelicanobj): global global_siteurl global_siteurl = pelicanobj.settings['SITEURL'] """ Prepare configurations for the MD plugin """ try: import markdown from .plantuml_md import PlantUMLMarkdownExtension except: # Markdown not available logger.debug...
0.009794
def mark_flag_as_required(flag_name, flag_values=FLAGS): """Ensures that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Important note: validator will pass for any non-None value, such as False, 0 (zero), '' (empty string) and so on. It is rec...
0.002896
def _stringify_value(self, value): """ This method stringifies values of environment variables. If the value of the method is a list or dictionary, then this method will replace it with empty string. Values of environment variables in Lambda must be a string. List or dictionary usually m...
0.004702
def _edits2(word: str) -> Set[str]: """ Return a set of words with edit distance of 2 from the input word """ return set(e2 for e1 in _edits1(word) for e2 in _edits1(e1))
0.005376
def AddWarning(self, warning): """Adds an warning. Args: warning (ExtractionWarning): an extraction warning. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed. """ self._RaiseIfNotWritable() self._storage_file.AddWarning(warning) ...
0.002841
def get(self, patch, default=None): """ Returns given patch value. :param patch: Patch name. :type patch: unicode :param default: Default value if patch is not found. :type default: object :return: Action. :rtype: QAction """ try: ...
0.004808
def add_actor(self, uinput, reset_camera=False, name=None, loc=None, culling=False): """ Adds an actor to render window. Creates an actor if input is a mapper. Parameters ---------- uinput : vtk.vtkMapper or vtk.vtkActor vtk mapper or vtk a...
0.002256
def upload_link(self, folder_id=None, sha1=None, httponly=False): """Makes a request to prepare for file upload. Note: If folder_id is not provided, it will make and upload link to the ``Home`` folder. Args: folder_id (:obj:`str`, optional): folder-ID to upload to. ...
0.00582
def finished(finished_status, update_interval, status_key, edit_at_key): """ Create dict query for pymongo that getting all finished task. :param finished_status: int, status code that greater or equal than this will be considered as finished. :param updat...
0.001297
def get_schema(self, table_name, database=None): """ Return a Schema object for the indicated table and database Parameters ---------- table_name : string May be fully qualified database : string, default None Returns ------- schema : i...
0.002976
def parse_zip(fp): """ Parse the zip file headers at fp :param fp: the file pointer from which to parse the zip file :return: A tuple of local files, directory headers, and end of central directory The local files are dictionary where the keys are the local file offset and the ...
0.00337
def init_app(self, app): """Register the extension with the application. Args: app (flask.Flask): The application to register with. """ app.url_rule_class = partial(NavigationRule, copilot=self) app.context_processor(self.inject_context)
0.006897
def api_request(self, url, **params): """ Make a trello API request. This takes an absolute url (without protocol and host) and a list of argumnets and return a GET request with the key and token from the configuration """ params['key'] = self.config.get('api_key'), ...
0.004175
def partition(self): """Convenience function for accessing the first partition in the partitions list, when there is only one.""" if not self.partitions: return None if len(self.partitions) > 1: raise ValueError( "Can't use this method when there...
0.005013
def ParseOptions(cls, options, configuration_object): """Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is o...
0.004367
def _parse_tuple_string(argument): """ Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) """ if isinstance(argument, str): return tuple(int(p.strip()) for p in argument.split(',')) return argument
0.008584
def remove_sandbox(parent_dir, dir_name): """ This function is written to remove sandbox directories if they exist under the parent_dir. :param parent_dir: string denoting full parent directory path :param dir_name: string denoting directory path which could be a sandbox :return: None """ ...
0.003497
def _nanpercentile_1d(values, mask, q, na_value, interpolation): """ Wraper for np.percentile that skips missing values, specialized to 1-dimensional case. Parameters ---------- values : array over which to find quantiles mask : ndarray[bool] locations in values that should be consi...
0.001135
def _compute_top_of_rupture_depth_term(self, C, rup): """ Compute and return top of rupture depth term, that is the seventh term in equation 1, page 74. The calculation of this term is explained in paragraph 'Depth-to-Top of Rupture Model', page 78. """ if rup.ztor >= 10....
0.004878
def next_sibling(self, name=None): """Get the next sibling in the children list of the parent node. If a name is provided, the next sibling with the given name is returned. """ if name is None: return XMLElement(lib.lsl_next_sibling(self.e)) else: return...
0.007874
def _generate_full_recipe_message(self, destination, message, add_path_step): """Factory function to generate independent message objects for downstream recipients with different destinations.""" if add_path_step and self.recipe_pointer: recipe_path = self.recipe_path + [self.recipe_...
0.003252
def get_cpu_percent(self, interval=0.1): """Return a float representing the current process CPU utilization as a percentage. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares...
0.000935
def on_any_event(self, event): """File created or modified""" if os.path.isfile(event.src_path): self.callback(event.src_path, **self.kwargs)
0.011834
def _convert(self, args): '''convert '(1,1)' to 'B2' and 'B2' to '(1,1)' auto-recongnize''' if args.find(",") > -1: b, a = args.replace("(", "").replace(")", "").split(",") a = chr(int(a)+65)#chr(65) is "A" and ord("A") is 65 b = str(int(b)+1) return a+b ...
0.009363
def omerc2cf(area): """Return the cf grid mapping for the omerc projection.""" proj_dict = area.proj_dict args = dict(azimuth_of_central_line=proj_dict.get('alpha'), latitude_of_projection_origin=proj_dict.get('lat_0'), longitude_of_projection_origin=proj_dict.get('lonc'), ...
0.001466
def binary(self): """Returns the binary this target references.""" dependencies = self.dependencies if len(dependencies) != 1: raise TargetDefinitionException(self, 'An app must define exactly one binary ' 'dependency, have: {}'.format(dependencies)) bin...
0.010324
def update_entity(self, table_name, entity, if_match='*', timeout=None): ''' Updates an existing entity in a table. Throws if the entity does not exist. The update_entity operation replaces the entire entity and can be used to remove properties. :param str table_name: ...
0.008811
def _address_from_row(self, row): """ Parse the broadcast rpc address from a row and return it untranslated. """ addr = None if "rpc_address" in row: addr = row.get("rpc_address") # peers and local if "native_transport_address" in row: addr = row....
0.004376
def in_single_path_and_inner(self): """ Test if a node is not linking to any fan in or out node. """ return len(self.successor) == 1 and self.successor[0] is not None and not self.successor[0].in_or_out and \ len(self.precedence) == 1 and self.precedence[0] is not None and...
0.014205
def _nac(self, q_direction): """nac_term = (A1 (x) A2) / B * coef. """ num_atom = self._pcell.get_number_of_atoms() nac_q = np.zeros((num_atom, num_atom, 3, 3), dtype='double') if (np.abs(q_direction) < 1e-5).all(): return nac_q rec_lat = np.linalg.inv(self._...
0.002252
def sequence(self): """ Returns the volume group sequence number. This number increases everytime the volume group is modified. """ self.open() seq = lvm_vg_get_seqno(self.handle) self.close() return seq
0.007491
def make_root_tuple_info(stream_id, tuple_id): """Creates a RootTupleInfo""" key = random.getrandbits(TupleHelper.MAX_SFIXED64_RAND_BITS) return RootTupleInfo(stream_id=stream_id, tuple_id=tuple_id, insertion_time=time.time(), key=key)
0.003676
def onset_backtrack(events, energy): '''Backtrack detected onset events to the nearest preceding local minimum of an energy function. This function can be used to roll back the timing of detected onsets from a detected peak amplitude to the preceding minimum. This is most useful when using onsets ...
0.000737
def _set_key_table(self, v, load=False): """ Setter method for key_table, mapped from YANG variable /interface/fortygigabitethernet/ip/interface_fo_ospf_conf/ospf_interface_config/md5_authentication/key_table (container) If this variable is read-only (config: false) in the source YANG file, then _set_ke...
0.005076
def do_condition(self, arg): """condition bpnumber [condition] Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditiona...
0.003289
def qos_queue_multicast_scheduler_dwrr_dwrr_traffic_class0(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") queue = ET.SubElement(qos, "queue") multicast = ET.SubElement(...
0.004425
def map_values( cr, source_column, target_column, mapping, model=None, table=None, write='sql'): """ Map old values to new values within the same model or table. Old values presumably come from a legacy column. You will typically want to use it in post-migration scripts. :param cr: ...
0.000372
def set_title(self, s, delay_draw=False): "set plot title" self.conf.relabel(title=s, delay_draw=delay_draw)
0.016129
def unregister_provider(self, provider): """ Unregister a provider. Blocks until this RpcConsumer is unregistered from its QueueConsumer, which only happens when all providers have asked to unregister. """ self._unregistering_providers.add(provider) remaining_providers =...
0.00235
def _sort_handlers(cls, signals, handlers, configs): """Sort class defined handlers to give precedence to those declared at lower level. ``config`` can contain two keys ``begin`` or ``end`` that will further reposition the handler at the two extremes. """ def macro_precedence_sor...
0.001227
def _get_vispy_caller(): """Helper to get vispy calling function from the stack""" records = inspect.stack() # first few records are vispy-based logging calls for record in records[5:]: module = record[0].f_globals['__name__'] if module.startswith('vispy'): line = str(record[...
0.001629
def _get_movielens_path(): """ Get path to the movielens dataset file. """ return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'movielens.zip')
0.005102
def loop_iteration(self, timeout = 60): """A loop iteration - check any scheduled events and I/O available and run the handlers. """ next_timeout, sources_handled = self._call_timeout_handlers() if self._quit: return sources_handled if self._timeout is not Non...
0.002978
def setup_exchanges(app): """ Setup result exchange to route all tasks to platform queue. """ with app.producer_or_acquire() as P: # Ensure all queues are noticed and configured with their # appropriate exchange. for q in app.amqp.queues.values(): P.maybe_declare(q)
0.003145
def login(self, login, password): """Login to the corresponding (self.url) mattermost instance.""" props = {'login_id': login, 'password': password} p = requests.post(self.url + '/users/login', data=json.dumps(props)) self.token = p.headers["Token"] # Store the token for further requests...
0.007874
def upgrade_available(name, **kwargs): ''' Check if there is an upgrade available for a certain package Accepts full or partial FMRI. Returns all matches found. CLI Example: .. code-block:: bash salt '*' pkg.upgrade_available apache-22 ''' version = None cmd = ['pkg', 'list', ...
0.001848
def linkcode_resolve(domain, info): # NOQA: C901 """ Determine the URL corresponding to Python object Notes ----- From https://github.com/numpy/numpy/blob/v1.15.1/doc/source/conf.py, 7c49cfa on Jul 31. License BSD-3. https://github.com/numpy/numpy/blob/v1.15.1/LICENSE.txt """ if domain...
0.001754
def last_updated(self, since, queue=None): """ Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :keyword queue: Queue where to search :returns: List of tickets with LastUpdated parameter later than *since* ordered in decreasi...
0.005076
def configure_new(self, config): """Configure a new genome based on the given configuration.""" # Create node genes for the output pins. for node_key in config.output_keys: self.nodes[node_key] = self.create_node(config, node_key) # Add hidden nodes if requested. if...
0.003899
def get_endpoints(self, query=None): '''use a transfer client to get endpoints. If a search term is included, we use it to search a scope of "all" in addition to personal and shared endpoints. Endpoints are organized by type (my-endpoints, shared-with-me, optionally all) and then id. Pa...
0.005098
def finalize(self): """finalize for PathConsumer""" super(TransposedConsumer, self).finalize() self.result = map(list, zip(*self.result))
0.012422
async def on_raw_671(self, message): """ WHOIS: user is connected securely. """ target, nickname = message.params[:2] info = { 'secure': True } if nickname in self._whois_info: self._whois_info[nickname].update(info)
0.007117
def all_thumbnails(path, recursive=True, prefix=None, subdir=None): """ Return a dictionary referencing all files which match the thumbnail format. Each key is a source image filename, relative to path. Each value is a list of dictionaries as explained in `thumbnails_for_file`. """ if prefix is...
0.000476
def local_session(factory): """Cache a session thread local for up to 45m""" factory_region = getattr(factory, 'region', 'global') s = getattr(CONN_CACHE, factory_region, {}).get('session') t = getattr(CONN_CACHE, factory_region, {}).get('time') n = time.time() if s is not None and t + (60 * 45...
0.002262
def transitions(self): """Transition matrix (sparse matrix). Is conjugate to the symmetrized transition matrix via:: self.transitions = self.Z * self.transitions_sym / self.Z where ``self.Z`` is the diagonal matrix storing the normalization of the underlying kernel matrix...
0.004886
def _register_resources(self, api_dirs, do_checks): '''Register all Apis, Resources and Models with the application.''' msg = 'Looking-up for APIs in the following directories: {}' log.debug(msg.format(api_dirs)) if do_checks: check_and_load(api_dirs) else: ...
0.003361
def fbcorr(imgs, filters): n_imgs, n_rows, n_cols, n_channels = imgs.shape n_filters, height, width, n_ch2 = filters.shape output = numpy.zeros((n_imgs, n_filters, (n_rows - height + 1),(n_cols - width + 1))) "omp parallel for private(rr,cc,hh,ww,jj,ff,imgval, filterval)" for ii in xrange(n_imgs): ...
0.014303
def argspec_report(functions, module=''): ''' Pass in a functions dict as it is returned from the loader and return the argspec function signatures ''' ret = {} if '*' in module or '.' in module: for fun in fnmatch.filter(functions, module): try: aspec = get_f...
0.00066
def members(self): """ Return a list of all users in this organization. Users are identified by their login name. Note that this is computed from the teams in the organization, because GitHub does not currently offer a WebHook for organization membership, so converting org member...
0.003914
def get_absolute_time(self, key): """Returns the absolute time position of the key. If absolute time positions are not calculated, then this function calculates it. """ keyframe = self.dct[key] try: # if absolute time is already calculated, return that ...
0.002491
def start_semester_view(request): """ Initiates a semester"s worth of workshift, with the option to copy workshift types from the previous semester. """ page_name = "Start Semester" year, season = utils.get_year_season() start_date, end_date = utils.get_semester_start_end(year, season) ...
0.000556
def update(self, infos): """Process received infos.""" genes = [i for i in infos if isinstance(i, LearningGene)] for gene in genes: if ( self.network.role == "experiment" and self.generation > 0 and random.random() < 0.10 ):...
0.00489
def _rewrite_tag_attrs(self, tag, tag_attrs, set_parsing_context=True): """Rewrite a tags attributes. If set_parsing_context is false then the parsing context will not set. If the head insert has not been added to the HTML being rewritten, there is no parsing context and the tag is not ...
0.00187
def merge(self, base, head, message=''): """Perform a merge from ``head`` into ``base``. :param str base: (required), where you're merging into :param str head: (required), where you're merging from :param str message: (optional), message to be used for the commit :returns: :cla...
0.003008
def store_script(self, script): """ Store a script for later execution. script:= the script text as a series of bytes. Returns a >=0 script id if OK. ... sid = pi.store_script( b'tag 0 w 22 1 mils 100 w 22 0 mils 100 dcr p0 jp 0') ... """ ...
0.003231
def show_fields(self, block=None): """Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the ...
0.004655
def docs(root_url, path): """Generate URL for path in the Taskcluster docs.""" root_url = root_url.rstrip('/') path = path.lstrip('/') if root_url == OLD_ROOT_URL: return 'https://docs.taskcluster.net/{}'.format(path) else: return '{}/docs/{}'.format(root_url, path)
0.003311
def AddScanNode(self, path_spec, parent_scan_node): """Adds a scan node for a certain path specification. Args: path_spec (PathSpec): path specification. parent_scan_node (SourceScanNode): parent scan node or None. Returns: SourceScanNode: scan node. Raises: KeyError: if the s...
0.0065
def get_ftype_counts(self): """Get the counts of ftypes in this object. Returns: The counts of ftypes in this object. """ if hasattr(self, "ftype"): return pandas.Series({self.ftype: 1}) return self.ftypes.value_counts().sort_index()
0.006536
def dispense(self, volume=None, location=None, rate=1.0): """ Dispense a volume of liquid (in microliters/uL) using this pipette Notes ----- If only a volume is passed, the pipette will dispense from it's current positio...
0.001285
def load_ipython_extension(ip): """Load the extension in IPython.""" global _loaded if not _loaded: plugin = StoreMagic(shell=ip, config=ip.config) ip.plugin_manager.register_plugin('storemagic', plugin) _loaded = True
0.003937
def run(self): """ The main entry point, performs the appropriate action for the given arguments. """ self._unlock_keychain() item = self.keychain.item( self.arguments.item, fuzzy_threshold=self._fuzzy_threshold(), ) if item is no...
0.003559
def to_chunks(self, df, **kwargs): """ pass thru chunker of the dataframe/series returns ------- ('NA', 'NA', 'NA', dataframe/series) """ if len(df) > 0: yield b'NA', b'NA', b'NA', df
0.007937
def do_postfix(self, arg): """Sets the function to apply to the values of a specific variable before plotting or tabulating values. """ usable, filename, append = self._redirect_split(arg) sargs = usable.split() if len(sargs) == 1 and sargs[0] == "list": self....
0.005435
def _generate_base_namespace_module(self, namespace): # type: (ApiNamespace) -> None """Creates a module for the namespace. All data types and routes are represented as Python classes.""" self.cur_namespace = namespace self.import_tracker.clear() generate_module_header(s...
0.002246
def get_unspents(address, blockchain_client=ChainComClient()): """ Get the spendable transaction outputs, also known as UTXOs or unspent transaction outputs. """ if not isinstance(blockchain_client, ChainComClient): raise Exception('A ChainComClient object is required') url = CHAIN_API_...
0.002817
def _index_into(self, idx, data): """ Attempts to get the column from the data using the specified index, raises an exception if this is not possible from this point in the stack. """ try: if is_dataframe(data): # Assume column indexing ...
0.007899