text
stringlengths
78
104k
score
float64
0
0.18
def save_xml(self, doc, element): '''Save this location into an xml.dom.Element object.''' element.setAttributeNS(RTS_EXT_NS, RTS_EXT_NS_S + 'x', str(self.x)) element.setAttributeNS(RTS_EXT_NS, RTS_EXT_NS_S + 'y', str(self.y)) element.setAttributeNS(RTS_EXT_NS, RTS_EXT_NS_S + 'height', ...
0.00321
def taskCompleted(self, *args, **kwargs): """ Task Completed Messages When a task is successfully completed by a worker a message is posted this exchange. This message is routed using the `runId`, `workerGroup` and `workerId` that completed the task. But information abou...
0.002612
def _gatk_apply_bqsr(data): """Parallel BQSR support for GATK4. Normalized qualities to 3 bin outputs at 10, 20 and 30 based on pipeline standard recommendations, which will help with output file sizes: https://github.com/CCDG/Pipeline-Standardization/blob/master/PipelineStandard.md#base-quality-score-...
0.004444
def from_(self) -> Optional[Sequence[AddressHeader]]: """The ``From`` header.""" try: return cast(Sequence[AddressHeader], self[b'from']) except KeyError: return None
0.009346
def _ParseCommentRecord(self, structure): """Parse a comment and store appropriate attributes. Args: structure (pyparsing.ParseResults): parsed log line. """ comment = structure[1] if comment.startswith('Version'): _, _, self._version = comment.partition(':') elif comment.startswith...
0.009058
def build(self) -> RegisteredTypeJSONEncoderType: """ Builds JSON encoder that uses the encoders registered at the point in time when this method is called. :return: the JSON encoder """ class_name = "%s_%s" % (_RegisteredTypeJSONEncoder.__class__.__name__, id(self)) # Us...
0.007452
def _combined_regex(regexes, flags=re.IGNORECASE, use_re2=False, max_mem=None): """ Return a compiled regex combined (using OR) from a list of ``regexes``. If there is nothing to combine, None is returned. re2 library (https://github.com/axiak/pyre2) often can match and compile large regexes much f...
0.001244
def FindNotNaNBackwards(x, i): """Returns last position (starting at i backwards) which is not NaN, or -1.""" while i >= 0: if not np.isnan(x[i]): return i i -= 1 return -1
0.009174
def authenticate(self, username, password): """ Should try to login with abakus.no (NERD). """ if getattr(settings, 'ABAKUS_DUMMY_AUTH', False): return self.dummy_authenticate(username, password) response = requests.post(url=path, data={'username': username, 'password...
0.002862
def get_dataset(corpora): """ Return a dictionary of subjectID -> [path_to_resource]. """ # TODO: make filter methods for the files def make_posix_path(dirpath, filename): dirpath = posixpath.sep.join(dirpath.split(os.sep)) return posixpath.join(dirpath, filename) wav_files_in_...
0.002436
def _check_completion_errors(self): """ Parses four potential errors that can cause jobs to crash: inability to transform coordinates due to a bad symmetric specification, an input file that fails to pass inspection, and errors reading and writing files. """ if read_patte...
0.002525
def predict(self, y_prob, cost_mat): """ Calculate the prediction using the Bayes minimum risk classifier. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of shape = [n_samples, 4] Cost m...
0.003656
def _load_from_module(module): """ 从python模块中获取配置 :param py: :return: """ settings = OrderedDict() for key in dir(module): if key.isupper(): settings[key] = getattr(module, key) return settings
0.004065
def get_all(self, search_filter=None): """Fetch all data from backend.""" items = self.backend.get_all() if not items: if self.version == 1: return {self.namespace: []} return [] if search_filter: items = jmespath.search(search_filter...
0.005714
def __read_stored_routine_metadata(self): """ Reads the metadata of stored routines from the metadata file. """ if os.path.isfile(self._pystratum_metadata_filename): with open(self._pystratum_metadata_filename, 'r') as file: self._pystratum_metadata = json.loa...
0.006116
def DEFINE(parser, name, default, help, flag_values=_flagvalues.FLAGS, # pylint: disable=redefined-builtin,invalid-name serializer=None, module_name=None, **args): """Registers a generic Flag object. NOTE: in the docstrings of all DEFINE* functions, "registers" is short for "creates a new flag and re...
0.004284
def _descend_cashed(self, curr, s): """ Спуск из вершины curr по строке s с кэшированием """ if s == "": return curr curr_cash = self._descendance_cash[curr] answer = curr_cash.get(s, None) if answer is not None: return answer # для...
0.003413
def eeg_add_events(raw, events_channel, conditions=None, treshold="auto", cut="higher", time_index=None, number="all", after=0, before=None, min_duration=1): """ Find events on a channel, convert them into an MNE compatible format, and add them to the raw data. Parameters ---------- raw : mne.io.Ra...
0.004885
def intervalCreateSimulateAnalyze (netParams=None, simConfig=None, output=False, interval=None): ''' Sequence of commands create, simulate and analyse network ''' import os from .. import sim (pops, cells, conns, stims, rxd, simData) = sim.create(netParams, simConfig, output=True) try: if si...
0.008427
def with_translations(self, **kwargs): """ Prefetches translations. Takes three optional keyword arguments: * ``field_names``: ``field_name`` values for SELECT IN * ``languages``: ``language`` values for SELECT IN * ``chunks_length``: fetches IDs by chunk """ ...
0.003106
def is_jsonable(obj) -> bool: """ Check if an object is jsonable. An object is jsonable if it is json serialisable and by loading its json representation the same object is recovered. Parameters ---------- obj : Python object Returns ------- bool >>> is_jsonable([1,2,...
0.008913
def filter_resource(self, resource_name, field_name, field_value, result_handler=ONE_RESULT): """ :return: The resource (as json), or None """ return self.multi_filter_resource(resource_name, {field_name: field_value}, ...
0.007712
def _data_channel_close(self, channel, transmit=True): """ Request closing the datachannel by sending an Outgoing Stream Reset Request. """ if channel.readyState not in ['closing', 'closed']: channel._setReadyState('closing') self._reconfig_queue.append(channel.id...
0.006928
def get_tree_collection_strings(self, scale=1, guide_tree=None): """ Function to get input strings for tree_collection tree_collection needs distvar, genome_map and labels - these are returned in the order above """ records = [self.collection[i] for i in self.indices] ret...
0.005348
def is_logged(self, user): """Check if a logged user is trying to access the register page. If so, redirect him/her to his/her profile""" response = None if user.is_authenticated(): if not user.needs_update: response = redirect('user_profile', username=use...
0.005618
def getDesc(self, entry): """Returns description for stat entry. @param entry: Entry name. @return: Description for entry. """ if len(self._descDict) == 0: self.getStats() return self._descDict.get(entry)
0.013937
def summary(self): """produce a summary of the model statistics Parameters ---------- None Returns ------- None """ if not self._is_fitted: raise AttributeError('GAM has not been fitted. Call fit first.') # high-level model s...
0.007581
def find(self, query, threshold=None): """Simply return the best match to the query, None on no match. >>> from ngram import NGram >>> n = NGram(["Spam","Eggs","Ham"], key=lambda x:x.lower(), N=1) >>> n.find('Hom') 'Ham' >>> n.find("Spom") 'Spam' >>> n.fi...
0.004115
def create_dialog(obj, obj_name): """Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt...
0.002993
def setMode(self, mode): """Sets the type of crypting mode, pyDes.ECB or pyDes.CBC""" _baseDes.setMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setMode(mode)
0.031088
def pair_SAM_alignments( alignments, bundle=False, primary_only=False): '''Iterate over SAM aligments, name-sorted paired-end Args: alignments (iterator of SAM/BAM alignments): the alignments to wrap bundle (bool): if True, bundle all alignments from one read pair into a...
0.001721
def get(self, uid=None, key_wrapping_specification=None): """ Get a managed object from a KMIP appliance. Args: uid (string): The unique ID of the managed object to retrieve. key_wrapping_specification (dict): A dictionary containing various settings to b...
0.000604
def _id_var(x, drop=False): """ Assign ids to items in x. If two items are the same, they get the same id. Parameters ---------- x : array-like items to associate ids with drop : bool Whether to drop unused factor levels """ if len(x) == 0: return [] cat...
0.000873
def kill(self, id, signal=signal.SIGTERM): """ Kill a job with given id :WARNING: beware of what u kill, if u killed redis for example core0 or coreX won't be reachable :param id: job id to kill """ args = { 'id': id, 'signal': int(signal), ...
0.007317
def parameters(self): """ Get the tool parameters :return: The tool parameters along with additional information (whether they are functions or sets) """ parameters = [] for k, v in self.__dict__.items(): if k.startswith("_"): continue ...
0.003606
def get_parameter(self, param_name: str) -> Parameter: """ This interface is used to get a Parameter object from an AbiFunction object which contain given function parameter's name, type and value. :param param_name: a string used to indicate which parameter we want to get from AbiFunct...
0.008278
def get_adjacency_matrix(self, fmt='coo'): r""" Returns an adjacency matrix in the specified sparse format, with 1's indicating the non-zero values. Parameters ---------- fmt : string, optional The sparse storage format to return. Options are: *...
0.001413
def cur_space(self, name=None): """Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned. """ if name is None: ...
0.004107
def intersectWithLine(self, p0, p1): """Return the list of points intersecting the actor along the segment defined by two points `p0` and `p1`. :Example: .. code-block:: python from vtkplotter import * s = Spring(alpha=0.2) pts = s.i...
0.003591
def open(self, filepath): """ Open settings backend to return its content Args: filepath (str): Settings object, depends from backend Returns: string: File content. """ with io.open(filepath, 'r', encoding='utf-8') as fp: content = f...
0.005698
def parse(self, paramfile): """ Read parameter file and set parameter values. File should have python-like syntax. Full file name needed. """ with open(paramfile, 'r') as f: for line in f.readlines(): line_clean = line.rstrip('\n').split('#')[0] # trim out ...
0.004021
def rendered(self): """Return (generating first if needed) rendered template.""" if not self._rendered: template_path = get_template_path(self.raw_template_path) if template_path: with open(template_path, 'r') as template: if len(os.path.splite...
0.002014
def axis_rotation(points, angle, inplace=False, deg=True, axis='z'): """ Rotates points angle ang (in deg) about an axis """ axis = axis.lower() # Copy original array to if not inplace if not inplace: points = points.copy() # Convert angle to radians if deg: angle *= np.pi / 18...
0.000912
def stop(self, *args, **kwargs): """ Set the status to Status.stopping and also call `onStopping` with the provided args and kwargs. """ if self.status in (Status.stopping, Status.stopped): logger.debug("{} is already {}".format(self, self.status.name)) else: ...
0.004474
def create_toc(doctree, depth=9223372036854775807, writer_name='html', exclude_first_section=True, href_prefix=None, id_prefix='toc-ref-'): """ Create a Table of Contents (TOC) from the given doctree Returns: (docutils.core.Publisher instance, output string) `writer_name`: represents a ...
0.00082
def _request(self, method, resource_uri, **kwargs): """Perform a method on a resource. Args: method: requests.`method` resource_uri: resource endpoint Raises: HTTPError Returns: JSON Response """ data = kwargs.get('data') ...
0.003968
def replaceNewlines(string, newlineChar): """There's probably a way to do this with string functions but I was lazy. Replace all instances of \r or \n in a string with something else.""" if newlineChar in string: segments = string.split(newlineChar) string = "" for segment in segments: string += segment r...
0.027108
def get_qualified_type(stmt): """Gets the qualified, top-level type of the node. This enters the typedef if defined instead of using the prefix to ensure absolute distinction. """ type_obj = stmt.search_one('type') fq_type_name = None if type_obj: if getattr(type_obj, 'i_typedef', No...
0.001239
def inside_nonspeech(self, index): """ If ``index`` is contained in a nonspeech interval, return a pair ``(interval_begin, interval_end)`` such that ``interval_begin <= index < interval_end``, i.e., ``interval_end`` is assumed not to be included. Otherwise, return ``None...
0.005085
def initialize_object(B, res, row): """ Do a shallow initialization of an object Arguments: - row<dict>: dict of data like depth=1, i.e. many_refs are only ids """ B = get_backend() field_groups = FieldGroups(B.get_concrete(res)) try: obj = B.get_object(B.get_concrete(res),...
0.000568
def photo_url(self): """获取用户头像图片地址. :return: 用户头像url :rtype: str """ if self.url is not None: if self.soup is not None: img = self.soup.find('img', class_='Avatar Avatar--l')['src'] return img.replace('_l', '_r') else: ...
0.003914
def publish(self, message_type, client_id, client_storage, *args, **kwargs): """ Publishes a message """ p = self.pack(message_type, client_id, client_storage, args, kwargs) self.client.publish(self.channel, p)
0.008
def _validate_buckets(categorical, k, scheme): """ This method validates that the hue parameter is correctly specified. Valid inputs are: 1. Both k and scheme are specified. In that case the user wants us to handle binning the data into k buckets ourselves, using the stated algorithm. We iss...
0.007074
def send_messages(self, messages): """Write all messages to the stream in a thread-safe way.""" if not messages: return self._lock.acquire() try: # The try-except is nested to allow for # Python 2.4 support (Refs #12147) try: ...
0.003363
def set(self, fmt, offset, value): """ Set the value of a given bitfield. :param fmt: format-string for the bitfield being read, e.g. u8 for an unsigned 8-bit integer. :param int offset: offset (in number of bits). :param int value: value to set at the given position...
0.004057
def convert(self, request, response, data): """ Performs the desired Conversion. :param request: The webob Request object describing the request. :param response: The webob Response object describing the response. :param data: The...
0.000979
def do_set_hub_connection(self, args): """Set Hub connection parameters. Usage: set_hub_connection username password host [port] Arguments: username: Hub username password: Hub password host: host name or IP address port: IP port [def...
0.001953
def fill_stroke(self, fill = None, stroke = None, opacity = 1, line_width = None): """fill and stroke the drawn area in one go""" if line_width: self.set_line_style(line_width) if fill and stroke: self.fill_preserve(fill, opacity) elif fill: self.fill(fill, opaci...
0.032
def probe_async(self, callback): """Send advertisements for all connected devices. Args: callback (callable): A callback for when the probe operation has completed. callback should have signature callback(adapter_id, success, failure_reason) where: succes...
0.005993
def install_string(self): """ Add every missing file to the install string shown to the user in an error message. """ args = [ "--reference-name", self.reference_name, "--annotation-name", self.annotation_name] if self.annotation_version: ...
0.002172
def nx_transitive_reduction(G, mode=1): """ References: https://en.wikipedia.org/wiki/Transitive_reduction#Computing_the_reduction_using_the_closure http://dept-info.labri.fr/~thibault/tmp/0201008.pdf http://stackoverflow.com/questions/17078696/transitive-reduction-of-directed-graph-in-p...
0.00106
def RemoveEmptyDirectoryTree(path, silent = False, recursion = 0): """ Delete tree of empty directories. Parameters ---------- path : string Path to root of directory tree. silent : boolean [optional: default = False] Turn off log output. recursion : int [optional: default = 0] ...
0.016647
def delete_hit(self, hitid): ''' Delete HIT ''' if not self.connect_to_turk(): return False try: self.mtc.delete_hit(HITId=hitid) except Exception, e: print "Failed to delete of HIT %s. Make sure there are no "\ "assignments remaining t...
0.005831
def parse_ppi_graph(path: str, min_edge_weight: float = 0.0) -> Graph: """Build an undirected graph of gene interactions from edgelist file. :param str path: The path to the edgelist file :param float min_edge_weight: Cutoff to keep/remove the edges, default is 0, but could also be 0.63. :return Graph:...
0.003783
def geocode(self, string, bounds=None, region=None, language=None, sensor=False): '''Geocode an address. Pls refer to the Google Maps Web API for the details of the parameters ''' if isinstance(string, unicode): string = string.encode('utf-8') params ...
0.010936
def quantile_1D(data, weights, quantile): """ Compute the weighted quantile of a 1D numpy array. Parameters ---------- data : ndarray Input array (one dimension). weights : ndarray Array with the weights of the same size of `data`. quantile : float Quantile to comput...
0.001336
def db_tables(name, **connection_args): ''' Shows the tables in the given MySQL database (if exists) CLI Example: .. code-block:: bash salt '*' mysql.db_tables 'database' ''' if not db_exists(name, **connection_args): log.info('Database \'%s\' does not exist', name) re...
0.001106
def options(self, context, module_options): ''' COMMAND Mimikatz command to execute (default: 'sekurlsa::logonpasswords') ''' self.command = 'privilege::debug sekurlsa::logonpasswords exit' if module_options and 'COMMAND' in module_options: self.command = module_o...
0.00939
def get_bar_config_list(self): """ Get list of bar IDs as active in the connected i3 session. :rtype: List of strings that can be fed as ``bar_id`` into :meth:`get_bar_config`. """ data = self.message(MessageType.GET_BAR_CONFIG, '') return json.loads(data)
0.006309
def register(self, _type, _format, creater, _2nd_pass=None): """ register a type/format handler when producing primitives example function to create a byte primitive: ```python def create_byte(obj, val, ctx): # val is the value used to create this primitive, for example, a ...
0.00295
def p_information_duration_speed(self, p): 'information : duration AT speed' logger.debug('information = duration %s at speed %s', p[1], p[3]) p[0] = p[3].for_duration(p[1])
0.010152
def _add_leaf_from_storage(self, args, kwargs): """Can be called from storage service to create a new leaf to bypass name checking""" return self._nn_interface._add_generic(self, type_name=LEAF, group_type_na...
0.014898
def all_equal(keys, axis=semantics.axis_default): """returns true of all keys are equal""" index = as_index(keys, axis) return index.groups == 1
0.00641
def read_json (self, mode='rt', **kwargs): """Use the :mod:`json` module to read in this file as a JSON-formatted data structure. Keyword arguments are passed to :func:`json.load`. Returns the read-in data structure. """ import json with self.open (mode=mode) as f: ...
0.019553
def _get_merged_nics(hypervisor, profile, interfaces=None, dmac=None): ''' Get network devices from the profile and merge uer defined ones with them. ''' nicp = _nic_profile(profile, hypervisor, dmac=dmac) if profile else [] log.debug('NIC profile is %s', nicp) if interfaces: users_nics ...
0.001572
def published(self, for_user=UNSET, force_exchange=False): """ Apply additional filtering of published items over that done in `PublishingQuerySet.published` to filter based on additional publising date fields used by Fluent. """ if for_user is not UNSET: retu...
0.001695
def update(self, photo, **kwds): """ Endpoint: /photo/<id>/update.json Updates a photo with the specified parameters. Returns the updated photo object. """ result = self._client.post("/photo/%s/update.json" % self._extract_id(photo), ...
0.004843
def make_multi_metatile(parent, tiles, date_time=None): """ Make a metatile containing a list of tiles all having the same layer, with coordinates relative to the given parent. Set date_time to a 6-tuple of (year, month, day, hour, minute, second) to set the timestamp for members. Otherwise the curr...
0.000493
def _try_redeem_disposable_app(file, client): """ Attempt to redeem a one time code registred on the client. """ redeemedClient = client.redeem_onetime_code(None) if redeemedClient is None: return None else: return _BlotreDisposableApp(file, redeemedClient.client, ...
0.0199
def loader_for_file(filename): """ Returns a Loader that can load the specified file, based on the file extension. None if failed to determine. :param filename: the filename to get the loader for :type filename: str :return: the assoicated loader instance or None if none found :rtype: Loader ...
0.004975
def extendleft(self, iterable): """Extend the left side of this GeventDeque by appending elements from the iterable argument. Note, the series of left appends results in reversing the order of elements in the iterable argument. """ self._deque.extendleft(iterable) ...
0.005291
def parse(self, args=None): """Parse textual keywords as described by this class’s attributes, and update this instance’s attributes with the parsed values. *args* is a list of strings; if ``None``, it defaults to ``sys.argv[1:]``. Returns *self* for convenience. Raises :exc:`KwargvError...
0.001885
def set_ctype(self, ctype, orig_ctype=None): """ Set the selected content type. Will not override the value of the content type if that has already been determined. :param ctype: The content type string to set. :param orig_ctype: The original content type, as found in the ...
0.004228
def summary(self, summary): """Prints the ASCII Icon""" if summary is not None: if summary == 'Clear': click.secho(""" ________ \ | / / ____/ /__ ____ ______ .-. / / / / _ \/ __ `/ ___/ ‒ ( ) ‒ / /___/ / __/ /_/ / / `-᾿ \__...
0.015014
def getTempFile(dir=None, shared=False, suffix=""): '''get a temporary file. The file is created and the caller needs to close and delete the temporary file once it is not used any more. Arguments --------- dir : string Directory of the temporary file and if not given is set to the ...
0.001241
def uimports(code): """ converts CPython module names into MicroPython equivalents """ for uimport in UIMPORTLIST: uimport = bytes(uimport, 'utf8') code = code.replace(uimport, b'u' + uimport) return code
0.00431
def is_address_reserved(self, address): """ Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address...
0.00295
def slice_config(config, key): """ Slice config for printing as defined in key. :param ConfigManager config: configuration dictionary :param str key: dotted key, by which config should be sliced for printing :returns: sliced config :rtype: dict """ if key: keys = key.split('.')...
0.002545
def unset_env(self, key): """Removes an environment variable using the prepended app_name convention with `key`.""" os.environ.pop(make_env_key(self.appname, key), None) self._registered_env_keys.discard(key) self._clear_memoization()
0.011278
def security_group(self, vpc): """Create and configure a new security group. Allows all ICMP in, all TCP and UDP in within VPC. This security group is very open. It allows all incoming ping requests on all ports. It also allows all outgoing traffic on all ports. This can be limited by ...
0.00213
def surface(self, param): """Return the detector surface point corresponding to ``param``. For parameter value ``p``, the surface point is given by :: surf = p[0] * axes[0] + p[1] * axes[1] Parameters ---------- param : `array-like` or sequence Paramete...
0.000779
def restore_taskset(self, taskset_id): """Get the async result instance by taskset id.""" try: return self.get(taskset_id=taskset_id) except self.model.DoesNotExist: pass
0.009174
def build_message(self): """ Make the one string message sent to the bulb """ if self.params is None: inline_params = "" else: # Put all params in one string inline_params = "" if type(self.params) is list: for x...
0.003681
def update_models_recursively(state_m, expected=True): """ If a state model is reused the model depth maybe is to low. Therefore this method checks if all library state models are created with reliable depth :param bool expected: Define newly generated library models as expected or triggers logger war...
0.006018
def connect(self): ''' Connects to the IRC server with the options defined in `config` ''' self._connect() try: self._listen() except (KeyboardInterrupt, SystemExit): pass finally: self.close()
0.006993
def _conform_mask(in_mask, in_reference): """Ensures the mask headers make sense and match those of the T1w""" from pathlib import Path import nibabel as nb from nipype.utils.filemanip import fname_presuffix ref = nb.load(in_reference) nii = nb.load(in_mask) hdr = nii.header.copy() hdr....
0.000946
def _get_support_mask(self): """ Get the boolean mask indicating which features are selected Returns ------- support : boolean array of shape [# input features] An element is True iff its corresponding feature is selected for retention. """ ...
0.00381
def get_topics_watermarks(kafka_client, topics, raise_on_error=True): """ Get current topic watermarks. NOTE: This method does not refresh client metadata. It is up to the caller to use avoid using stale metadata. If any partition leader is not available, the request fails for all the other topics...
0.000316
def _denominator(self, weighted, include_transforms_for_dims, axis): """Calculate denominator for percentages. Only include those H&S dimensions, across which we DON'T sum. These H&S are needed because of the shape, when dividing. Those across dims which are summed across MUST NOT be in...
0.003788
def system_status(): # noqa: E501 """Retrieve the system status Retrieve the system status # noqa: E501 :rtype: Response """ if(not hasAccess()): return redirectUnauthorized() body = State.config.serialize(["driver", "log", "log-file", "log-colorize"]) body.update({'debug': Stat...
0.007177