text
stringlengths
78
104k
score
float64
0
0.18
def squash_unicode(obj): """coerce unicode back to bytestrings.""" if isinstance(obj,dict): for key in obj.keys(): obj[key] = squash_unicode(obj[key]) if isinstance(key, unicode): obj[squash_unicode(key)] = obj.pop(key) elif isinstance(obj, list): for ...
0.006466
def evaluate(inputs_stream, predict_fun, metric_funs, rng): """Evaluate. Args: inputs_stream: iterable of inputs to evaluate on. predict_fun: function from inputs to predictions. params should already be partially applied. metric_funs: dict from metric name to metric function, which takes inputs ...
0.008314
def setup_graph(self): """ Will setup the assign operator for that variable. """ all_vars = tfv1.global_variables() + tfv1.local_variables() for v in all_vars: if v.name == self.var_name: self.var = v break else: raise ValueError("{...
0.007958
def get_file_clusters(self, date): """Retrieves file similarity clusters for a given time frame. Args: date: the specific date for which we want the clustering details. Example: 'date': '2013-09-10' Returns: A dict with the VT report. """ api_...
0.0033
def _worst_case_load(self, worst_case_scale_factors, peakload_consumption_ratio, modes): """ Define worst case load time series for each sector. Parameters ---------- worst_case_scale_factors : dict Scale factors defined in config file 'confi...
0.003224
def reset(self, data, size): """ Set new contents for frame """ return lib.zframe_reset(self._as_parameter_, data, size)
0.013158
def p_statements_statement(p): """ statements : statement | statements_co statement """ if len(p) == 2: p[0] = make_block(p[1]) else: p[0] = make_block(p[1], p[2])
0.004673
def as_dict(self): """ Json-serializable dict representation of Molecule """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "charge": self._charge, "spin_multiplicity": self._spin_multiplicity, "sites": []...
0.003868
def update_validators(): """ Call this to updade the global nrml.validators """ validators.update({ 'fragilityFunction.id': valid.utf8, # taxonomy 'vulnerabilityFunction.id': valid.utf8, # taxonomy 'consequenceFunction.id': valid.utf8, # taxonomy 'asset.id': valid.asse...
0.000439
def get(self, section, option): """Gets an option value for a given section. Args: section (str): section name option (str): option name Returns: :class:`Option`: Option object holding key/value pair """ if not self.has_section(section): ...
0.003339
def fastaAlignmentRead(fasta, mapFn=(lambda x : x), l=None): """ reads in columns of multiple alignment and returns them iteratively """ if l is None: l = _getMultiFastaOffsets(fasta) else: l = l[:] seqNo = len(l) for i in xrange(0, seqNo): j = open(fasta, 'r') ...
0.008147
def get_python_version(path): # type: (str) -> str """Get python version string using subprocess from a given path.""" version_cmd = [path, "-c", "import sys; print(sys.version.split()[0])"] try: c = vistir.misc.run( version_cmd, block=True, nospin=True, ...
0.001567
def update_req(req): """Updates a given req object with the latest version.""" if not req.name: return req, None info = get_package_info(req.name) if info['info'].get('_pypi_hidden'): print('{} is hidden on PyPI and will not be updated.'.format(req)) return req, None if _...
0.001036
def set_default_init_cli_human_cmds(self): # pylint: disable=no-self-use """ Default commands to restore cli to human readable state are echo on, set --vt100 on, set --retcode false. :return: List of default commands to restore cli to human readable format """ post_cli_...
0.009191
def rand_imancon(X, rho): """Iman-Conover Method to generate random ordinal variables (Implementation adopted from Ekstrom, 2005) x : ndarray <obs x cols> matrix with "cols" ordinal variables that are uncorrelated. rho : ndarray Spearman Rank Correlation Matrix Links ...
0.000567
def add_handlers(self, host_pattern: str, host_handlers: _RuleList) -> None: """Appends the given handlers to our handler list. Host patterns are processed sequentially in the order they were added. All matching patterns will be considered. """ host_matcher = HostMatches(host_pa...
0.00468
def ModifyInstance(self, ModifiedInstance, IncludeQualifiers=None, PropertyList=None, **extra): # pylint: disable=invalid-name,line-too-long """ Modify the property values of an instance. This method performs the ModifyInstance operation (see :term:`DSP020...
0.000563
def plotSet(imgDir, posExTime, outDir, show_legend, show_plots, save_to_file, ftype): ''' creates plots showing both found GAUSSIAN peaks, the histogram, a smoothed histogram from all images within [imgDir] posExTime - position range of the exposure time in the image name e.g.: img_30...
0.00164
def create(self): """ Create an instance of the Time Series Service with the typical starting settings. """ self.service.create() predix.config.set_env_value(self.use_class, 'ingest_uri', self.get_ingest_uri()) predix.config.set_env_value(self.use...
0.00995
def unlock_connection(cls, conf, dsn, key=None): """ A class method to unlock a connection (given by :code:`dsn`) in the specified configuration file. Automatically opens the file and writes to it before closing. :param str conf: The configuration file to modify :param s...
0.006211
def schedule_host_svc_downtime(self, host, start_time, end_time, fixed, trigger_id, duration, author, comment): """Schedule a service downtime for each service of an host Format of the line that triggers function call:: SCHEDULE_HOST_SVC_DOWNTIME;<host_name>;<...
0.002461
def register_foreign_device(self, addr, ttl): """Add a foreign device to the FDT.""" if _debug: BIPBBMD._debug("register_foreign_device %r %r", addr, ttl) # see if it is an address or make it one if isinstance(addr, Address): pass elif isinstance(addr, str): ...
0.006757
def _load_output_data_port_models(self): """Reloads the output data port models directly from the the state""" if not self.state_copy_initialized: return self.output_data_ports = [] for output_data_port_m in self.state_copy.output_data_ports: new_op_m = deepcopy(o...
0.004107
def sorted_timeseries(self, ascending=True): """Returns a sorted copy of the TimeSeries, preserving the original one. As an assumption this new TimeSeries is not ordered anymore if a new value is added. :param boolean ascending: Determines if the TimeSeries will be ordered ascending ...
0.007634
def table(self, rows, col_width=2): '''table will print a table of entries. If the rows is a dictionary, the keys are interpreted as column names. if not, a numbered list is used. ''' labels = [str(x) for x in range(1,len(rows)+1)] if isinstance(rows, dict): ...
0.008251
def get_linenumbertable(self): """ a sequence of (code_offset, line_number) pairs. reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.12 """ # noqa lnt = self._lnt if lnt is None: buff = self.get_attribute("LineNumberTable") ...
0.003676
def _zfs_image_create(vm_name, pool, disk_name, hostname_property_name, sparse_volume, disk_size, disk_image_name): ''' Clones an existing image, or creates a new one. When cl...
0.000811
def get_json(self): """Create JSON data for iSCSI initiator. :returns: JSON data for iSCSI initiator as follows: { "DHCPUsage":{ }, "Name":{ }, "IPv4Address":{ }, "SubnetMask":{ ...
0.003135
def all_functions_called(self): ''' list(Function): List of functions reachable from the contract (include super) ''' all_calls = [f.all_internal_calls() for f in self.functions + self.modifiers] + [self.functions + self.modifiers] all_calls = [item for sublist in all_calls f...
0.007587
def _create_request_record(self, identifier, rtype, name, content, ttl, priority): # pylint: disable=too-many-arguments """Creates record for Subreg API calls""" record = collections.OrderedDict() # Mandatory content # Just for update - not for creation if identifier is not No...
0.003866
def propmerge(into, data_from): """ Merge JSON schema requirements into a dictionary """ newprops = copy.deepcopy(into) for prop, propval in six.iteritems(data_from): if prop not in newprops: newprops[prop] = propval continue new_sp = newprops[prop] for subp...
0.000699
def get_interface_detail_output_interface_ifindex(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output") ...
0.002413
def load_terminfo(terminal_name=None, fallback='vt100'): """ If the environment variable TERM is unset try with `fallback` if not empty. vt100 is a popular terminal supporting ANSI X3.64. """ terminal_name = os.getenv('TERM') if not terminal_name: if not fallback: raise Term...
0.008664
def clean(self, value): """ When cleaning field, store original value to SourceText model and return rendered field. @raise ValidationError when something went wrong with transformation. """ super_value = super(RichTextField, self).clean(value) if super_value in fields.E...
0.003638
def _sasl_authenticate(self, stream, username, authzid): """Start SASL authentication process. [initiating entity only] :Parameters: - `username`: user name. - `authzid`: authorization ID. - `mechanism`: SASL mechanism to use.""" if not stream.initia...
0.00195
def get_dependency_graph(component): """ Generate a component's graph of dependencies, which can be passed to :func:`run` or :func:`run_incremental`. """ if component not in DEPENDENCIES: raise Exception("%s is not a registered component." % get_name(component)) if not DEPENDENCIES[comp...
0.003636
def get_book(self): """Gets the ``Book`` at this node. return: (osid.commenting.Book) - the book represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_provider_manager('COM...
0.007407
def remove_service(self, zeroconf, srv_type, srv_name): """Remove the server from the list.""" self.servers.remove_server(srv_name) logger.info( "Glances server %s removed from the autodetect list" % srv_name)
0.008163
def tokenize_paragraphs(self): """Apply paragraph tokenization to this Text instance. Creates ``paragraphs`` layer.""" tok = self.__paragraph_tokenizer spans = tok.span_tokenize(self.text) dicts = [] for start, end in spans: dicts.append({'start': start, 'end': end}) ...
0.008065
def _fromScopeXpathToRefsDecl(self, scope, xpath): """ Update xpath and scope property when refsDecl is updated """ if scope is not None and xpath is not None: _xpath = scope + xpath i = _xpath.find("?") ii = 1 while i >= 0: _xpath...
0.004348
def upload_check(self, filename=None, folder_key=None, filedrop_key=None, size=None, hash_=None, path=None, resumable=None): """upload/check http://www.mediafire.com/developers/core_api/1.3/upload/#check """ return self.request('upload/check', QueryParams({ ...
0.005445
def busy_display(): """Display animation to show activity.""" sys.stdout.write("\033[?25l") # cursor off sys.stdout.flush() for x in range(1800): symb = ['\\', '|', '/', '-'] sys.stdout.write("\033[D{}".format(symb[x % 4])) sys.stdout.flush() gevent.sleep(0.1)
0.003236
def create_free_space_request_content(): """Creates an XML for requesting of free space on remote WebDAV server. :return: the XML string of request content. """ root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, 'q...
0.004132
def evaluate_model(recording, model_folder, verbose=False): """Evaluate model for a single recording.""" from . import preprocess_dataset from . import features for target_folder in get_recognizer_folders(model_folder): # The source is later than the target. That means we need to # refr...
0.000494
def to_n_ref(self, fill=0, dtype='i1'): """Transform each genotype call into the number of reference alleles. Parameters ---------- fill : int, optional Use this value to represent missing calls. dtype : dtype, optional Output dtype. Retu...
0.001178
def add_files_via_url(self, dataset_key, files={}): """Add or update dataset files linked to source URLs :param dataset_key: Dataset identifier, in the form of owner/id :type dataset_key: str :param files: Dict containing the name of files and metadata Uses file name as a di...
0.00112
def remove_variable(self, name): """Remove a variable from the problem.""" index = self._get_var_index(name) # Remove from matrix self._A = np.delete(self.A, index, 1) # Remove from bounds del self.bounds[name] # Remove from var list del self._variables[na...
0.005076
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with rotation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform ...
0.006446
def forward(self, inputs, label, begin_state, sampled_values): # pylint: disable=arguments-differ """Defines the forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". b...
0.004787
def implicify_hydrogens(self): """ remove explicit hydrogen if possible :return: number of removed hydrogens """ explicit = defaultdict(list) c = 0 for n, atom in self.atoms(): if atom.element == 'H': for m in self.neighbors(n): ...
0.003476
def get_version(): """ Return package version as listed in `__version__` in `init.py`. """ with open(os.path.join(os.path.dirname(__file__), 'argparsetree', '__init__.py')) as init_py: return re.search('__version__ = [\'"]([^\'"]+)[\'"]', init_py.read()).group(1)
0.010453
def add_require(self, require): """ Add a require object if it does not already exist """ for p in self.requires: if p.value == require.value: return self.requires.append(require)
0.008658
def propagate(self, date): """Propagate the orbit to a new date Args: date (Date) Return: Orbit """ if self.propagator.orbit is not self: self.propagator.orbit = self return self.propagator.propagate(date)
0.006849
def send_cmd_recv_rsp(self, target, data, timeout): """Exchange data with a remote Target Sends command *data* to the remote *target* discovered in the most recent call to one of the sense_xxx() methods. Note that *target* becomes invalid with any call to mute(), sense_xxx() or ...
0.001899
def init_driver(client_id): """Initialises a new driver via webwhatsapi module @param client_id: ID of user client @return webwhatsapi object """ # Create profile directory if it does not exist profile_path = CHROME_CACHE_PATH + str(client_id) if not os.path.exists(profile_path): ...
0.008172
def get_server_model(snmp_client): """Get server model of the node. :param snmp_client: an SNMP client object. :raises: SNMPFailure if SNMP operation failed. :returns: a string of server model. """ try: server_model = snmp_client.get(SERVER_MODEL_OID) return six.text_type(serve...
0.002217
def get_span_offsets(docgraph, node_id): """ returns the character start and end position of the span of text that the given node spans or dominates. Returns ------- offsets : tuple(int, int) character onset and offset of the span """ try: span = get_span(docgraph, node_...
0.001431
def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. ...
0.003521
def supported_languages(self, task=None): """Languages that are covered by a specific task. Args: task (string): Task name. """ if task: collection = self.get_collection(task=task) return [isoLangs[x.id.split('.')[1]]["name"] for x in collectio...
0.012579
def update_member(self, member_id, peer_urls): """ Update the configuration of an existing member in the cluster. :param member_id: ID of the member to update :param peer_urls: new list of peer urls the member will use to communicate with the cluster ""...
0.002999
def export(self, class_name=None, method_name=None, num_format=lambda x: str(x), details=False, **kwargs): # pylint: disable=unused-argument """ Transpile a trained model to the syntax of a chosen programming language. Parameters ---------- :param ...
0.00194
def get_token(self, token): ''' Request a token from the master ''' load = {} load['token'] = token load['cmd'] = 'get_token' tdata = self._send_token_request(load) return tdata
0.008299
def from_config(cls, cp, variable_params): """Gets sampling transforms specified in a config file. Sampling parameters and the parameters they replace are read from the ``sampling_params`` section, if it exists. Sampling transforms are read from the ``sampling_transforms`` section(s), u...
0.001396
def dict_to_nvlist(dict): '''Convert a dictionary into a CORBA namevalue list.''' result = [] for item in list(dict.keys()): result.append(SDOPackage.NameValue(item, omniORB.any.to_any(dict[item]))) return result
0.008299
def change_forms(self, *args, **keywords): """ Checks which form is currently displayed and toggles to the other one """ # Returns to previous Form in history if there is a previous Form try: self.parentApp.switchFormPrevious() except Exception as e: # pragma...
0.005319
def parse_args(args=None): """Parses arguments, returns (options, args).""" from argparse import ArgumentParser if args is None: args = sys.argv parser = ArgumentParser(description='Rename template project with' 'hyphen-separated <new name> (path names and in ' ...
0.001938
def ontologyShapeTree(self): """ Returns a dict representing the ontology tree Top level = {0:[top properties]} Multi inheritance is represented explicitly """ treedict = {} if self.all_shapes: treedict[0] = self.toplayer_shapes for element...
0.004082
def walk_files_info(self, relativePath="", fullPath=False, recursive=False): """ Walk the repository relative path and yield tuple of two items where first item is file relative/full path and second item is file info. If file info is not found on disk, second item will be None. ...
0.00721
def mask_binary(self, binary_im): """Create a new image by zeroing out data at locations where binary_im == 0.0. Parameters ---------- binary_im : :obj:`BinaryImage` A BinaryImage of the same size as this image, with pixel values of either zero or one. Wh...
0.005563
def compileFeatures( ufo, ttFont=None, glyphSet=None, featureWriters=None, featureCompilerClass=None, ): """ Compile OpenType Layout features from `ufo` into FontTools OTL tables. If `ttFont` is None, a new TTFont object is created containing the new tables, else the provided `ttFont` is...
0.000755
def stop(self, ends=None, forced=False): """ Stops an ``NuMap`` instance. If the list of end tasks is specified *via* the "ends" argument a call to ``NuMap.stop`` will block the calling thread and retrieve (discards) a maximum of 2 * stride of results. This will stop the worke...
0.008089
def current_sleep_breakdown(self): """Return durations of sleep stages for in-progress session.""" try: stages = self.intervals[0]['stages'] breakdown = {'awake': 0, 'light': 0, 'deep': 0, 'rem': 0} for stage in stages: if stage['stage'] == 'awake': ...
0.002584
def export(self, nidm_version, export_dir): """ Create prov entities and activities. """ if nidm_version['major'] < 1 or \ (nidm_version['major'] == 1 and nidm_version['minor'] < 3): self.type = NIDM_DATA_SCALING # Create "Data" entity # FIXME: gra...
0.002186
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SyncMapItemContext for this SyncMapItemInstance :rtype: twilio.rest.preview.sync.service.sync_map...
0.007418
def get_attached_container_host_config_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to set up the HostConfig or start an attached container. :param action: Action configuration. :type action: ActionConfig :param contain...
0.006826
def set_index(self, field, value): """ set_index(field, value) Works like :meth:`add_index`, but ensures that there is only one index on given field. If other found, then removes it first. :param field: The index field. :type field: string :param value: ...
0.003284
def _get_list_widget( self, filters, actions=None, order_column="", order_direction="", page=None, page_size=None, widgets=None, **args ): """ get joined base filter and current active filter for query """ widgets = widgets or ...
0.002012
def authorization_header(self): """ Returns a string containing the authorization header used to authenticate with GenePattern. This string is included in the header of subsequent requests sent to GenePattern. """ return 'Basic %s' % base64.b64encode(bytes(self.username +...
0.010899
def satisfy_custom_matcher(self, args, kwargs): """Returns a boolean indicating whether or not the mock will accept the provided arguments. :param tuple args: A tuple of position args :param dict kwargs: A dictionary of keyword args :return: Whether or not the mock accepts the provided ...
0.007692
def execute(self, eopatch): """ Computation of NDVI slope using finite central differences This implementation loops through every spatial location, considers the valid NDVI values and approximates their first order derivative using central differences. The argument of min and max is added to t...
0.004462
def log_fault (exc, message = "", level = logging.CRITICAL, traceback = False): """Print the usual traceback information, followed by a listing of all the local variables in each frame. """ tb = sys.exc_info ()[2] stack = _get_stack (tb) LOG.log (level, "FAULT: %s%s(%s): %s", ("%s ...
0.037102
def install_anaconda_python(args): """Provide isolated installation of Anaconda python for running bcbio-nextgen. http://docs.continuum.io/anaconda/index.html """ anaconda_dir = os.path.join(args.datadir, "anaconda") bindir = os.path.join(anaconda_dir, "bin") conda = os.path.join(bindir, "conda"...
0.005803
def data_iterator_csv_dataset(uri, batch_size, shuffle=False, rng=None, normalize=True, with_memory_cache=True, with_file_cache=True, ...
0.003114
def _process_response(self, response, object_mapping=None): """ Attempt to find a ResponseHandler that knows how to process this response. If no handler can be found, raise an Exception. """ try: pretty_response = response.json() except ValueError: ...
0.00664
def capture_guest(userid): """Caputre a virtual machine image. Input parameters: :userid: USERID of the guest, last 8 if length > 8 Output parameters: :image_name: Image name that captured """ # check power state, if down, start it ret = sdk_client.send_request('guest_get_power_...
0.001344
def setColumns(self, columns): """ Sets the column count and list of columns to the inputed column list. :param columns | [<str>, ..] """ self.setColumnCount(len(columns)) self.setHeaderLabels(columns)
0.011111
def stop(self): """Permanently stop sending heartbeats.""" if not self.stopped: self.stopped = True if self.pendingHeartbeat is not None: self.pendingHeartbeat.cancel() self.pendingHeartbeat = None
0.007435
def execute_once(self, swap=None, spell_changes=None, spell_destructions=None, random_fill=False): """Execute the board only one time. Do not execute chain reactions. Arguments: swap - pair of adjacent positions spell_changes - sequence of (posi...
0.00271
def ticket_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tickets#show-ticket" api_path = "/api/v2/tickets/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
0.008032
def render_as_xml(func): """ Decorator to render as XML :param func: :return: """ if inspect.isclass(func): setattr(func, "_renderer", xml_renderer) return func else: @functools.wraps(func) def decorated_view(*args, **kwargs): data = func(*args, **...
0.002445
def _delete_nodes(self, features): """ Removes the node corresponding to each item in 'features'. """ graph = self._graph if graph is not None: for feature in features: graph.delete_node( id(feature) ) graph.arrange_all()
0.013746
def uniquify(value, seen_values): """ Adds value to seen_values set and ensures it is unique """ id = 1 new_value = value while new_value in seen_values: new_value = "%s%s" % (value, id) id += 1 seen_values.add(new_value) return new_value
0.003597
def tasks(self): """ Returns a list of all tasks known to the engine. :return: A list of task names. """ task_input = {'taskName': 'QueryTaskCatalog'} output = taskengine.execute(task_input, self._engine_name, cwd=self._cwd) return output['outputParameters']['TAS...
0.009259
def auto_load_configs(self): """Auto load all configs from app configs""" for app in apps.get_app_configs(): for model in app.get_models(): config = ModelConfig(model, getattr(app, model.__name__, None)) self.configs[self.get_model_name(model)] = config
0.00639
def call(cmd, input=None, assert_zero_exit_status=True, warn_on_non_zero_exist_status=False, **kwargs): """ :rtype: SubprocessResult Raises OSError if command was not found Returns non-zero result in result.ret if subprocess terminated with non-zero exist status. """ if (not kwargs.get('shell'...
0.004172
def is_fully_defined(self): """Returns True iff `self` is fully defined in every dimension.""" return self._dims is not None and all( dim.value is not None for dim in self._dims )
0.009302
def _fetch_from_archive(self, method, args): """Fetch data from the archive :param method: the name of the command to execute :param args: the arguments required by the command """ if not self.archive: raise ArchiveError(cause="Archive not provided") data = ...
0.00432
def _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type newPathName: String @return: Path Name as string. """ directory = self._directory() assert...
0.004444
def _read(self, fd, mask): """Read waiting data and terminate Tk mainloop if done""" try: # if EOF was encountered on a tty, avoid reading again because # it actually requests more data if select.select([fd],[],[],0)[0]: snew = os.read(fd, self.nbytes)...
0.010596
def masked_rec_array_to_mgr(data, index, columns, dtype, copy): """ Extract from a masked rec array and create the manager. """ # essentially process a record array then fill it fill_value = data.fill_value fdata = ma.getdata(data) if index is None: index = get_names_from_index(fdat...
0.00089