Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
347,800
def build_edit_form(title, id, cols, return_page): txt = + title + txt += + return_page + txt += + str(id) + txt += + str(id) + txt += for col_num, col in enumerate(cols): txt += txt += + col + txt += + str(col_num) + txt += txt += ...
returns the html for a simple edit form
347,801
def _create_config_file(out_dir, samples): out_file = os.path.join(out_dir, "multiqc_config.yaml") out = {"table_columns_visible": dict()} if any(("qualimap" in dd.get_tools_on(d) or "qualimap_full" in dd.get_tools_on(d)) for d in samples): out["table_columns_visible"]["bcbio"] =...
Provide configuration file hiding duplicate columns. Future entry point for providing top level configuration of output reports.
347,802
def visit_Attribute(self, node): new_node = ast.Name("%s.%s" % (node.value.id, node.attr), node.ctx) return ast.copy_location(new_node, node)
Flatten one level of attribute access.
347,803
def _clipPrices(self): if self.guaranteeOfferPrice: for offer in self.offers: if offer.accepted and offer.clearedPrice < offer.price: offer.clearedPrice = offer.price if self.guaranteeBidPrice: for bid in self.bids: ...
Clip cleared prices according to guarantees and limits.
347,804
def _parse_tree(self, node): if node.tag == : if in node.attrib and node.attrib[] == : self.kind = self.value = node.text.lower()
Parse a <provide> object
347,805
def console_main(): from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument(, , action=, help=) parser.add_argument( , , choices=[, ], help=( )) parser.add_argument(, , type=float, ...
Process command-line arguments.
347,806
def _parse_udf_descriptors(self): block_size = self.pvd.logical_block_size() anchor_locations = [(256 * block_size, os.SEEK_SET), (-2048, os.SEEK_END)] for loc, whence in anchor_locations: self._cdfp.seek(loc, whence) extent = self._cdfp.tell()...
An internal method to parse the UDF descriptors on the ISO. This should only be called if it the ISO has a valid UDF Volume Recognition Sequence at the beginning of the ISO. Parameters: None. Returns: Nothing.
347,807
def one_step(self, current_state, previous_kernel_results): with tf.compat.v1.name_scope( name=mcmc_util.make_name(self.name, , ), values=[ self.step_size, self.max_doublings, self._seed_stream, current_state, previous_kernel_results.target_log_prob ]): wit...
Runs one iteration of Slice Sampler. Args: current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). The first `r` dimensions index independent chains, `r = tf.rank(target_log_prob_fn(*current_state))`. previous_kernel_result...
347,808
def _download_movielens(dest_path): url = req = requests.get(url, stream=True) with open(dest_path, ) as fd: for chunk in req.iter_content(): fd.write(chunk)
Download the dataset.
347,809
def json_encode_default(obj): if isinstance(obj, (datetime, date)): result = dt2ts(obj) else: result = json_encoder.default(obj) return to_encoding(result)
Convert datetime.datetime to timestamp :param obj: value to (possibly) convert
347,810
def _pip_safe_ssl(cmds, anaconda_dir): try: for cmd in cmds: subprocess.check_call(cmd) except subprocess.CalledProcessError: _set_pip_ssl(anaconda_dir) for cmd in cmds: subprocess.check_call(cmd)
Run pip, retrying with conda SSL certificate if global certificate fails.
347,811
def deregister(self, key): if not key in self._actions: return False del self._actions[key] if key in self._cache: del self._cache[key] return True
Deregisters an existing key. `key` String key to deregister. Returns boolean.
347,812
def ipc_weights(event, time): if event.all(): return numpy.ones(time.shape[0]) unique_time, p = kaplan_meier_estimator(~event, time) idx = numpy.searchsorted(unique_time, time[event]) Ghat = p[idx] assert (Ghat > 0).all() weights = numpy.zeros(time.shape[0]) weights[event] =...
Compute inverse probability of censoring weights Parameters ---------- event : array, shape = (n_samples,) Boolean event indicator. time : array, shape = (n_samples,) Time when a subject experienced an event or was censored. Returns ------- weights : array, shape = (n_samp...
347,813
def getdict(source): std_dict = {} for var, val in source.iteritems(): std_dict[var] = source[var] return std_dict
Returns a standard python Dict with computed values from the DynDict :param source: (DynDict) input :return: (dict) Containing computed values
347,814
def _filter_options(self, aliases=True, comments=True, historical=True): options = [] if not aliases: options.append() if not comments: options.append() if not historical: options.append() return options
Converts a set of boolean-valued options into the relevant HTTP values.
347,815
def update_uris(self, new_uri): self.uri = new_uri if self.obj: self.obj.base_url = .format(self.uri, self.service_name)
Update all URIS. :param new_uri: URI to switch to and update the matching :returns: n/a Note: This overwrites any existing URI
347,816
def index_open(self, index): my_index request = self.session url = % (self.host, self.port, index) response = request.post(url,None) return response
Opens the speicified index. http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close.html > ElasticSearch().index_open('my_index')
347,817
def add(self, *args): self.children.extend(args) bump_child_depth(self, self._depth) return self.children
Add object(s) to the Container. :param *args: Any objects to add to the Container. :returns: full list of Container's child objects
347,818
def euler_tour_dfs(G, source=None): if source is None: nodes = G else: nodes = [source] yielder = [] visited = set() for start in nodes: if start in visited: continue visited.add(start) stack = [(start, iter(G[start]))] ...
adaptation of networkx dfs
347,819
def set_dataset_year_range(self, dataset_year, dataset_end_year=None): if isinstance(dataset_year, int): dataset_date = % dataset_year elif isinstance(dataset_year, str): dataset_date = % dataset_year else: raise hdx.data.hdxobject.HDXError...
Set dataset date as a range from year or start and end year. Args: dataset_year (Union[str, int]): Dataset year given as string or int dataset_end_year (Optional[Union[str, int]]): Dataset end year given as string or int Returns: None
347,820
def block(self): if self._uses_subprocess: if self.blocking: try: stdout, stderr = self.subprocess.communicate() self.__out = stdout self.__err = stderr except ValueError: ...
Blocks until process is complete.
347,821
def alwaysThrew(cls, spy, error_type=None): cls.__is_spy(spy) if not (spy.alwaysThrew(error_type)): raise cls.failException(cls.message)
Checking the inspector is always raised error_type Args: SinonSpy, Exception (defaut: None)
347,822
def is_ini_file(filename, show_warnings = False): try: config_dict = load_config(filename, file_type = "ini") if config_dict == {}: is_ini = False else: is_ini = True except: is_ini = False return(is_ini)
Check configuration file type is INI Return a boolean indicating wheather the file is INI format or not
347,823
def notify_complete(self, result_code, error_info): if not isinstance(result_code, baseinteger): raise TypeError("result_code can only be an instance of type baseinteger") if not isinstance(error_info, IVirtualBoxErrorInfo): raise TypeError("error_info can only be an ins...
Internal method, not to be called externally. in result_code of type int in error_info of type :class:`IVirtualBoxErrorInfo`
347,824
def update_configuration(self): uri = "{}/configuration".format(self.data["uri"]) result = self._helper.update({}, uri) self.refresh() return result
Asynchronously applies or re-applies the SAS Logical Interconnect configuration to all managed interconnects of a SAS Logical Interconnect. Returns: dict: SAS Logical Interconnect.
347,825
def to_kirbidir(self, directory_path): kf_abs = os.path.abspath(directory_path) for cred in self.credentials: kirbi, filename = cred.to_kirbi() filename = % filename.replace(,) filepath = os.path.join(kf_abs, filename) with open(filepath, ) as o: o.write(kirbi.dump())
Converts all credential object in the CCACHE object to the kirbi file format used by mimikatz. The kirbi file format supports one credential per file, so prepare for a lot of files being generated. directory_path: str the directory to write the kirbi files to
347,826
def build_insert(self, table, values, columns=None): if not columns: columns = table.columns if len(values) < len(columns): column_names = .join(columns[-len(values):]) else: column_names = .join(columns) query = "INSERT INTO %s (%s) VALUES (%...
Insert an active record into DB and return lastrowid if available
347,827
def init_sources(path): for f in dir_list(path): if(os.path.splitext(f)[1][1:] == config.source_ext): print "Source file discovered: %s" % (f) script = Script(f) if (script.filename not in config.sources.keys()): config.sources[script.path] = script ...
initializes array of groups and their associated js files
347,828
def set_device_scale(self, x_scale, y_scale): cairo.cairo_surface_set_device_scale(self._pointer, x_scale, y_scale) self._check_status()
Sets a scale that is multiplied to the device coordinates determined by the CTM when drawing to surface. One common use for this is to render to very high resolution display devices at a scale factor, so that code that assumes 1 pixel will be a certain size will still work. Setting a t...
347,829
def normalize_outputdir(outputdir=None): normalized = cwd = os.getcwd() if not outputdir: outputdir_drivers = os.path.join(cwd, ) if os.path.isdir(outputdir_drivers): normalized = outputdir_drivers else: normalized = cwd else: normalized = os...
if output dir is None try using the ./drivers directory if it already exists, otherwise use the current working directory
347,830
def _observe_block(self, change): if self.is_initialized: if change[] == : old_block = change[] old_parent = old_block.parent for c in self.children: old_parent.child_removed(c) new_block = change[] ...
A change handler for the 'objects' list of the Include. If the object is initialized objects which are removed will be unparented and objects which are added will be reparented. Old objects will be destroyed if the 'destroy_old' flag is True.
347,831
def automain(module, *, args=(), kwargs=None): if callable(module): raise AutomainRequiresModuleError(module) if module == or module is True: if kwargs is None: kwargs = {} def automain_decorator(main): sys.exit(main(*args, **kwargs)) ...
This decorator automatically invokes a function if the module is being run as the "__main__" module. Optionally, provide args or kwargs with which to call the function. If `module` is "__main__", the function is called, and the program is `sys.exit`ed with the return value. You can also pass `True` to c...
347,832
def extract_id(*object_types): def outer(func): def inner(*args, **kwargs): def id_of(x): return x.id if type(x) in object_types else x new_args = [id_of(arg) for arg in args] new_kwargs = {k: id_of(v) for k, v in kwargs.items()} return ...
Decorator for extracting id from passed parameters for specific types.
347,833
def copy_from(self, src, dest): logger.debug("copying %s from host to container at %s", src, dest) cmd = ["machinectl", "--no-pager", "copy-from", self.name, src, dest] run_cmd(cmd)
copy a file or a directory from container or image to host system. :param src: str, path to a file or a directory within container or image :param dest: str, path to a file or a directory on host system :return: None
347,834
def use_isolated_family_view(self): self._family_view = ISOLATED for session in self._get_provider_sessions(): try: session.use_isolated_family_view() except AttributeError: pass
Pass through to provider RelationshipLookupSession.use_isolated_family_view
347,835
def _print_count(log): r log[] += 1 cp = log[]/log[]*100 if log[] == 0: pass elif log[] > log[]: print(" fmin fct calls : %d" % (log[]-log[]), end=) elif int(cp) > log[] or cp < 1 or log[] == log[]: sec = int(default_t...
r"""Print run-count information.
347,836
def get_gene_goterms(self, gene, ancestors=False): annotations = self.gene_annotations[gene] terms = set(ann.term for ann in annotations) if ancestors: assert self._flattened ancestor_terms = set() for t in terms: ancestor_terms.updat...
Return all GO terms a particular gene is annotated with. Parameters ---------- gene: str The gene symbol of the gene. ancestors: bool, optional If set to True, also return all ancestor GO terms. Returns ------- set of GOTerm objects ...
347,837
def on_drag_data_get(self, widget, context, data, info, time): tree_paths = self.iconview.get_selected_items() if not tree_paths: return filelist = [] for tree_path in tree_paths: filelist.append({ : self.liststore[tree_path][PATH_COL], ...
拖放开始
347,838
def list_of_installed(self, repo, name): all_installed_names = [] all_installed_packages = find_package("", self.meta.pkg_path) for inst in all_installed_packages: if repo == "sbo" and inst.endswith("_SBo"): name = split_package(inst)[0] all_i...
Return installed packages
347,839
def clear(self): def clear_element(): return self.element.clear() self.execute_and_handle_webelement_exceptions(clear_element, ) return self
Clears the field represented by this element @rtype: WebElementWrapper @return: Returns itself
347,840
def pushd(directory): cwd = os.getcwd() os.chdir(directory) try: yield directory finally: os.chdir(cwd)
A with-context that encapsulates pushd/popd.
347,841
def update_or_create(cls, with_status=False, overwrite_existing=False, **kw): created = False modified = False try: element = cls.get(kw.get()) except ElementNotFound: element = cls.create(**kw) created = True if not created: ...
Update or create the Access List. This method will not attempt to evaluate whether the access list has differences, instead it will update with the contents of the payload entirely. If the intent is to only add or remove a single entry, use `~add_entry` and `~remove_entry` methods. ...
347,842
def main(): if "-h" in sys.argv or "--help" in sys.argv: print(__doc__) print("Usage: regen_libxcfunc.py path_to_libxc_docs.txt") return 0 try: path = sys.argv[1] except IndexError: print(__doc__) print("Usage: regen_libxcfunc.py path_to_libxc_docs.txt")...
Main function.
347,843
def safe_extract_proto_from_ipfs(ipfs_client, ipfs_hash, protodir): spec_tar = get_from_ipfs_and_checkhash(ipfs_client, ipfs_hash) with tarfile.open(fileobj=io.BytesIO(spec_tar)) as f: for m in f.getmembers(): if (os.path.dirname(m.name) != ""): raise Exception("tarball ...
Tar files might be dangerous (see https://bugs.python.org/issue21109, and https://docs.python.org/3/library/tarfile.html, TarFile.extractall warning) we extract only simple files
347,844
def L(self): r from numpy_sugar.linalg import ddot, sum2diag if self._L_cache is not None: return self._L_cache s = self._cov["scale"] d = self._cov["delta"] Q = self._cov["QS"][0][0] S = self._cov["QS"][1] ddot(self.A * self._site.tau, Q, l...
r"""Cholesky decomposition of :math:`\mathrm B`. .. math:: \mathrm B = \mathrm Q^{\intercal}\tilde{\mathrm{T}}\mathrm Q + \mathrm{S}^{-1}
347,845
def point_eval(M, C, x): x_ = regularize_array(x) M_out = empty(x_.shape[0]) V_out = empty(x_.shape[0]) if isinstance(C, pymc.gp.BasisCovariance): y_size = len(C.basis) elif C.obs_mesh is not None: y_size = C.obs_mesh.shape[0] else: y_size = 1 n_chunks = ceil...
Evaluates M(x) and C(x). Minimizes computation; evaluating M(x) and C(x) separately would evaluate the off-diagonal covariance term twice, but callling point_eval(M,C,x) would only evaluate it once. Also chunks the evaluations if the off-diagonal term.
347,846
def StopHuntIfCPUOrNetworkLimitsExceeded(hunt_id): hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) if hunt_obj.hunt_state == rdf_hunt_objects.Hunt.HuntState.STOPPED: return hunt_obj hunt_counters = data_store.REL_DB.ReadHuntCounters(hunt_id) if (hunt_obj.total_network_bytes_limit and ...
Stops the hunt if average limites are exceeded.
347,847
def random(self, *args, **kwargs): indexer = Random() self.add(indexer) return self
Add a random index. Shortcut of :class:`recordlinkage.index.Random`:: from recordlinkage.index import Random indexer = recordlinkage.Index() indexer.add(Random())
347,848
def bar(msg=, width=40, position=None): r if position == : start_bar = end_bar = r elif position == : start_bar = r end_bar = else: start_bar = end_bar = if msg: msg = + msg + width -= 4 return start_bar + msg.center(width, ) + end_bar
r""" Returns a string with text centered in a bar caption. Examples: >>> bar('test', width=10) '== test ==' >>> bar(width=10) '==========' >>> bar('Richard Dean Anderson is...', position='top', width=50) '//========= Richard Dean Anderson is... ========\\\\' >>> bar('...MacGyver', p...
347,849
def build_queryset(self): paths = [(os.path.join(self.build_prefix, ), {})] self.request = None queryset = self.get_queryset() paginator = self.get_paginator(queryset, self.get_paginate_by(queryset)) for page in paginator.page_range: paths.append( ...
Override django-bakery's build logic to fake pagination.
347,850
def get(cls, tag_id_or_URI, label=None): semantictag = SemanticTag.by_id(tag_id_or_URI) if semantictag: return semantictag else: semantictag = SemanticTag.by_URI(tag_id_or_URI) return semantictag
Return the tag with the given id or URI, or None. :param tag_id_or_name: the id or name of the tag to return :type tag_id_or_name: string :returns: the tag object with the given id or name, or None if there is no tag with that id or name :rtype: ckan.model.tag.Tag
347,851
def virtual_interface_list(provider, names, **kwargs): salt-master client = _get_client() return client.extra_action(provider=provider, names=names, action=, **kwargs)
List virtual interfaces on a server CLI Example: .. code-block:: bash salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
347,852
def decode_name(s): return re.sub(r, lambda x: chr(int(x.group(1))), s)
Decode names in ModelSEED files
347,853
def metaprop(name: str, doc: str, readonly=False): def get(self): return self.meta[name] get.__doc__ = "Get %s%s." % (doc, " (readonly)" if readonly else "") if not readonly: def set(self, value): self.meta[name] = value set.__doc__ =...
Temporary property builder.
347,854
def longest_dimension_first(vector, start=(0, 0), width=None, height=None): x, y = start out = [] for dimension, magnitude in sorted(enumerate(vector), key=(lambda x: abs(x[1]) + random.random()), ...
List the (x, y) steps on a longest-dimension first route. Note that when multiple dimensions are the same magnitude, one will be chosen at random with uniform probability. Parameters ---------- vector : (x, y, z) The vector which the path should cover. start : (x, y) The coordi...
347,855
def add_next_hop(self, access_or_prefix_list, rank=None): self.conditions.append(dict( next_hop_ref=access_or_prefix_list.href, type=, rank=rank))
Add a next hop condition. Next hop elements must be of type IPAccessList or IPPrefixList. :raises ElementNotFound: If element specified does not exist
347,856
def _is_modified(self, filepath): if self._is_new(filepath): return False mtime = self._get_modified_time(filepath) return self._watched_files[filepath] < mtime
Returns True if the file has been modified since last seen. Will return False if the file has not been seen before.
347,857
def add_nodes(self, root_id, current_node, indent=1): if not current_node.children: return config.LOGGER.info("({count} of {total} uploaded) {indent}Processing {title} ({kind})".format( count=self.node_count_dict[], total=self.node_count_dict[], ...
add_nodes: adds processed nodes to tree Args: root_id (str): id of parent node on Kolibri Studio current_node (Node): node to publish children indent (int): level of indentation for printing Returns: link to uploadedchannel
347,858
def hideEvent(self, event): super(CompletionWidget, self).hideEvent(event) self._text_edit.cursorPositionChanged.disconnect(self._update_current) self._text_edit.removeEventFilter(self)
Reimplemented to disconnect signal handlers and event filter.
347,859
def download_and_extract(uri, name, path): if not os.path.exists(path): os.makedirs(path) if not os.listdir(path): with tmpdir() as tmp: if uri.startswith(): dst = os.path.join(tmp, ) s3_download(uri, dst) with tarfile.open(name...
Download, prepare and install a compressed tar file from S3 or local directory as an entry point. SageMaker Python SDK saves the user provided entry points as compressed tar files in S3 Args: name (str): name of the entry point. uri (str): the location of the entry point. path (bool): ...
347,860
def install(name, provider, genome_dir, localname, mask, regex, match, annotation): genomepy.install_genome( name, provider, genome_dir=genome_dir, localname=localname, mask=mask, regex=regex, invert_match=not(match), annotation=annotation)
Install genome NAME from provider PROVIDER in directory GENOME_DIR.
347,861
def get_fd_from_final_mass_spin(template=None, distance=None, **kwargs): input_params = props(template, mass_spin_required_args, **kwargs) final_mass = input_params[] final_spin = input_params[] lmns = input_params[] for lmn in lmns: if int(lmn[2]) == 0: raise ValueEr...
Return frequency domain ringdown with all the modes specified. Parameters ---------- template: object An object that has attached properties. This can be used to substitute for keyword arguments. A common example would be a row in an xml table. distance : {None, float}, optional ...
347,862
def sort_bamfile(job, bamfile, sample_type, univ_options, samtools_options): work_dir = os.getcwd() in_bamfile = .join([sample_type, ]) out_bamfile = .join([sample_type, ]) input_files = { in_bamfile: bamfile} input_files = get_files_from_filestore(job, input_files, work_dir, docker=Tru...
Sort `bamfile` using samtools :param toil.fileStore.FileID bamfile: fsID for the bam file :param str sample_type: Description of the sample to inject into the filename :param dict univ_options: Dict of universal options used by almost all tools :param dict samtools_options: Options specific to samtools...
347,863
def ext(external, pillar=None): ext_pillargitmybranch https://github.com/myuser/myrepoenvbaseext_pillargitmybranch https://github.com/myuser/myrepoenvbasegitmybranch https://github.com/myuser/myrepoenvbase*{libvirt: _}*gitmaster https://github.com/myuser/myrepo*gitmybranch https://github.com/myuser/myrepoenvbase ...
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0 The supported ext_pillar types are now tunable using the :conf_master:`on_demand_ext_pillar` config option. Earlier releases used a hard-coded default. Generate the pillar and apply an explicit external pillar external A single e...
347,864
def check_values(self): error_color = no_error_color = self.error_batch_name = False self.error_report_parameter = False self.error_saa_result = False self.error_sza_result = False self.error_p_result = False self.error_wavelength_result = Fa...
This function checks if there is no problem about values given. If there is a problem with a or some values, their label's color is changed to red, and call a function to display an error message. If there is no problem, their label, if it is necessary, is changed to grey (default color).
347,865
def get_favorite_radio_shows(self, *args, **kwargs): args = tuple([] + list(args)) return self.get_music_library_information(*args, **kwargs)
Convenience method for `get_music_library_information` with ``search_type='radio_stations'``. For details of other arguments, see `that method <#soco.music_library.MusicLibrary.get_music_library_information>`_.
347,866
def full_name(self): import ibis.expr.operations as ops return ops.DayOfWeekName(self.op().arg).to_expr()
Get the name of the day of the week. Returns ------- StringValue The name of the day of the week
347,867
def set_bucket_name(self, bucket_name): is_valid_bucket_name(bucket_name) self.policies.append((, , bucket_name)) self.form_data[] = bucket_name self.bucket_name = bucket_name
Set bucket name policy condition. :param bucket_name: set bucket name.
347,868
def get(self, name): if not name in self._vars: raise AttributeError setting = self._vars[name] return setting.value
get a setting
347,869
def update_roles(self, roles=): if not self.object_id: return False url = self.build_url(self._endpoints.get().format( driveitem_id=self.driveitem_id, id=self.object_id)) if roles in {, }: data = {: []} elif roles == {, }: data =...
Updates the roles of this permission :return: Success / Failure :rtype: bool
347,870
def iter_call(self, name, *args, **kwargs): return self.client.iter_call(self.name, name, *args, **kwargs)
A generator that deals with paginating through results. :param method: the method to call on the service :param integer chunk: result size for each API call :param \\*args: same optional arguments that ``Service.call`` takes :param \\*\\*kwargs: same optional keyword arguments that ...
347,871
def eth_getUncleCountByBlockNumber(self, block=BLOCK_TAG_LATEST): block = validate_block(block) response = yield from self.rpc_call(, [block]) if response: return hex_to_dec(response) return response
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getunclecountbyblocknumber :param block: Block tag or number (optional) :type block: int or BLOCK_TAGS :return: count :rtype: int
347,872
def iter_sites(sites=None, site=None, renderer=None, setter=None, no_secure=False, verbose=None): if verbose is None: verbose = get_verbose() hostname = get_current_hostname() target_sites = env.available_sites_by_host.get(hostname, None) if sites is None: site = site or env.SITE...
Iterates over sites, safely setting environment variables for each site.
347,873
def add_mag_drifts(inst): inst[] = {:inst[] * inst[] + inst[]*inst[] + inst[]*inst[], :, :, :( ...
Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates along with pre-calculated unit vectors for magnetic coordinates. Note ---- Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with unit vectors labels 'unit_zonal_*', 'unit_fa_*', and 'unit_mer_*', ...
347,874
def calc_2dsplinecoeffs_c(array2d): out= copy.copy(array2d) out= numpy.require(out,dtype=numpy.float64,requirements=[,]) ndarrayFlags= (,) interppotential_calc_2dsplinecoeffs= _lib.samples_to_coefficients interppotential_calc_2dsplinecoeffs.argtypes= [ndpointer(dtype=numpy.float64,fl...
NAME: calc_2dsplinecoeffs_c PURPOSE: Use C to calculate spline coefficients for a 2D array INPUT: array2d OUTPUT: new array with spline coeffs HISTORY: 2013-01-24 - Written - Bovy (IAS)
347,875
def remove(self, source_id, auth_ids): params = {: source_id, : auth_ids} return self.request.post(, params)
Remove one or more sets of authorization credentials from a Managed Source Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceauthremove :param source_id: target Source ID :type source_id: str :param resources: An array of the authorization...
347,876
def geometry_point(lat, lon, elev): logger_excel.info("enter geometry_point") coordinates = [] point_dict = OrderedDict() for idx, val in enumerate(lat): try: coordinates.append(lon[idx]) coordinates.append(lat[idx]) except IndexError as e: print(...
GeoJSON point. Latitude and Longitude only have one value each :param list lat: Latitude values :param list lon: Longitude values :param float elev: Elevation value :return dict:
347,877
def deallocate(self, buf): with self._lock: buf.truncate(0) self._free.append(buf) if self._waiters: self._waiters[0].notify()
Return buffers to the pool. If they are of the poolable size add them to the free list, otherwise just mark the memory as free. Arguments: buffer_ (io.BytesIO): The buffer to return
347,878
def get_version(*args): contents = get_contents(*args) metadata = dict(re.findall("]([^\, contents)) return metadata[]
Extract the version number from a Python module.
347,879
def logical_or(self, other): return self.operation(other, lambda x, y: int(x or y))
logical_or(t) = self(t) or other(t).
347,880
def hscan(self, name, key_start, key_end, limit=10): limit = get_positive_integer(, limit) return self.execute_command(, name, key_start, key_end, limit)
Return a dict mapping key/value in the top ``limit`` keys between ``key_start`` and ``key_end`` within hash ``name`` in ascending order Similiar with **Redis.HSCAN** .. note:: The range is (``key_start``, ``key_end``]. The ``key_start`` isn't in the range, but ``key_end`` is. ...
347,881
def extract(self, item, list_article_candidate): list_publish_date = [] for article_candidate in list_article_candidate: if article_candidate.publish_date != None: list_publish_date.append((article_candidate.publish_date, article_candidate.extractor)) ...
Compares the extracted publish dates. :param item: The corresponding NewscrawlerItem :param list_article_candidate: A list, the list of ArticleCandidate-Objects which have been extracted :return: A string, the most likely publish date
347,882
def get_authorization_query_session(self): if not self.supports_authorization_query(): raise errors.Unimplemented() return sessions.AuthorizationQuerySession(runtime=self._runtime)
Gets the ``OsidSession`` associated with the authorization query service. return: (osid.authorization.AuthorizationQuerySession) - an ``AuthorizationQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authorization_query()`` is ...
347,883
def get_users(self, *args, **kwargs): arguments, _ = self.argparser.parse_known_args() if self.is_pipe and self.use_pipe: return self.get_pipe(self.object_type) elif arguments.tags or arguments.group or arguments.search or arguments.domain: return self.argument_s...
Retrieves the users from elastic.
347,884
def get_ptn(unit): ptn = 0 match_re = re.findall(chinese, unit) if match_re: string = .join(match_re) ptn = len(string) return int(ptn)
获取文本行的中文字符的个数 Keyword arguments: unit -- 文本行 Return: ptn -- 纯文本数
347,885
def headerData(self, section, orientation, role): if role == Qt.TextAlignmentRole: if orientation == Qt.Horizontal: return Qt.AlignCenter | Qt.AlignBottom else: return Qt.AlignRight | Qt.AlignVCenter if role != Qt.DisplayRole and ro...
Get the information to put in the header.
347,886
def get_arguments(self, **include): d = dict(self._kwargs) for k in include: if not include[k] and k in d: d.pop(k) return d
return a shallow copy of self._kwargs passing {key}=False will pop the {key} from the dict e.g. get_arguments(inputs=False) returns all keywords except inputs
347,887
def _get_left(cls): if cls._traverse: return [cls.fromSymbol] if len(cls.rules) > 1: raise CantCreateSingleRuleException(cls) return cls.rules[0][0]
Get left part of the rule. :param cls: Rule for which return the left side. :return: Symbols on the left side of the array. :raise RuleNotDefinedException: If the rule is not defined. :raise CantCreateSingleRuleException: If the rule consists of more rules. :raise NotASingleSymbo...
347,888
def article2draft(article): draft = Draft(article._content, article.metadata, article.settings, article.source_path, article._context) draft.status = return draft
Transform an Article to Draft
347,889
def vcpkg_dir(): for p in ["vcpkg-exported", "C:/tools/vcpkg", "C:/open/vcpkg"]: if os.path.isdir(p): return os.path.realpath(p) raise Exception("cannot find vcpkg")
Figure out where vcpkg is installed. vcpkg-exported is populated in some flavors of FB internal builds. C:/tools/vcpkg is the appveyor location. C:/open/vcpkg is my local location.
347,890
def deserialize(cls, v, bind_client=None): if v is None: return None az_classes = {: HeartrateActivityZone, : PowerActivityZone, : PaceActivityZone} try: clazz = az_classes[v[]] except KeyError: rais...
Creates a new object based on serialized (dict) struct.
347,891
def calculate_tx_fee(tx_cost_constants, num_inputs, num_outputs): tx_size = calculate_raw_tx_size_with_op_return(num_inputs, num_outputs) tx_fee = tx_cost_constants.satoshi_per_byte * tx_size return max(tx_fee, tx_cost_constants.get_recommended_fee_coin())
The course grained (hard-coded value) of something like 0.0001 BTC works great for standard transactions (one input, one output). However, it will cause a lag in more complex or large transactions. So we calculate the raw tx fee, then take the max of the default fee and the refined cost to ensure prompt process...
347,892
def extendSeed(self, seedKmer, endSeeds): if self.foundKmers.has_key(seedKmer): return pathK = self.settingsDict.get(, len(seedKmer)) countK = self.settingsDict.get(, pathK) isMerged = self.settingsDict.get(, False) trackPairs = self.setting...
This function is intended to be an interactive technique for constructing transcripts, probably to be released in a future version of msbwt @param bwtFN - the filename of the BWT to load @param seedKmer - the seed sequence to use for construction @param threshold - minimum number for a p...
347,893
def get_interface_detail_output_interface_line_protocol_state_info(self, **kwargs): config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output") interface = ET...
Auto Generated Code
347,894
async def connect(self, conn_id, connection_string): self._logger.info("Inside connect, conn_id=%d, conn_string=%s", conn_id, connection_string) try: self._setup_connection(conn_id, connection_string) resp = await self._execute(self._adapter.connect_sync, conn_id, con...
Connect to a device. See :meth:`AbstractDeviceAdapter.connect`.
347,895
def emit(self, record): failures = 0 while failures < 3: try: self.stream_emit(record, record.name) break except: failures += 1 else: traceback.print_stack() print("Error writing to file?") self.close()
Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit.
347,896
def complete_transaction(cleanup_only=False, recursive=False, max_attempts=3): *** return _complete_transaction(cleanup_only, recursive, max_attempts, 1, [])
.. versionadded:: Fluorine Execute ``yum-complete-transaction``, which is provided by the ``yum-utils`` package. cleanup_only Specify if the ``--cleanup-only`` option should be supplied. recursive Specify if ``yum-complete-transaction`` should be called recursively (it only comple...
347,897
def format_align(sign, body, spec): padding = spec[] * (spec[] - len(sign) - len(body)) align = spec[] if align == : result = sign + body + padding elif align == : result = padding + sign + body elif align == : result = sign + padding + body elif align == : h...
Given an unpadded, non-aligned numeric string 'body' and sign string 'sign', add padding and alignment conforming to the given format specifier dictionary 'spec' (as produced by parse_format_specifier).
347,898
def POST(self, *args, **kwargs): Content-type: application/json{"foo": "Foo!", "bar": "Bar!"}s Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {: , : { ...
Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhos...
347,899
def _savepath(self, filename): (basename, ext) = os.path.splitext(filename) basename = basename if (ext in self.extensions) else filename ext = ext if (ext in self.extensions) else self.extensions[0] savepath = os.path.abspath(os.path.join(self.directory, ...
Returns the full path for saving the file, adding an extension and making the filename unique as necessary.