text
stringlengths
78
104k
score
float64
0
0.18
def extract_forward_and_reverse_complement( self, forward_reads_to_extract, reverse_reads_to_extract, database_fasta_file, output_file): '''As per extract except also reverse complement the sequences.''' self.extract(forward_reads_to_extract, database_fasta_file, output_file) ...
0.005814
def insert(self, index, child, by_name_index=-1): """ Add the child at the given index :type index: ``int`` :param index: child position :type child: :class:`Element <hl7apy.core.Element>` :param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass ...
0.004261
def on_finish(func, handler, args, kwargs): """ Wrap the handler ``on_finish`` method to finish the Span for the given request, if available. """ tracing = handler.settings.get('opentracing_tracing') tracing._finish_tracing(handler) return func(*args, **kwargs)
0.003448
def display_callback(self, component, **kwargs): """ Display given component in this environment. .. note:: To be overridden by inheriting classes An example of a introducing a custom display environment. .. doctest:: import cqparts from c...
0.001421
def fetch_organization_courses(organization): """ Retrieves the set of courses currently linked to the specified organization """ organization_obj = serializers.deserialize_organization(organization) queryset = internal.OrganizationCourse.objects.filter( organization=organization_obj, ...
0.004228
def cached_unless_authenticated(timeout=50, key_prefix='default'): """Cache anonymous traffic.""" def caching(f): @wraps(f) def wrapper(*args, **kwargs): cache_fun = current_cache.cached( timeout=timeout, key_prefix=key_prefix, unless=lambda: current_c...
0.002232
def GetClientConfig(filename): """Write client config to filename.""" config_lib.SetPlatformArchContext() config_lib.ParseConfigCommandLine() context = list(grr_config.CONFIG.context) context.append("Client Context") deployer = build.ClientRepacker() # Disable timestamping so we can get a reproducible and...
0.018771
def create_plot_option_dicts(info, marker_types=None, colors=None, line_dash=None, size=None): """Create two dictionaries with plot-options. The first iterates colors (based on group-number), the second iterates through marker types. Returns: group_styles (dict), sub_group...
0.000506
def lookup(domain): """Find the virNetwork object associated to the domain. If the domain has more than one network interface, the first one is returned. None is returned if the domain is not attached to any network. """ xml = domain.XMLDesc(0) element = etree.fromstring(xml) subelm = ...
0.001779
def _set_policy_map(self, v, load=False): """ Setter method for policy_map, mapped from YANG variable /policy_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_policy_map is considered as a private method. Backends looking to populate this variable should ...
0.003623
def anneal(self, mode, matches, orig_matches): """ Perform post-processing. Return True when any changes were applied. """ changed = False def dupes_in_matches(): """Generator for index of matches that are dupes.""" items_by_path = config.engine.grou...
0.001245
def get_head_revision_from_alembic( alembic_config_filename: str, alembic_base_dir: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str: """ Ask Alembic what its head revision is (i.e. where the Python code would like the database to be at). Arguments: ...
0.001031
def uni_to_beta(text): """ Convert unicode text to a betacode equivalent. This method can handle tónos or oxeîa characters in the input. Args: text: The text to convert to betacode. This text does not have to all be Greek polytonic text, and only Greek characters will be converted. Note ...
0.001385
def save_binary(self, fname, silent=True): """Save DMatrix to an XGBoost buffer. Parameters ---------- fname : string Name of the output buffer file. silent : bool (optional; default: True) If set, the output is suppressed. """ _check_call...
0.004202
def to_ufo_guidelines(self, ufo_obj, glyphs_obj): """Set guidelines.""" guidelines = glyphs_obj.guides if not guidelines: return new_guidelines = [] for guideline in guidelines: new_guideline = {} x, y = guideline.position angle = guideline.angle % 360 if _is_...
0.000806
def add_node(self, node): """Add a new node to the scheduler. From now on the node will be assigned work units to be executed. Called by the ``DSession.worker_workerready`` hook when it successfully bootstraps a new node. """ assert node not in self.assigned_work ...
0.005525
def _element_to_node(self, node, name, value): """ Insert the parsed element (``name``, ``value`` pair) into the node. You should always use the returned node and forget the one that was given in parameter. :param node: the node where the is added to :returns: the node. Note th...
0.003597
def get_all_zk_state_managers(conf): """ Creates all the zookeeper state_managers and returns them in a list """ state_managers = [] state_locations = conf.get_state_locations_of_type("zookeeper") for location in state_locations: name = location['name'] hostport = location['hostport'] hostport...
0.014231
def close(self): """ Close service client and its plugins. """ self._execute_plugin_hooks_sync(hook='close') if not self.session.closed: ensure_future(self.session.close(), loop=self.loop)
0.008299
def get_port_stats(port): """ Iterate over connections and count states for specified port :param port: port for which stats are collected :return: Counter with port states """ cnts = defaultdict(int) for c in psutil.net_connections(): c_port = c.laddr[1] if c_port != port: ...
0.00241
def _generate_struct_cstor_default(self, struct): """Emits struct convenience constructor. Default arguments are omitted.""" if not self._struct_has_defaults(struct): return fields_no_default = [ f for f in struct.all_fields if not f.has_default and not is_nu...
0.003122
def extract(self, path, outdir, concurrency_safe=False, **kwargs): """Extracts an archive's contents to the specified outdir with an optional filter. Keyword arguments are forwarded to the instance's self._extract() method. :API: public :param string path: path to the zipfile to extract from :par...
0.008729
def index(): """ Base testsuite view. """ # setup_env() logs = Table('log', metadata, autoload=True) criticals = logs.select().where(logs.c.log_level == 50).order_by( 'siteconfig', 'date_created') criticals_count = logs.count(logs.c.log_level == 50) errors = logs.select().where(logs....
0.000818
def posthoc_wilcoxon(a, val_col=None, group_col=None, zero_method='wilcox', correction=False, p_adjust=None, sort=False): '''Pairwise comparisons with Wilcoxon signed-rank test. It is a non-parametric version of the paired T-test for use with non-parametric ANOVA. Parameters ---------- a : array_l...
0.00244
def types(cls, **kwargs): """Create an Arguments of the possible Types.""" named = {name: factory(Arguments._fields.index(name), name) for name, factory in six.iteritems(kwargs)} return cls(**named)
0.004484
def result(self): """ Return result axes """ if self.subplots: if self.layout is not None and not is_list_like(self.ax): return self.axes.reshape(*self.layout) else: return self.axes else: sec_true = isinstance(s...
0.002782
def sorted_enums(self) -> List[Tuple[str, int]]: """Return list of enum items sorted by value.""" return sorted(self.enum.items(), key=lambda x: x[1])
0.012048
def transmit(self, channel, message): """ Send the message to Slack. :param channel: channel or user to whom the message should be sent. If a ``thread`` attribute is present, that thread ID is used. :param str message: message to send. """ target = ( self.slack.server.channels.find(channel) or sel...
0.029167
def _get_type(self, policy): """ Returns the type of the given policy :param string or dict policy: Policy data :return PolicyTypes: Type of the given policy. None, if type could not be inferred """ # Must handle intrinsic functions. Policy could be a primitive type or ...
0.005859
def _add_list_getter(self): """ Add a read-only ``{prop_name}_lst`` property to the element class to retrieve a list of child elements matching this type. """ prop_name = '%s_lst' % self._prop_name property_ = property(self._list_getter, None, None) setattr(self._...
0.00565
def merge_stats(self, other_col_counters): """ Merge statistics from a different column stats counter in to this one. Parameters ---------- other_column_counters: Other col_stat_counter to marge in to this one. """ for column_name, _ in self._column_stats.items():...
0.00404
def is_dictlist(data): ''' Returns True if data is a list of one-element dicts (as found in many SLS schemas), otherwise returns False ''' if isinstance(data, list): for element in data: if isinstance(element, dict): if len(element) != 1: retur...
0.002433
def pickle(self, path): """Write objects to python pickle. Pickling is Python's method for serializing/deserializing Python objects. This allows you to save a fully functional JSSObject to disk, and then load it later, without having to retrieve it from the JSS. This me...
0.002364
def collect_dependency_paths(package_name): """ TODO docstrings """ deps = [] try: dist = pkg_resources.get_distribution(package_name) except (pkg_resources.DistributionNotFound, ValueError): message = "Distribution '{}' not found.".format(package_name) raise RequirementN...
0.001078
def value(self): """convenience method to just get one value or tuple of values for the query""" field_vals = None field_names = self.fields_select.names() fcount = len(field_names) if fcount: d = self._query('get_one') if d: field_vals = [...
0.00713
def get_lldp_neighbors(self): """Return LLDP neighbors details.""" lldp = junos_views.junos_lldp_table(self.device) try: lldp.get() except RpcError as rpcerr: # this assumes the library runs in an environment # able to handle logs # otherwi...
0.003793
def activateAaPdpContextRequest(AccessPointName_presence=0, ProtocolConfigurationOptions_presence=0, GprsTimer_presence=0): """ACTIVATE AA PDP CONTEXT REQUEST Section 9.5.10""" a = TpPd(pd=0x8) b = MessageType(mesType=0x50) # 01010000 c = ...
0.001178
def b58decode(v): '''Decode a Base58 encoded string''' v = v.rstrip() v = scrub_input(v) origlen = len(v) v = v.lstrip(alphabet[0:1]) newlen = len(v) acc = b58decode_int(v) result = [] while acc > 0: acc, mod = divmod(acc, 256) result.append(mod) return (b'\0'...
0.002725
def do_erase(self): """! @brief Handle 'erase' subcommand.""" self._increase_logging(["pyocd.tools.loader", "pyocd"]) session = ConnectHelper.session_with_chosen_probe( project_dir=self._args.project_dir, config_file=self._args.con...
0.003584
def switch_org(orgname, profile='grafana'): ''' Switch the current organization. name Name of the organization to switch to. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. CLI Example: .. code-block:: bash salt '*...
0.001236
def add_genesis_parser(subparsers, parent_parser): """Creates the arg parsers needed for the genesis command. """ parser = subparsers.add_parser( 'genesis', help='Creates the genesis.batch file for initializing the validator', description='Generates the genesis.batch file for ' ...
0.0008
def message( *tokens: Token, end: str = "\n", sep: str = " ", fileobj: FileObj = sys.stdout, update_title: bool = False ) -> None: """ Helper method for error, warning, info, debug """ if using_colorama(): global _INITIALIZED if not _INITIALIZED: colorama.ini...
0.001451
def create_data(datatype='ChanTime', n_trial=1, s_freq=256, chan_name=None, n_chan=8, time=None, freq=None, start_time=None, signal='random', amplitude=1, color=0, sine_freq=10, attr=None): """Create data of different datatype from scratch. Parame...
0.000455
def play_tone(self, pin, tone_command, frequency, duration=None): """ This method will call the Tone library for the selected pin. It requires FirmataPlus to be loaded onto the arduino If the tone command is set to TONE_TONE, then the specified tone will be played. Else...
0.00232
def upper(self): '''Upper bound''' try: return self._model._limits_upper[self._reaction] except KeyError: return self._model._v_max
0.011173
def check_dispatch(self): # pylint: disable=too-many-branches """Check that all active satellites have a configuration dispatched A DispatcherError exception is raised if no configuration is dispatched! :return: None """ if not self.arbiter_link: raise DispatcherEr...
0.004811
def QAM_bb(N_symb,Ns,mod_type='16qam',pulse='rect',alpha=0.35): """ QAM_BB_TX: A complex baseband transmitter x,b,tx_data = QAM_bb(K,Ns,M) //////////// Inputs ////////////////////////////////////////////////// N_symb = the number of symbols to process Ns = number of samples per symbol ...
0.011028
def _validate_config(): ''' Validate azurefs config, return False if it doesn't validate ''' if not isinstance(__opts__['azurefs'], list): log.error('azurefs configuration is not formed as a list, skipping azurefs') return False for container in __opts__['azurefs']: if not is...
0.003501
def register_warning_code(code, exception_type, domain='core'): """Register a new warning code""" Logger._warning_code_to_exception[code] = (exception_type, domain) Logger._domain_codes[domain].add(code)
0.008811
def lookup_stdout(self, pk=None, start_line=None, end_line=None, full=True): """ Internal method that lies to our `monitor` method by returning a scorecard for the workflow job where the standard out would have been expected. """ uj_res = get_resourc...
0.002045
def by_id(self, region, league_id): """ Get league with given ID, including inactive entries :param string region: the region to execute this request on :param string league_id: the league ID to query :returns: LeagueListDTO """ url, query = LeagueApiV4...
0.004545
def get_paths(self, user_ids=None, startup_ids=None, direction=None): """ user_ids: paths between you and these users startup_ids: paths between you and these startups direction: 'following' or 'followed' """ if user_ids is None and startup_ids is None and direction is None: raise Exceptio...
0.011236
def removeNestedGroups(node): """ This walks further and further down the tree, removing groups which do not have any attributes or a title/desc child and promoting their children up one level """ global _num_elements_removed num = 0 groupsToRemove = [] # Only consider <g> elements ...
0.003388
def build_constraints(self, coefs, constraint_lam, constraint_l2): """ builds the GAM block-diagonal constraint matrix in quadratic form out of constraint matrices specified for each feature. behaves like a penalty, but with a very large lambda value, ie 1e6. Parameters ...
0.003735
def bytscl(array, maximum=None , minimum=None , nan=0, top=255 ): """ see http://star.pst.qub.ac.uk/idl/BYTSCL.html note that IDL uses slightly different formulae for bytscaling floats and ints. here we apply only the FLOAT formula... """ if maximum is None: maximum = np.nanmax(array) ...
0.021097
def _configure_manager(self): """ Creates the Manager instances to handle monitoring. """ self._flavor_manager = CloudCDNFlavorManager(self, uri_base="flavors", resource_class=CloudCDNFlavor, response_key=None, plural_response_key="flavors") self._...
0.011928
def eventFilter(self, widget, event): """ A filter that is used to send a signal when the figure canvas is clicked. """ if event.type() == QEvent.MouseButtonPress: if event.button() == Qt.LeftButton: self.sig_canvas_clicked.emit(self) return su...
0.005362
def pull(self, project, run=None, entity=None): """Download files from W&B Args: project (str): The project to download run (str, optional): The run to upload to entity (str, optional): The entity to scope this project to. Defaults to wandb models Returns: ...
0.004243
def append(self, name, *args, **kwargs) -> 'Pipeline': """Add a function (either as a reference, or by name) and arguments to the pipeline. :param name: The name of the function :type name: str or (pybel.BELGraph -> pybel.BELGraph) :param args: The positional arguments to call in the fu...
0.002918
def add_message(self, path, tags=None, afterwards=None): """ Adds a file to the notmuch index. :param path: path to the file :type path: str :param tags: tagstrings to add :type tags: list of str :param afterwards: callback to trigger after adding :type a...
0.002688
def clear_secure_boot_keys(self): """Reset all keys. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server. """ if self._is_boot_mode_uefi(): self._change_secure_boot_settings('Re...
0.003663
def add_dummy_scores(iteratable, score=0): """Add zero scores to all sequences""" for seq in iteratable: seq.letter_annotations["phred_quality"] = (score,)*len(seq) yield seq
0.005051
def func(self, values): """ The actual ensembling logic that combines multiple *values*. The method call is forwareded tothe ensemble method-specific variant which is determined using *method*. """ if self.method == METHOD_MEAN: return self.func_mean(values) e...
0.006299
def recarrayuniqify(X, retainorder=False): """ Very fast uniqify routine for numpy record arrays (or ndarrays with structured dtype). Record array version of func:`tabular.fast.arrayuniqify`. **Parameters** **X** : numpy recarray Determine the unique elements of...
0.0076
def addvPPfunc(self,solution): ''' Adds the marginal marginal value function to an existing solution, so that the next solver can evaluate vPP and thus use cubic interpolation. Parameters ---------- solution : ConsumerSolution The solution to this single peri...
0.007926
def _prt_results(self, goea_results): """Print GOEA results to the screen.""" min_ratio = self.args.ratio if min_ratio is not None: assert 1 <= min_ratio <= 2 self.objgoea.print_date(min_ratio=min_ratio, pval=self.args.pval) results_adj = self.objgoea.get_adj_records(...
0.0064
def build(self, shutit): """Sets up the target ready for building. """ target_child = self.start_container(shutit, 'target_child') self.setup_host_child(shutit) # TODO: on the host child, check that the image running has bash as its cmd/entrypoint. self.setup_target_child(shutit, target_child) shutit.send...
0.020374
def require_group(self, name, overwrite=False): """Obtain a sub-group, creating one if it doesn't exist. Parameters ---------- name : string Group name. overwrite : bool, optional Overwrite any existing array with given `name` if present. Returns...
0.002845
def make_unistream(stream): '''Make a stream which unescapes string literals before writes out.''' unistream = lambda: 'I am an unistream!' # make unistream look like the stream for attr_name in dir(stream): if not attr_name.startswith('_'): setattr(unistream, attr_name, getattr(st...
0.003279
def _get_file_event_handler(self, file_path, save_name): """Get or create an event handler for a particular file. file_path: the file's actual path save_name: its path relative to the run directory (aka the watch directory) """ self._file_pusher.update_file(save_name, file_path)...
0.00487
def get_item(self, item_cls, item_type, key): """ Get a piece of information (a request or a response) from the state database. :param item_cls: The :py:class:`oidcmsg.message.Message` subclass that described the item. :param item_type: Which request/response that is...
0.003049
def parse_assembly(llvmir, context=None): """ Create Module from a LLVM IR string """ if context is None: context = get_global_context() llvmir = _encode_string(llvmir) strbuf = c_char_p(llvmir) with ffi.OutputString() as errmsg: mod = ModuleRef( ffi.lib.LLVMPY_Pa...
0.001953
def connection_with_anon(credentials, anon=True): """ Connect to S3 with automatic handling for anonymous access. Parameters ---------- credentials : dict AWS access key ('access') and secret access key ('secret') anon : boolean, optional, default = True Whether to make an anon...
0.002506
def write_supercells_with_displacements(supercell, cells_with_disps, filename="geo.gen"): """Writes perfect supercell and supercells with displacements Args: supercell: perfect supercell cells_with_disps: supercells with displaced atoms filename: root-filename """ # original ce...
0.003922
def get_codomain(self, key): """ RETURN AN ARRAY OF OBJECTS THAT key MAPS TO """ return [v for k, v in self.all if k == key]
0.012821
def get_models(cls, index, as_class=False): ''' Returns the list of models defined for this index. :param index: index name. :param as_class: set to True to return the model as a model object instead of as a string. ''' try: return cls._index_to_model[index] i...
0.009363
def remove(self, models): """ Removed the passed model(s) from the selection""" models = self._check_model_types(models) for model in models: if model in self._selected: self._selected.remove(model)
0.008
def _resource_prefix(self, resource=None): """Get elastic prefix for given resource. Resource can specify ``elastic_prefix`` which behaves same like ``mongo_prefix``. """ px = 'ELASTICSEARCH' if resource and config.DOMAIN[resource].get('elastic_prefix'): px = config....
0.007979
def reply(self, message): """ Sends a reply to this USSD message in the same USSD session :raise InvalidStateException: if the USSD session is not active (i.e. it has ended) :return: The USSD response message/session (as a Ussd object) """ if self.sessionActive...
0.013187
def upload_to(field_path, default): """ Used as the ``upload_to`` arg for file fields - allows for custom handlers to be implemented on a per field basis defined by the ``UPLOAD_TO_HANDLERS`` setting. """ from yacms.conf import settings for k, v in settings.UPLOAD_TO_HANDLERS.items(): ...
0.002398
def polynomial(img, mask, inplace=False, replace_all=False, max_dev=1e-5, max_iter=20, order=2): ''' replace all masked values calculate flatField from 2d-polynomal fit filling all high gradient areas within averaged fit-image returns flatField, average background level, fitte...
0.001899
def get_pairtree_prefix(pairtree_store): """Returns the prefix given in pairtree_prefix file.""" prefix_path = os.path.join(pairtree_store, 'pairtree_prefix') with open(prefix_path, 'r') as prefixf: prefix = prefixf.read().strip() return prefix
0.003731
def IsHuntStarted(self): """Is this hunt considered started? This method is used to check if new clients should be processed by this hunt. Note that child flow responses are always processed but new clients are not allowed to be scheduled unless the hunt is started. Returns: If a new cli...
0.005208
def _merge_config(self, config, templates): """ Merges config with templates """ if not templates: return config # type check if not isinstance(templates, list): raise TypeError('templates argument must be an instance of list') # merge temp...
0.005396
def _parse_vrf(self, config): """Parses config file for the OSPF vrf name Args: config(str): Running configuration Returns: dict: key: ospf_vrf (str) """ match = re.search(r'^router ospf \d+ vrf (\w+)', config) if match: r...
0.005195
def _set_mld(self, v, load=False): """ Setter method for mld, mapped from YANG variable /mld_snooping/ipv6/mld (container) If this variable is read-only (config: false) in the source YANG file, then _set_mld is considered as a private method. Backends looking to populate this variable should do ...
0.00591
def to(self, fmt=None, filename=None): """ Outputs the molecule to a file or string. Args: fmt (str): Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include "xyz",...
0.000839
def mark_offer_as_win(self, offer_id): """ Mark offer as win :param offer_id: the offer id :return Response """ return self._create_put_request( resource=OFFERS, billomat_id=offer_id, command=WIN, )
0.006873
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameGetSceneListConfirmation): self.count_scenes = frame.count_scenes if self.count_scenes == 0: self.success = True ...
0.004343
def DeserializeExclusiveData(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): Raises: Exception: If the version read is incorrect. """ if self.Version > 1: raise Exception('Invalid format') self...
0.003106
def fgmc(log_fg_ratios, mu_log_vt, sigma_log_vt, Rf, maxfg): ''' Function to fit the likelihood Fixme ''' Lb = np.random.uniform(0., maxfg, len(Rf)) pquit = 0 while pquit < 0.1: # quit when the posterior on Lf is very close to its prior nsamp = len(Lb) Rf_sel = np.rand...
0.001236
def subscribed_tracks(self): """ Access the subscribed_tracks :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList """ ...
0.006536
def _name_value_to_bson(name, value, check_keys, opts): """Encode a single name, value pair.""" # First see if the type is already cached. KeyError will only ever # happen once per subtype. try: return _ENCODERS[type(value)](name, value, check_keys, opts) except KeyError: pass ...
0.00078
def pytwis_clt(): """The main routine of this command-line tool.""" epilog = '''After launching `pytwis_clt.py`, you will be able to use the following commands: * Register a new user: 127.0.0.1:6379> register {username} {password} * Log into a user: 127.0.0.1:6379> login {username}...
0.004973
def get_args(self, kwargs): """Construct log configuration from default and user args.""" args = dict(self.LoggerArgs) args.update(kwargs) return args
0.010989
def add(self, *args): ''' Add new child tags. ''' for obj in args: if isinstance(obj, numbers.Number): # Convert to string so we fall into next if block obj = str(obj) if isinstance(obj, basestring): obj = escape(obj) self.children.append(obj) elif isi...
0.011727
def _delete(self): """Override this method in inheriting objects to perform special clearing operations.""" try: for record in self._records: try: self._records[record]._delete() except AttributeError: pass excep...
0.008475
def lookup_class_name(name, context, depth=3): """ given a table name in the form `schema_name`.`table_name`, find its class in the context. :param name: `schema_name`.`table_name` :param context: dictionary representing the namespace :param depth: search depth into imported modules, helps avoid inf...
0.004916
def build_swagger_spec(user, repo, sha, serverName): """Build grlc specification for the given github user / repo in swagger format """ if user and repo: # Init provenance recording prov_g = grlcPROV(user, repo) else: prov_g = None swag = swagger.get_blank_spec() swag['host'...
0.001729
def update_aliases(self): """ Get aliases information from room state Returns: boolean: True if the aliases changed, False if not """ changed = False try: response = self.client.api.get_room_state(self.room_id) except MatrixRequestError: ...
0.001845