Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
369,200
def _prepare_outputs(self, data_out, outputs): compress = ROOTModule.ROOT.CompressionSettings(ROOTModule.ROOT.kZLIB, 1) if isinstance(data_out, (str, unicode)): self.file_emulation = True outputs.append(ROOTModule.TFile.Open(data_out, , , compress)) elif...
Open a ROOT file with option 'RECREATE' to create a new file (the file will be overwritten if it already exists), and using the ZLIB compression algorithm (with compression level 1) for better compatibility with older ROOT versions (see https://root.cern.ch/doc/v614/release-notes.html#important-...
369,201
def _get_trendline(self,date0=None,date1=None,on=None,kind=,to_strfmt=,from_strfmt=,**kwargs): ann_values=copy.deepcopy(get_annotation_kwargs()) ann_values.extend([,]) ann_kwargs=utils.check_kwargs(kwargs,ann_values,{},clean_origin=True) def position(d0,d1): return d0+(d1-d0)/2 date0=kwargs.pop(,date0)...
Returns a trendline (line), support or resistance Parameters: date0 : string Trendline starting date date1 : string Trendline end date on : string Indicate the data series in which the trendline should be based. 'close' 'high' 'low' 'open' kind : string Def...
369,202
def remove_known_host(host, application_name, user=None): log( % host) cmd = [, , known_hosts(application_name, user), , host] subprocess.check_call(cmd)
Remove the entry in known_hosts for host. :param host: hostname to lookup in file. :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str
369,203
def iter_elements(element_function, parent_to_parse, **kwargs): parent = get_element(parent_to_parse) if not hasattr(element_function, ): return parent for child in ([] if parent is None else parent): element_function(child, **kwargs) return parent
Applies element_function to each of the sub-elements in parent_to_parse. The passed in function must take at least one element, and an optional list of kwargs which are relevant to each of the elements in the list: def elem_func(each_elem, **kwargs)
369,204
def top(self): try: response = self.d.top(self.container_id, ps_args=ps_args) except docker.errors.APIError as ex: logger.warning("error getting processes: %r", ex) return [] logger.debug(json.dumps(response, indent=2)) retur...
list of processes in a running container :return: None or list of dicts
369,205
def after_reinstate(analysis_request): do_action_to_descendants(analysis_request, "reinstate") do_action_to_analyses(analysis_request, "reinstate") prev_status = get_prev_status_from_history(analysis_request, "cancelled") changeWorkflowState(analysis_request, AR_WORKFLOW_ID, prev_status, ...
Method triggered after a 'reinstate' transition for the Analysis Request passed in is performed. Sets its status to the last status before it was cancelled. Reinstates the descendant partitions and all the analyses associated to the analysis request as well.
369,206
def _additive_estimate(events, timeline, _additive_f, _additive_var, reverse): if reverse: events = events.sort_index(ascending=False) at_risk = events["entrance"].sum() - events["removed"].cumsum().shift(1).fillna(0) deaths = events["observed"] estimate_ = np.cumsum(_additive...
Called to compute the Kaplan Meier and Nelson-Aalen estimates.
369,207
def adjust(self): if self._fro is None and self._to is not None: self._fro = dict( [(value.lower(), key) for key, value in self._to.items()]) if self._to is None and self._fro is not None: self._to = dict( [(value.lower(), key) for key, v...
If one of the transformations is not defined it is expected to be the mirror image of the other.
369,208
def get(self, callback): derived_path = self.context.request.url logger.debug(.format( log_prefix=LOG_PREFIX, path=derived_path)) callback(self.storage.get(self.result_key_for(derived_path)))
Gets an item based on the path.
369,209
def get_ordering(self): if self.__ordering is None: self.__ordering = [] for cluster in self.__clusters: for index_object in cluster: optics_object = self.__optics_objects[index_object] if optics_...
! @brief Returns clustering ordering information about the input data set. @details Clustering ordering of data-set contains the information about the internal clustering structure in line with connectivity radius. @return (ordering_analyser) Analyser of clustering ordering. ...
369,210
def process_remove_action(processors, action, argument): for processor in processors: processor(action, argument) db.session.commit()
Process action removals.
369,211
def layer_uri(self, layer_name): for layer in self._vector_layers(): if layer == layer_name: uri = .format( self.uri.absoluteFilePath(), layer_name) return uri else: for layer in self._raster_layers(): i...
Get layer URI. For a vector layer : /path/to/the/geopackage.gpkg|layername=my_vector_layer For a raster : GPKG:/path/to/the/geopackage.gpkg:my_raster_layer :param layer_name: The name of the layer to fetch. :type layer_name: str :return: The URI to the layer. ...
369,212
def _get_collection(self, collection_uri, request_headers=None): status, headers, thecollection = self._rest_get(collection_uri) if status != 200: msg = self._get_extended_error(thecollection) raise exception.IloError(msg) while status < 300: ...
Generator function that returns collection members.
369,213
def execute_sql_statement(sql_statement, query, user_name, session, cursor): database = query.database db_engine_spec = database.db_engine_spec parsed_query = ParsedQuery(sql_statement) sql = parsed_query.stripped() SQL_MAX_ROWS = app.config.get() if not parsed_query.is_readonly() and not ...
Executes a single SQL statement
369,214
def parse_library(lib_files): tracks, playlists = lib_files lib = MusicLibrary() lib_length = len(tracks) i = 0 writer = lib.ix.writer() previous_procent_done_str = "" for f in tracks: track_info = TrackInfo(f) lib.add_track_internal(track_info, writer) current_...
Analizuje pliki podane w liście lib_files Zwraca instancję MusicLibrary
369,215
def retrieve(self, filter_expression=None, order_expression=None, slice_key=None): ents = iter(self.__entities) if not filter_expression is None: ents = filter_expression(ents) if not order_expression is None: ents = ite...
Retrieve entities from this cache, possibly after filtering, ordering and slicing.
369,216
def setup(self, hunt_id, reason, grr_server_url, grr_username, grr_password, approvers=None, verify=True): super(GRRHuntDownloader, self).setup( reason, grr_server_url, grr_username, grr_password, approvers=approvers, verify=verify) self.hunt_id = hunt_id...
Initializes a GRR Hunt file collector. Args: hunt_id: Hunt ID to download results from. reason: justification for GRR access. grr_server_url: GRR server URL. grr_username: GRR username. grr_password: GRR password. approvers: comma-separated list of GRR approval recipients. ...
369,217
def get_feature(self, croplayer_id, cropfeature_id): target_url = self.client.get_url(, , , {: croplayer_id, : cropfeature_id}) return self.client.get_manager(CropFeature)._get(target_url)
Gets a crop feature :param int croplayer_id: ID of a cropping layer :param int cropfeature_id: ID of a cropping feature :rtype: CropFeature
369,218
def Network_emulateNetworkConditions(self, offline, latency, downloadThroughput, uploadThroughput, **kwargs): assert isinstance(offline, (bool,) ), "Argument must be of type bool. Received type: " % type( offline) assert isinstance(latency, (float, int) ), "Argument must be of type float...
Function path: Network.emulateNetworkConditions Domain: Network Method name: emulateNetworkConditions Parameters: Required arguments: 'offline' (type: boolean) -> True to emulate internet disconnection. 'latency' (type: number) -> Minimum latency from request sent to response headers received ...
369,219
def set_relay_on(self): if not self.get_relay_state(): try: request = requests.get( .format(self.resource), params={: }, timeout=self.timeout) if request.status_code == 200: self.data[] = True ...
Turn the relay on.
369,220
def dispatch_shell(self, stream, msg): if self.control_stream: self.control_stream.flush() idents,msg = self.session.feed_identities(msg, copy=False) try: msg = self.session.unserialize(msg, content=True, copy=False) except: ...
dispatch shell requests
369,221
def analysis_question_extractor(impact_report, component_metadata): multi_exposure = impact_report.multi_exposure_impact_function if multi_exposure: return multi_exposure_analysis_question_extractor( impact_report, component_metadata) context = {} extra_args = component_metadat...
Extracting analysis question from the impact layer. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :param component_metadata: the component metadata. Used to obtain informa...
369,222
def searchForMessages(self, query, offset=0, limit=5, thread_id=None): message_ids = self.searchForMessageIDs( query, offset=offset, limit=limit, thread_id=thread_id ) for mid in message_ids: yield self.fetchMessageInfo(mid, thread_id)
Find and get :class:`models.Message` objects by query .. warning:: This method sends request for every found message ID. :param query: Text to search for :param offset: Number of messages to skip :param limit: Max. number of messages to retrieve :param thread_id: Us...
369,223
def ws050(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( .format(value)) self._ws050 = value
Corresponds to IDD Field `ws050` Wind speed corresponding 5.0% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `ws050` Unit: m/s if `value` is None it will not be checked against the specification and is assu...
369,224
def get_role_id(self, role_name, mount_point=): url = .format(mount_point, role_name) return self._adapter.get(url).json()[][]
GET /auth/<mount_point>/role/<role name>/role-id :param role_name: :type role_name: :param mount_point: :type mount_point: :return: :rtype:
369,225
def interface_type(self, ift): if not isinstance(ift, str): ift = str(ift) self._attributes["if"] = ift
Set the CoRE Link Format if attribute of the resource. :param ift: the CoRE Link Format if attribute
369,226
def remove_lines(lines, remove=(, )): if not remove: return lines[:] out = [] for l in lines: if l.startswith(remove): continue out.append(l) return out
Removes existing [back to top] links and <a id> tags.
369,227
def _help(): statement = % (shelp, phelp % .join(cntx_.keys())) print statement.strip()
Display both SQLAlchemy and Python help statements
369,228
def define_property(obj, name, fget=None, fset=None, fdel=None, doc=None): if hasattr(fget, ): prop = fget else: prop = property(fget, fset, fdel, doc) cls = obj.__class__ obj.__class__ = type(cls.__name__, (cls, ), { : cls.__doc__, name: prop })
Defines a @property dynamically for an instance rather than a class.
369,229
def sign(pkey, data, digest): data = _text_to_bytes_and_warn("data", data) digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest)) if digest_obj == _ffi.NULL: raise ValueError("No such digest method") md_ctx = _lib.Cryptography_EVP_MD_CTX_new() md_ctx = _ffi.gc(md_ctx, _lib.Crypt...
Sign a data string using the given key and message digest. :param pkey: PKey to sign with :param data: data to be signed :param digest: message digest to use :return: signature .. versionadded:: 0.11
369,230
def analyse(self, traj, network, current_subrun, subrun_list, network_dict): if len(subrun_list)==0: spikes_e = traj.results.monitors.spikes_e time_window = traj.parameters.analysis.statistics.time_window start_time = traj.parameters.simulation.durations.in...
Calculates average Fano Factor of a network. :param traj: Trajectory container Expects: `results.monitors.spikes_e`: Data from SpikeMonitor for excitatory neurons Adds: `results.statistics.mean_fano_factor`: Average Fano Factor :param ne...
369,231
def add_constraints(self): if self._constraints: foreign_key = getattr(self._parent, self._foreign_key, None) if foreign_key is None: self._query = None else: table = self._related.get_table() self._query.where( ...
Set the base constraints on the relation query. :rtype: None
369,232
def multiplySeries(requestContext, *seriesLists): if not seriesLists or not any(seriesLists): return [] seriesList, start, end, step = normalize(seriesLists) if len(seriesList) == 1: return seriesList name = "multiplySeries(%s)" % .join([s.name for s in seriesList]) product =...
Takes two or more series and multiplies their points. A constant may not be used. To multiply by a constant, use the scale() function. Example:: &target=multiplySeries(Series.dividends,Series.divisors)
369,233
def update_cluster(cluster_dict, datacenter=None, cluster=None, service_instance=None): ** schema = ESXClusterConfigSchema.serialize() try: jsonschema.validate(cluster_dict, schema) except jsonschema.exceptions.ValidationError as exc: raise InvalidConfigError(exc)...
Updates a cluster. config_dict Dictionary with the config values of the new cluster. datacenter Name of datacenter containing the cluster. Ignored if already contained by proxy details. Default value is None. cluster Name of cluster. Ignored if already cont...
369,234
def from_payload(self, payload): self.session_id = payload[0]*256 + payload[1] self.status = CommandSendConfirmationStatus(payload[2])
Init frame from binary data.
369,235
def stop(self): self.__active = False self.__timer.stop() self.__thread.join()
停止引擎
369,236
def shell(cmd, output=None, mode=, cwd=None, shell=False): if not output: output = os.devnull else: folder = os.path.dirname(output) if folder and not os.path.isdir(folder): os.makedirs(folder) if not isinstance(cmd, (list, tuple)) and not shell: cmd = shlex...
Execute a shell command. You can add a shell command:: server.watch( 'style.less', shell('lessc style.less', output='style.css') ) :param cmd: a shell command, string or list :param output: output stdout to the given file :param mode: only works with output, mode ``w`` mea...
369,237
def _do_setup_step(self, play): host_list = self._list_available_hosts(play.hosts) if play.gather_facts is False: return {} elif play.gather_facts is None: host_list = [h for h in host_list if h not in self.SETUP_CACHE or not in self.SETUP_CACHE[h]] ...
get facts from the remote system
369,238
def bilateral2(data, fSize, sigma_p, sigma_x = 10.): dtype = data.dtype.type dtypes_kernels = {np.float32:"bilat2_float", np.uint16:"bilat2_short"} if not dtype in dtypes_kernels: logger.info("data type %s not supported yet (%s), casting to float:"%(dtype,list(dtyp...
bilateral filter
369,239
def tunnel(self, local_port, remote_port): r = self.local_renderer r.env.tunnel_local_port = local_port r.env.tunnel_remote_port = remote_port r.local()
Creates an SSH tunnel.
369,240
def _encrypt_private(self, ret, dictkey, target): pubfn = os.path.join(self.opts[], , target) key = salt.crypt.Crypticle.generate_key_string() pcrypt = salt.crypt.Crypticle( self.opts, key) ...
The server equivalent of ReqChannel.crypted_transfer_decode_dictentry
369,241
def fit_two_gaussian(spectra, f_ppm, lb=3.6, ub=3.9): idx = ut.make_idx(f_ppm, lb, ub) n_points = idx.stop - idx.start n_params = 8 fit_func = ut.two_gaussian bounds = [(lb,ub), (lb,ub), (0,None), (0,None), (0,None), (0,Non...
Fit a gaussian function to the difference spectra This is useful for estimation of the Glx peak, which tends to have two peaks. Parameters ---------- spectra : array of shape (n_transients, n_points) Typically the difference of the on/off spectra in each transient. f_ppm : array lb, ub :...
369,242
def set_keyspace(self, keyspace): self.keyspace = keyspace dfrds = [] for p in self._protos: dfrds.append(p.submitRequest(ManagedThriftRequest( , keyspace))) return defer.gatherResults(dfrds)
switch all connections to another keyspace
369,243
def search_all_payments(payment_status=None, page_size=20, start_cursor=None, offset=0, use_cache=True, cache_begin=True, relations=None): if payment_status: return PaymentsByStatusSearch(payment_status, page_size, start_cursor, offset, use_cache, ...
Returns a command to search all payments ordered by creation desc @param payment_status: The payment status. If None is going to return results independent from status @param page_size: number of payments per page @param start_cursor: cursor to continue the search @param offset: offset number of payment...
369,244
def return_ok(self, cookie, request): _debug(" - checking cookie %s=%s", cookie.name, cookie.value) for n in "version", "verifiability", "secure", "expires", "port", "domain": fn_name = "return_ok_"+n fn = getattr(self, fn_name) if not fn(c...
If you override .return_ok(), be sure to call this method. If it returns false, so should your subclass (assuming your subclass wants to be more strict about which cookies to return).
369,245
def _R2deriv(self,R,z,phi=0.,t=0.): if True: if isinstance(R,nu.ndarray): if not isinstance(z,nu.ndarray): z= nu.ones_like(R)*z out= nu.array([self._R2deriv(rr,zz) for rr,zz in zip(R,z)]) return out if R > 16.*self._hr or R > 6.: r...
NAME: R2deriv PURPOSE: evaluate R2 derivative INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: -d K_R (R,z) d R HISTORY: 2012-12-27 - Written - Bovy (IAS...
369,246
def write(self, image, dest_fobj, quality=95, format=None): if isinstance(format, basestring) and format.lower() == : format = raw_data = self._get_raw_data(image, format, quality) dest_fobj.write(raw_data)
Wrapper for ``_write`` :param Image image: This is your engine's ``Image`` object. For PIL it's PIL.Image. :keyword int quality: A quality level as a percent. The lower, the higher the compression, the worse the artifacts. :keyword str format: The format to save to. If o...
369,247
def get_client(self): context = self.context parent = api.get_parent(context) if context.portal_type == "Client": return context elif parent.portal_type == "Client": return parent elif context.portal_type == "Batch": return context.get...
Returns the Client
369,248
def bloquear_sat(retorno): resposta = analisar_retorno(forcar_unicode(retorno), funcao=) if resposta.EEEEE not in (,): raise ExcecaoRespostaSAT(resposta) return resposta
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.bloquear_sat`.
369,249
def get_relative_to_remote(self): s = self.git("status", "--short", "-b")[0] r = re.compile("\[([^\]]+)\]") toks = r.findall(s) if toks: try: s2 = toks[-1] adj, n = s2.split() assert(adj in ("ahead", "behind")) ...
Return the number of commits we are relative to the remote. Negative is behind, positive in front, zero means we are matched to remote.
369,250
def potential_from_grid(self, grid): potential_grid = quad_grid(self.potential_func, 0.0, 1.0, grid, args=(self.axis_ratio, self.slope, self.core_radius))[0] return self.einstein_radius_rescaled * self.axis_ratio * potential_grid
Calculate the potential at a given set of arc-second gridded coordinates. Parameters ---------- grid : grids.RegularGrid The grid of (y,x) arc-second coordinates the deflection angles are computed on.
369,251
def load_atomic(self, ptr, ordering, align, name=): if not isinstance(ptr.type, types.PointerType): raise TypeError("cannot load from value of type %s (%r): not a pointer" % (ptr.type, str(ptr))) ld = instructions.LoadAtomicInstr(self.block, ptr, ordering...
Load value from pointer, with optional guaranteed alignment: name = *ptr
369,252
def add(self, varname, result, pointer=None): self.result[varname] = result setattr(self, varname, result) if pointer is not None: self._finalizers[varname] = pointer
Adds the specified python-typed result and an optional Ftype pointer to use when cleaning up this object. :arg result: a python-typed representation of the result. :arg pointer: an instance of Ftype with pointer information for deallocating the c-pointer.
369,253
def logout(self): sess = cherrypy.session username = sess.get(SESSION_KEY, None) sess[SESSION_KEY] = None if username: cherrypy.request.login = None cherrypy.log.error( msg="user logout" % {: username}, severity=logging.INFO ...
logout page
369,254
def geom_reflect(g, nv): import numpy as np g = make_nd_vec(g, nd=None, t=np.float64, norm=False) refl_g = np.dot(mtx_refl(nv, reps=(g.shape[0] // 3)), g) \ .reshape((g.shape[0],1)) return refl_g
Reflection symmetry operation. nv is normal vector to reflection plane g is assumed already translated to center of mass @ origin .. todo:: Complete geom_reflect docstring
369,255
def unpack_layer(plane): size = point.Point.build(plane.size) if size == (0, 0): data = data[:size.x * size.y] return data.reshape(size.y, size.x)
Return a correctly shaped numpy array given the feature layer bytes.
369,256
def do_cat(self, path): path = path[0] tmp_file_path = self.TMP_PATH + if not os.path.exists(self.TMP_PATH): os.makedirs(self.TMP_PATH) f = self.n.downloadFile(self.current_path + path, tmp_file_path) f = open(tmp_file_path, ) self.stdout.write(f....
display the contents of a file
369,257
def cancel_job(self, job_resource_name: str): self.service.projects().programs().jobs().cancel( name=job_resource_name, body={}).execute()
Cancels the given job. See also the cancel method on EngineJob. Params: job_resource_name: A string of the form `projects/project_id/programs/program_id/jobs/job_id`.
369,258
def compile_string(self, mof, ns, filename=None): lexer = self.lexer.clone() lexer.parser = self.parser try: oldfile = self.parser.file except AttributeError: oldfile = None self.parser.file = filename try: oldmof = self.parse...
Compile a string of MOF statements into a namespace of the associated CIM repository. Parameters: mof (:term:`string`): The string of MOF statements to be compiled. ns (:term:`string`): The name of the CIM namespace in the associated CIM repository ...
369,259
def p_initial(self, p): p[0] = Initial(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
initial : INITIAL initial_statement
369,260
def create_exception_by_name( name, detailCode=, description=, traceInformation=None, identifier=None, nodeId=None, ): try: dataone_exception = globals()[name] except LookupError: dataone_exception = ServiceFailure return dataone_exception( detailCode, de...
Create a DataONEException based object by name. Args: name: str The type name of a DataONE Exception. E.g. NotFound. If an unknown type name is used, it is automatically set to ServiceFailure. As the XML Schema for DataONE Exceptions does not restrict the type names, this may...
369,261
def tremolo(self, freq, depth=40): self.command.append("tremolo") self.command.append(freq) self.command.append(depth) return self
tremolo takes two parameters: frequency and depth (max 100)
369,262
def apply_color_scheme(self, color_scheme): self.stdout_color = color_scheme.formats[].foreground().color() self.stdin_color = color_scheme.formats[].foreground().color() self.app_msg_color = color_scheme.formats[ ].foreground().color() self.background_color = color_...
Apply a pygments color scheme to the console. As there is not a 1 to 1 mapping between color scheme formats and console formats, we decided to make the following mapping (it usually looks good for most of the available pygments styles): - stdout_color = normal color - s...
369,263
def orient_averaged_adaptive(tm): S = np.zeros((2,2), dtype=complex) Z = np.zeros((4,4)) def Sfunc(beta, alpha, i, j, real): (S_ang, Z_ang) = tm.get_SZ_single(alpha=alpha, beta=beta) s = S_ang[i,j].real if real else S_ang[i,j].imag return s * tm.or_pdf(beta) in...
Compute the T-matrix using variable orientation scatterers. This method uses a very slow adaptive routine and should mainly be used for reference purposes. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMatrix (or descendant) instance Returns...
369,264
def datetime2literal_rnc(d: datetime.datetime, c: Optional[Dict]) -> str: dt = d.isoformat(" ") return _mysql.string_literal(dt, c)
Format a DateTime object as something MySQL will actually accept.
369,265
def _findlinestarts(code): lineno = code.co_firstlineno addr = 0 for byte_incr, line_incr in zip(code.co_lnotab[0::2], code.co_lnotab[1::2]): if byte_incr: yield addr, lineno addr += byte_incr lineno += line_incr yield addr...
Find the offsets in a byte code which are start of lines in the source Generate pairs offset,lineno as described in Python/compile.c This is a modified version of dis.findlinestarts, which allows multiplelinestarts with the same line number
369,266
def fit(self, X, y=None): X = check_array(X, accept_sparse=) kwargs = self.get_params() del kwargs[] kwargs.update(self.metric_params) self.labels_, self._cluster_hierarchy = robust_single_linkage( X, **kwargs) return self
Perform robust single linkage clustering from features or distance matrix. Parameters ---------- X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ array of shape (n_samples, n_samples) A feature array, or array of distances between sampl...
369,267
def bootstrap( self, controller_name, region=None, agent_version=None, auto_upgrade=False, bootstrap_constraints=None, bootstrap_series=None, config=None, constraints=None, credential=None, default_model=None, keep_broken=False, metadata_source=None, no_gui=Fa...
Initialize a cloud environment. :param str controller_name: Name of controller to create :param str region: Cloud region in which to bootstrap :param str agent_version: Version of tools to use for Juju agents :param bool auto_upgrade: Upgrade to latest path release tools on first ...
369,268
def add_variant(self, variant): LOG.debug("Upserting variant: {0}".format(variant.get())) update = self._get_update(variant) message = self.db.variant.update_one( {: variant[]}, update, upsert=True ) if message.modifi...
Add a variant to the variant collection If the variant exists we update the count else we insert a new variant object. Args: variant (dict): A variant dictionary
369,269
def get(self, query_path=None, return_type=list, preceding_depth=None, throw_null_return_error=False): function_type_lookup = {str: self._get_path_entry_from_string, list: self._get_path_entry_from_list} if query_path is None: return self._default_co...
Traverses the list of query paths to find the data requested :param query_path: (list(str), str), list of query path branches or query string Default behavior: returns list(str) of possible config headers :param return_type: (list, str, dict, OrderedDict), d...
369,270
def is_not_empty(value, **kwargs): try: value = validators.not_empty(value, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
Indicate whether ``value`` is empty. :param value: The value to evaluate. :returns: ``True`` if ``value`` is empty, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the...
369,271
def get_vault_form_for_create(self, vault_record_types): if self._catalog_session is not None: return self._catalog_session.get_catalog_form_for_create(catalog_record_types=vault_record_types) for arg in vault_record_types: if not isinstance(arg, ABCTyp...
Gets the vault form for creating new vaults. A new form should be requested for each create transaction. arg: vault_record_types (osid.type.Type[]): array of vault record types return: (osid.authorization.VaultForm) - the vault form raise: NullArgument - ``vault_rec...
369,272
def mean_by_panel(self, length): self._check_panel(length) func = lambda v: v.reshape(-1, length).mean(axis=0) newindex = arange(length) return self.map(func, index=newindex)
Compute the mean across fixed sized panels of each record. Splits each record into panels of size `length`, and then computes the mean across panels. Panel length must subdivide record exactly. Parameters ---------- length : int Fixed length with which to su...
369,273
def __collect_fields(self): form = FormData() form.add_field(self.__username_field, required=True, error=self.__username_error) form.add_field(self.__password_field, required=True, error=self.__password_error) form.parse() ...
Use field values from config.json and collect from request
369,274
def delete(self, robj, rw=None, r=None, w=None, dw=None, pr=None, pw=None, timeout=None): params = {: rw, : r, : w, : dw, : pr, : pw, : timeout} headers = {} bucket_type = self._get_bucket_type(robj.bucket.bucket_type) url = s...
Delete an object.
369,275
def _compute_childtab(self, lcptab): last_index = -1 stack = [0] n = len(lcptab) childtab_up = np.zeros(n, dtype=np.int) childtab_down = np.zeros(n, dtype=np.int) for i in xrange(n): while lcptab[i] < lcptab[stack[-1]]: last_index = ...
Computes the child 'up' and 'down' arrays in O(n) based on the LCP table. Abouelhoda et al. (2004).
369,276
def index_bams(job, config): job.fileStore.logToMaster( + config.uuid) disk = if config.ci_test else config.normal_bai = job.addChildJobFn(run_samtools_index, config.normal_bam, cores=1, disk=disk).rv() config.tumor_bai = job.addChildJobFn(run_samtools_index, config.tumor_bam, cores=1, disk=disk)...
Convenience job for handling bam indexing to make the workflow declaration cleaner :param JobFunctionWrappingJob job: passed automatically by Toil :param Namespace config: Argparse Namespace object containing argument inputs
369,277
def _waiting_expect(self): if self._expect_sent is None: if self.environ.get(, ).lower() == : return True self._expect_sent = return False
``True`` when the client is waiting for 100 Continue.
369,278
def _stdlib_paths(): attr_candidates = [ , , , ] prefixes = (getattr(sys, a) for a in attr_candidates if hasattr(sys, a)) version = % sys.version_info[0:2] return set(os.path.abspath(os.path.join(p, , version)) for p in prefixes)
Return a set of paths from which Python imports the standard library.
369,279
def stack(args): p = OptionParser(stack.__doc__) p.add_option("--top", default=10, type="int", help="Draw the first N chromosomes [default: %default]") p.add_option("--stacks", default="Exons,Introns,DNA_transposons,Retrotransposons", help="Features to...
%prog stack fastafile Create landscape plots that show the amounts of genic sequences, and repetitive sequences along the chromosomes.
369,280
def show_item_v3(h): st = rar3_type(h.type) xprint("%s: hdrlen=%d datlen=%d", st, h.header_size, h.add_size) if h.type in (rf.RAR_BLOCK_FILE, rf.RAR_BLOCK_SUB): if h.host_os == rf.RAR_OS_UNIX: s_mode = "0%o" % h.mode else: s_mode = "0x%x" % h.mode xprint(...
Show any RAR3 record.
369,281
def pluralize(self, measure, singular, plural): if measure == 1: return "{} {}".format(measure, singular) else: return "{} {}".format(measure, plural)
Returns a string that contains the measure (amount) and its plural or singular form depending on the amount. Parameters: :param measure: Amount, value, always a numerical value :param singular: The singular form of the chosen word :param plural: The plural form of th...
369,282
def _contains_blinded_text(stats_xml): tree = ET.parse(stats_xml) root = tree.getroot() total_tokens = int(root.find().text) unique_lemmas = int(root.find().get()) return (unique_lemmas / total_tokens) < 0.01
Heuristic to determine whether the treebank has blinded texts or not
369,283
def make_proxy_method(cls, name): i = cls() view = getattr(i, name) for decorator in cls.decorators: view = decorator(view) @functools.wraps(view) def proxy(**forgettable_view_args): del forgettable_view_args if hasatt...
Creates a proxy function that can be used by Flasks routing. The proxy instantiates the Mocha subclass and calls the appropriate method. :param name: the name of the method to create a proxy for
369,284
def delete_namespaced_service(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_namespaced_service_with_http_info(name, namespace, **kwargs) else: (data) = self.delete_namespaced_service_with_http_info(name, namespace, **kw...
delete_namespaced_service # noqa: E501 delete a Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_service(name, namespace, async_req=True) >>> result...
369,285
def make_spindles(events, power_peaks, powers, dat_det, dat_orig, time, s_freq): i, events = _remove_duplicate(events, dat_det) power_peaks = power_peaks[i] spindles = [] for i, one_peak, one_pwr in zip(events, power_peaks, powers): one_spindle = {: time[i[0]], ...
Create dict for each spindle, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples, and peak frequency power_peaks : ndarray (dtype='float') peak in power spectrum for each event powers : ndarray (dtype='floa...
369,286
def compact(db_spec, poll_interval=0): server = get_server_from_specifier(db_spec) db = get_db_from_specifier(db_spec) logger = logging.getLogger() logger.info( % (db_spec, repr_bytes(db.info()[]),)) logger.debug( + urlparse.urljoin(db.resource.uri + , )) resp_he...
Compact a CouchDB database with optional synchronicity. The ``compact`` function will compact a CouchDB database stored on an running CouchDB server. By default, this process occurs *asynchronously*, meaning that the compaction will occur in the background. Often, you'll want to know when the proce...
369,287
def triangulate(self): npts = self._vertices.shape[0] if np.any(self._vertices[0] != self._vertices[1]): edges = np.empty((npts, 2), dtype=np.uint32) edges[:, 0] = np.arange(npts) edges[:, 1] = edges[:, 0] + 1 edges[-1, 1] = 0 ...
Triangulates the set of vertices and stores the triangles in faces and the convex hull in convex_hull.
369,288
def deep_del(data, fn): result = {} for k, v in data.iteritems(): if not fn(v): if isinstance(v, dict): result[k] = deep_del(v, fn) else: result[k] = v return result
Create dict copy with removed items. Recursively remove items where fn(value) is True. Returns: dict: New dict with matching items removed.
369,289
def set_key(key, value, host=None, port=None, db=None, password=None): * server = _connect(host, port, db, password) return server.set(key, value)
Set redis key value CLI Example: .. code-block:: bash salt '*' redis.set_key foo bar
369,290
def get(self, columns=None): if columns is None: columns = ["*"] if self._query.get_query().columns: columns = [] select = self._get_select_columns(columns) models = self._query.add_select(*select).get_models() self._hydrate_pivot_relation(mod...
Execute the query as a "select" statement. :type columns: list :rtype: orator.Collection
369,291
def contour_to_geojson(contour, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit=, stroke_width=1, geojson_properties=None, strdump=False, serialize=True): collections = contour.collections contour_index = 0 line_features = [] for collection i...
Transform matplotlib.contour to geojson.
369,292
def k_ion(self, E): return self.n_p * _np.power(_spc.e, 2) / (2*_sltr.GeV2joule(E) * _spc.epsilon_0)
Geometric focusing force due to ion column for given plasma density as a function of *E*
369,293
def env_present(name, value=None, user=): ret = {: {}, : , : name, : True} if __opts__[]: status = _check_cron_env(user, name, value=value) ret[] = None if status == : ret[] = .format(name) elif sta...
Verifies that the specified environment variable is present in the crontab for the specified user. name The name of the environment variable to set in the user crontab user The name of the user whose crontab needs to be modified, defaults to the root user value The val...
369,294
def exclude(self, *fields): if len(fields) == 1 and isinstance(fields[0], list): exclude_fields = fields[0] else: exclude_fields = list(fields) exclude_fields = [self._defunc(it) for it in exclude_fields] exclude_fields = [field.name if not isinstance(f...
Projection columns which not included in the fields :param fields: field names :return: new collection :rtype: :class:`odps.df.expr.expression.CollectionExpr`
369,295
def sphinx(self): try: assert __IPYTHON__ classdoc = except (NameError, AssertionError): scls = self.sphinx_class() classdoc = .format(scls) if scls else prop_doc = .format( name=self.name, cls=classdoc, ...
Generate Sphinx-formatted documentation for the Property
369,296
def getProvince(self, default=None): physical_address = self.getPhysicalAddress().get("state", default) postal_address = self.getPostalAddress().get("state", default) return physical_address or postal_address
Return the Province from the Physical or Postal Address
369,297
def create_review(self, commit=github.GithubObject.NotSet, body=None, event=github.GithubObject.NotSet, comments=github.GithubObject.NotSet): assert commit is github.GithubObject.NotSet or isinstance(commit, github.Commit.Commit), commit assert isinstance(body, str), body assert event i...
:calls: `POST /repos/:owner/:repo/pulls/:number/reviews <https://developer.github.com/v3/pulls/reviews/>`_ :param commit: github.Commit.Commit :param body: string :param event: string :param comments: list :rtype: :class:`github.PullRequestReview.PullRequestReview`
369,298
def get_header(self, name, default=None): return self._handler.headers.get(name, default)
Retrieves the value of a header
369,299
def infer_active_forms(stmts): linked_stmts = [] for act_stmt in _get_statements_by_type(stmts, RegulateActivity): if not (act_stmt.subj.activity is not None and act_stmt.subj.activity.activity_type == and act_stmt.subj.activity.is_activ...
Return inferred ActiveForm from RegulateActivity + Modification. This function looks for combinations of Activation/Inhibition Statements and Modification Statements, and infers an ActiveForm from them. For example, if we know that A activates B and A phosphorylates B, then we can infer...