Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
370,400
def estimate_completion(self): if self.completion_ts: defer.returnValue(self.completed) subtask_completion = yield self.estimate_descendents() defer.returnValue(subtask_completion) if self.state == task_states.FREE: est_compl...
Estimate completion time for a task. :returns: deferred that when fired returns a datetime object for the estimated, or the actual datetime, or None if we could not estimate a time for this task method.
370,401
def get(self, volume_id): return self.prepare_model(self.client.api.inspect_volume(volume_id))
Get a volume. Args: volume_id (str): Volume name. Returns: (:py:class:`Volume`): The volume. Raises: :py:class:`docker.errors.NotFound` If the volume does not exist. :py:class:`docker.errors.APIError` If the serve...
370,402
def read_obo(cls, path, flatten=True, part_of_cc_only=False): name2id = {} alt_id = {} syn2id = {} terms = [] with open(path) as fh: n = 0 while True: try: nextline = next(fh) except StopIterat...
Parse an OBO file and store GO term information. Parameters ---------- path: str Path of the OBO file. flatten: bool, optional If set to False, do not generate a list of all ancestors and descendants for each GO term. part_of_cc_only: bool, op...
370,403
def finalize_prov_profile(self, name): if name is None: filename = "primary.cwlprov" else: filename = "%s.%s.cwlprov" % (wf_name, self.workflow_run_uuid) basename = posixpath.join(_posix_path(...
Transfer the provenance related files to the RO.
370,404
def send(self): if self.logger: self.logger.info("Starting to send %d items" % len(self._items_list)) try: max_value = ZBX_TRAPPER_MAX_VALUE if self.debug_level >= 4: max_value = 1 if sel...
Entrypoint to send data to Zabbix If debug is enabled, items are sent one by one If debug isn't enable, we send items in bulk Returns a list of results (1 if no debug, as many as items in other case)
370,405
def receive_data(self, data): if data is None: self._events.append(CloseConnection(code=CloseReason.ABNORMAL_CLOSURE)) self._state = ConnectionState.CLOSED return if self.state in (ConnectionState...
Pass some received data to the connection for handling. A list of events that the remote peer triggered by sending this data can be retrieved with :meth:`~wsproto.connection.Connection.events`. :param data: The data received from the remote peer on the network. :type data: ``bytes``
370,406
def main(): logger.info(, repr(REQUIRED_TOPICS)) client = connect_kafka(hosts=KAFKA_HOSTS) check_topics(client, REQUIRED_TOPICS)
Start main part of the wait script.
370,407
def flip_alleles(genotypes): warnings.warn("deprecated: use ", DeprecationWarning) genotypes.reference, genotypes.coded = (genotypes.coded, genotypes.reference) genotypes.genotypes = 2 - genotypes.genotypes return genotypes
Flip the alleles of an Genotypes instance.
370,408
def bin_spikes(spike_times, binsz): bins = np.empty((len(spike_times),), dtype=int) for i, stime in enumerate(spike_times): bins[i] = np.floor(np.around(stime/binsz, 5)) return bins
Sort spike times into bins :param spike_times: times of spike instances :type spike_times: list :param binsz: length of time bin to use :type binsz: float :returns: list of bin indicies, one for each element in spike_times
370,409
def _to_dict(self): _dict = {} if hasattr(self, ) and self.heading is not None: _dict[] = self.heading._to_dict() return _dict
Return a json dictionary representing this model.
370,410
def with_units(self, val, ua, ub): if not val: return str(val) if ua or ub: if ua and ub: if ua == ub: return str(val) + ua else: ...
Return value with unit. args: val (mixed): result ua (str): 1st unit ub (str): 2nd unit raises: SyntaxError returns: str
370,411
def get_all_for_project(self, name, **kwargs): kwargs[] = True if kwargs.get(): return self.get_all_for_project_with_http_info(name, **kwargs) else: (data) = self.get_all_for_project_with_http_info(name, **kwargs) return data
Gets the Build Records produced from the BuildConfiguration by name. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response):...
370,412
def build_net(self, is_training): cfg = self.cfg with tf.device(): word_embed = tf.get_variable( name=, initializer=self.embed, dtype=tf.float32, trainable=False) char_embed = tf.get_variable(name=, shape=[cfg.char...
Build the whole neural network for the QA model.
370,413
def split(self, t): pt = self.point(t) return Line(self.start, pt), Line(pt, self.end)
returns two segments, whose union is this segment and which join at self.point(t).
370,414
def embed(args): p = OptionParser(embed.__doc__) p.set_mingap(default=10) p.add_option("--min_length", default=200, type="int", help="Minimum length to consider [default: %default]") opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) e...
%prog embed evidencefile scaffolds.fasta contigs.fasta Use SSPACE evidencefile to scaffold contigs into existing scaffold structure, as in `scaffolds.fasta`. Contigs.fasta were used by SSPACE directly to scaffold. Rules: 1. Only update existing structure by embedding contigs small enough to fit. ...
370,415
def go_from(self, vertex): if self.vertex_out: self.vertex_out.edges_out.remove(self) self.vertex_out = vertex vertex.edges_out.add(self)
Tell the edge to go out from this vertex. Args: vertex (Vertex): vertex to go from.
370,416
def format_item(self, item, defaults=None, stencil=None): from pyrobase.osutil import shell_escape try: item_text = fmt.to_console(formatting.format_item(self.options.output_format, item, defaults)) except (NameError, ValueError, TypeError), exc: self.fatal("Tro...
Format an item.
370,417
def _handle_sdp_target_state_updated(sdp_state: SDPState): LOG.info() LOG.info(, sdp_state.target_state) if sdp_state.target_state == : _update_services_target_state() sdp_state.update_current_state(sdp_state.target_state)
Respond to an SDP target state change event. This function sets the current state of SDP to the target state if that is possible. TODO(BMo) This cant be done as a blocking function as it is here!
370,418
def write(self, learn:Learner, trn_batch:Tuple, val_batch:Tuple, iteration:int, tbwriter:SummaryWriter)->None: "Writes training and validation batch images to Tensorboard." self._write_for_dstype(learn=learn, batch=val_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Valid) sel...
Writes training and validation batch images to Tensorboard.
370,419
def libvlc_video_set_marquee_string(p_mi, option, psz_text): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,), (1,), (1,),), None, None, MediaPlayer, ctypes.c_uint, ctypes.c_char_p) return f(p_mi, option, psz_text)
Set a marquee string option. @param p_mi: libvlc media player. @param option: marq option to set See libvlc_video_marquee_string_option_t. @param psz_text: marq option value.
370,420
def place_on_gpu(data): data_type = type(data) if data_type in (list, tuple): data = [place_on_gpu(data[i]) for i in range(len(data))] data = data_type(data) return data elif isinstance(data, torch.Tensor): return data.cuda() else: return ValueError(f"Data ty...
Utility to place data on GPU, where data could be a torch.Tensor, a tuple or list of Tensors, or a tuple or list of tuple or lists of Tensors
370,421
def terminate(self): self.log.info("Sending termination message to manager.") self._child_signal_conn.send(DagParsingSignal.TERMINATE_MANAGER)
Send termination signal to DAG parsing processor manager and expect it to terminate all DAG file processors.
370,422
def get_contributors(self, anon=github.GithubObject.NotSet): url_parameters = dict() if anon is not github.GithubObject.NotSet: url_parameters["anon"] = anon return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, self._requester, ...
:calls: `GET /repos/:owner/:repo/contributors <http://developer.github.com/v3/repos>`_ :param anon: string :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
370,423
def main(): parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", help="convert the markdown file to HTML") parser.add_argument("-d", "--directory", help="convert the markdown files in the directory to HTML") parser.add_argument(...
function to
370,424
def uri_to_iri(value): if not isinstance(value, byte_cls): raise TypeError(unwrap( , type_name(value) )) parsed = urlsplit(value) scheme = parsed.scheme if scheme is not None: scheme = scheme.decode() username = _urlunquote(parsed.username, re...
Converts an ASCII URI byte string into a unicode IRI :param value: An ASCII-encoded byte string of the URI :return: A unicode string of the IRI
370,425
def _from_binary_ea(cls, binary_stream): _ea_list = [] offset = 0 _MOD_LOGGER.debug("Creating Ea object from binary ...", binary_stream.tobytes()) while True: entry = EaEntry.create_from_binary(binary_stream[offset:]) offset += entry.offset_next_ea _ea_list.append(entr...
See base class.
370,426
def _authn_context_decl_ref(decl_ref, authn_auth=None): return factory(saml.AuthnContext, authn_context_decl_ref=decl_ref, authenticating_authority=factory( saml.AuthenticatingAuthority, text=authn_auth))
Construct the authn context with a authn context declaration reference :param decl_ref: The authn context declaration reference :param authn_auth: Authenticating Authority :return: An AuthnContext instance
370,427
def _logins(users, user_attrs=None): if in user_attrs: if user_attrs.index() >= 0: del user_attrs[user_attrs.index()] _users = {} for u in users: l = u.login logr.debug(.format(l)) ...
FIXME: DOCS...
370,428
def _updateTransitionMatrix(self): C = self.model.count_matrix() + self.prior_C if self.reversible and not _tmatrix_disconnected.is_connected(C, strong=True): raise NotImplementedError( + str(C) + ) ...
Updates the hidden-state transition matrix and the initial distribution
370,429
def buildPaginationHeader(resultCount, resultsPerPage, pageArg, url): lastPage = resultCount / resultsPerPage if pageArg: page = int(pageArg) next_url = re.sub("page=[0-9]+", "page={}".format(page + 1), url) prev_url = re.sub("page=[0-9]+", "page={}".format(page - 1), url) ...
Build link header for result pagination
370,430
def _do_shell(self, line): if not line: return sp = Popen(line, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=not WINDOWS) (fo, fe) = (sp.stdout, sp.stderr) i...
Send a command to the Unix shell.\n==> Usage: shell ls ~
370,431
def create_space(self, space_name, add_users=True): body = { : space_name, : self.api.config.get_organization_guid() } if add_users: space_users = [] org_users = self.org.get_users() for org_user in org_users[]: ...
Create a new space with the given name in the current target organization.
370,432
def eval_string(self, s): self._filename = None return expr_value(self._expect_expr_and_eol())
Returns the tristate value of the expression 's', represented as 0, 1, and 2 for n, m, and y, respectively. Raises KconfigError if syntax errors are detected in 's'. Warns if undefined symbols are referenced. As an example, if FOO and BAR are tristate symbols at least one of which has t...
370,433
def animate(self,*args,**kwargs): try: from IPython.display import HTML except ImportError: raise ImportError("Orbit.animate requires ipython/jupyter to be installed") if (kwargs.get(,False) \ and kwargs.get(,self._roSet)) or \ (n...
NAME: animate PURPOSE: animate an Orbit INPUT: d1= first dimension to plot ('x', 'y', 'R', 'vR', 'vT', 'z', 'vz', ...); can be list with up to three entries for three subplots d2= second dimension to plot; can be list with up to three entries for three subplot...
370,434
def add_user(self, workspace, params={}, **options): path = "/workspaces/%s/addUser" % (workspace) return self.client.post(path, params, **options)
The user can be referenced by their globally unique user ID or their email address. Returns the full user record for the invited user. Parameters ---------- workspace : {Id} The workspace or organization to invite the user to. [data] : {Object} Data for the request - u...
370,435
def ensure_dir_exists(f, fullpath=False): if fullpath is False: d = os.path.dirname(f) else: d = f if not os.path.exists(d): os.makedirs(d)
Ensure the existence of the (parent) directory of f
370,436
def preprocess(input_file, output_file, defines=None, options=None, content_types_db=None, _preprocessed_files=None, _depth=0): include_paths = options.include_paths should_keep_lines = options.should_keep_lines...
Preprocesses the specified file. :param input_filename: The input path. :param output_filename: The output file (NOT path). :param defines: a dictionary of defined variables that will be understood in preprocessor statements. Keys must be strings and, currently, only...
370,437
def set_leaf_dist(self, attr_value, dist): assert self.attr_name assert self.tree.data.is_valid(self.attr_name, attr_value), \ "Value %s is invalid for attribute %s." \ % (attr_value, self.attr_name) if self.is_continuous_class: assert isinstance(...
Sets the probability distribution at a leaf node.
370,438
def init_db(self): db_path = self.get_data_file("data.sqlite") self.db = sqlite3.connect(db_path) self.cursor = self.db.cursor() self.db_exec()
Init database and prepare tables
370,439
def list_build_set_records(id=None, name=None, page_size=200, page_index=0, sort="", q=""): content = list_build_set_records_raw(id, name, page_size, page_index, sort, q) if content: return utils.format_json_list(content)
List all build set records for a BuildConfigurationSet
370,440
def template_instances(cls, dataset, capacity=0): return Instances( javabridge.make_instance( "weka/core/Instances", "(Lweka/core/Instances;I)V", dataset.jobject, capacity))
Uses the Instances as template to create an empty dataset. :param dataset: the original dataset :type dataset: Instances :param capacity: how many data rows to reserve initially (see compactify) :type capacity: int :return: the empty dataset :rtype: Instances
370,441
def entry_point(): try: mainret = main() except (EOFError, KeyboardInterrupt): print_err() mainret = 2 except BrokenPipeError: print_err() mainret = 3 except InvalidArg as exarg: handle_err(exarg.as_colr()) mainret = 4 except ValueError as...
An entry point for setuptools. This is required because `if __name__ == '__main__'` is not fired when the entry point is 'main()'. This just wraps the old behavior in a function so it can be called from setuptools.
370,442
def file_ns_handler(importer, path_item, packageName, module): subpath = os.path.join(path_item, packageName.split()[-1]) normalized = _normalize_cached(subpath) for item in module.__path__: if _normalize_cached(item) == normalized: break else: return subpath
Compute an ns-package subpath for a filesystem or zipfile importer
370,443
def set_min(self, fmin): if round(100000*fmin) != 100000*fmin: raise DriverError( + ) self.fmin = fmin self.set(self.fmin)
Updates minimum value
370,444
def _from_dict(cls, _dict): args = {} if in _dict: args[] = [ Configuration._from_dict(x) for x in (_dict.get()) ] return cls(**args)
Initialize a ListConfigurationsResponse object from a json dictionary.
370,445
def __protocolize(base_url): if not base_url.startswith("http://") and not base_url.startswith("https://"): base_url = "https://" + base_url base_url = base_url.rstrip("/") return base_url
Internal add-protocol-to-url helper
370,446
def U(self): if self._U is None: sinv = N.diag(1/self.singular_values) self._U = dot(self.arr,self.V.T,sinv) return self._U
Property to support lazy evaluation of residuals
370,447
def create_user(name, username, email, password, token_manager=None, app_url=defaults.APP_URL): headers = token_manager.get_access_token_headers() auth_url = environment.get_auth_url(app_url=app_url) url = "%s/api/v1/accoun...
create a new user with the specified name, username email and password
370,448
def get_repository_search_session(self): if not self.supports_repository_search(): raise Unimplemented() try: from . import sessions except ImportError: raise try: session = sessions.RepositorySearchSession(proxy=self._proxy, ...
Gets the repository search session. return: (osid.repository.RepositorySearchSession) - a RepositorySearchSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_repository_search() is false compliance: optional - This method must be...
370,449
def getResults(uri): i3Browser = browser.Browser() data = i3Browser.recoverURL(uri) regExp = "<!-- Results -->(.*)<!-- /Results -->" results = re.findall(regExp, data, re.DOTALL) return results
Method that recovers the text for each result in infobel.com :param uri: Infobel uri :return: A list of textual information to be processed
370,450
def search_converted_models(root=None): if root is None: root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tests")) root = os.path.normpath(root) if not os.path.exists(root): raise FileNotFoundError("Unable to find .".format(root)) founds = glob.iglob("{...
Searches for all converted models generated by unit tests in folders tests and with function *dump_data_and_model*.
370,451
def compute_tls13_handshake_secrets(self): if self.tls13_early_secret is None: warning("No early secret. This is abnormal.") hkdf = self.prcs.hkdf self.tls13_handshake_secret = hkdf.extract(self.tls13_early_secret, self.tl...
Ciphers key and IV are updated accordingly for Handshake data. self.handshake_messages should be ClientHello...ServerHello.
370,452
def get_output(self): if self.process.poll() is not None: self.close() yield None, None while not (self.stdout_queue.empty() and self.stderr_queue.empty()): if not self.stdout_queue.empty(): line = self.stdout_queue.get().decode() ...
:yield: stdout_line, stderr_line, running Generator that outputs lines captured from stdout and stderr These can be consumed to output on a widget in an IDE
370,453
def post_replicate(request): d1_gmn.app.views.assert_db.post_has_mime_parts( request, ((, ), (, )) ) sysmeta_pyxb = d1_gmn.app.sysmeta.deserialize(request.FILES[]) d1_gmn.app.local_replica.assert_request_complies_with_replication_policy( sysmeta_pyxb ) pid = d1_common.xml.ge...
MNReplication.replicate(session, sysmeta, sourceNode) → boolean.
370,454
def collapse_whitespace(message): return u.join(map(lambda s: s.strip(), filter(None, message.strip().splitlines())))
Collapses consecutive whitespace into a single space
370,455
def createInput(self): print "-" * 70 + "Creating a random input vector" + "-" * 70 self.inputArray[0:] = 0 for i in range(self.inputSize): self.inputArray[i] = random.randrange(2)
create a random input vector
370,456
def is_local(self, hadoop_conf=None, hadoop_home=None): conf = self.hadoop_params(hadoop_conf, hadoop_home) keys = (, , ) for k in keys: if conf.get(k, ).lower() != : return False return True
\ Is Hadoop configured to run in local mode? By default, it is. [pseudo-]distributed mode must be explicitly configured.
370,457
def get_status(self, mxit_id, scope=): status = _get( token=self.oauth.get_app_token(scope), uri= + urllib.quote(mxit_id) ) if status.startswith() and status.endswith(): status = status[1:-1] return status
Retrieve the Mxit user's current status No user authentication required
370,458
def _create_binary_trigger(trigger): ops = { 0: ">", 1: "<", 2: ">=", 3: "<=", 4: "==", 5: } op_codes = {y: x for x, y in ops.items()} source = 0 if isinstance(trigger, TrueTrigger): op_code = op_codes[] elif isinstance(trigger, Fa...
Create an 8-bit binary trigger from an InputTrigger, TrueTrigger, FalseTrigger.
370,459
def retention_policy_get(database, name, user=None, password=None, host=None, port=None): * client = _client(user=user, password=password, host=host, port=port) for policy in client....
Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retention_policy_get metrics default
370,460
def get_surveys(self): payload = { : , : } r = self._session.get(QUALTRICS_URL, params=payload) output = r.json() return output[][]
Gets all surveys in account Args: None Returns: list: a list of all surveys
370,461
def samples(self, gp, Y_metadata=None): orig_shape = gp.shape gp = gp.flatten() gp = gp.flatten() Ysim = np.array([np.random.normal(self.gp_link.transf(gpj), scale=np.sqrt(self.variance), size=1) for gpj in gp]) return Ysim.reshape(orig_shape)
Returns a set of samples of observations based on a given value of the latent variable. :param gp: latent variable
370,462
def add_context(self, err_context, succ_context=None): self.err_context = err_context self.succ_context = succ_context
Prepend msg to add some context information :param pmsg: context info :return: None
370,463
def process(self, data=None): return super(RequestHandler, self).process(data=data or self.get_request_data())
Fetch incoming data from the Flask request object when no data is supplied to the process method. By default, the RequestHandler expects the incoming data to be sent as JSON.
370,464
def Romeo_2002(Re, eD): r fd = (-2*log10(eD/3.7065-5.0272/Re*log10(eD/3.827-4.567/Re*log10((eD/7.7918)**0.9924+(5.3326/(208.815+Re))**0.9345))))**-2 return fd
r'''Calculates Darcy friction factor using the method in Romeo (2002) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_d}} = -2\log\left\{\frac{\epsilon}{3.7065D}\times \frac{5.0272}{Re}\times\log\left[\frac{\epsilon}{3.827D} - \frac{4.567}{Re}\times\log\left(\frac{\epsilon}{7.7918D}^{...
370,465
def get_source(self): if self._source is None: self.emit("}\n") self._source = "\n".join(self.lines) del self.lines return self._source
returns self._source
370,466
def blake2b(data, digest_size=BLAKE2B_BYTES, key=b, salt=b, person=b, encoder=nacl.encoding.HexEncoder): digest = _b2b_hash(data, digest_size=digest_size, key=key, salt=salt, person=person) return encoder.encode(digest)
Hashes ``data`` with blake2b. :param data: the digest input byte sequence :type data: bytes :param digest_size: the requested digest size; must be at most :const:`BLAKE2B_BYTES_MAX`; the default digest size is :const:`BLAKE2B_BYTES` ...
370,467
def strframe(obj, extended=False): fname = normalize_windows_fname(obj[1]) ret = list() ret.append(pcolor("Frame object ID: {0}".format(hex(id(obj[0]))), "yellow")) ret.append("File name......: {0}".format(fname)) ret.append("Line number....: {0}".format(obj[2])) ret.append("...
Return a string with a frame record pretty-formatted. The record is typically an item in a list generated by `inspect.stack() <https://docs.python.org/3/library/inspect.html#inspect.stack>`_). :param obj: Frame record :type obj: tuple :param extended: Flag that indicates whether contents of the ...
370,468
def get_corrections_dict(self, entry): corrections = {} for c in self.corrections: val = c.get_correction(entry) if val != 0: corrections[str(c)] = val return corrections
Returns the corrections applied to a particular entry. Args: entry: A ComputedEntry object. Returns: ({correction_name: value})
370,469
def install_all_labels(stdout=None): if not stdout: stdout = sys.stdout def subsub(kls): return kls.__subclasses__() + [g for s in kls.__subclasses__() for g in subsub(s)] stdout.write("Setting up indexes and constraints...\n\n") i = 0 for cls in subsub(StructuredNode): ...
Discover all subclasses of StructuredNode in your application and execute install_labels on each. Note: code most be loaded (imported) in order for a class to be discovered. :param stdout: output stream :return: None
370,470
def bank_chisq_from_filters(tmplt_snr, tmplt_norm, bank_snrs, bank_norms, tmplt_bank_matches, indices=None): if indices is not None: tmplt_snr = Array(tmplt_snr, copy=False) bank_snrs_tmp = [] for bank_snr in bank_snrs: bank_snrs_tmp.append(bank_snr.take(indices)) ...
This function calculates and returns a TimeSeries object containing the bank veto calculated over a segment. Parameters ---------- tmplt_snr: TimeSeries The SNR time series from filtering the segment against the current search template tmplt_norm: float The normalization fac...
370,471
def set_slimits(self, row, column, min, max): subplot = self.get_subplot_at(row, column) subplot.set_slimits(min, max)
Set limits for the point sizes. :param min: point size for the lowest value. :param max: point size for the highest value.
370,472
def read_telenor(incoming_cdr, outgoing_cdr, cell_towers, describe=True, warnings=True): log.warn("read_telenor has been deprecated in bandicoot 0.4.") import itertools import csv def parse_direction(code): if code == : return elif code == : ...
Load user records from a CSV file in *telenor* format, which is only applicable for call records. .. warning:: ``read_telenor`` has been deprecated in bandicoot 0.4. Parameters ---------- incoming_cdr : str Path to the CSV file containing incoming records, using the following schem...
370,473
def _strip_colors(self, message: str) -> str: for c in self.COLORS: message = message.replace(c, "") return message
Remove all of the color tags from this message.
370,474
def _apply_bias(inputs, outputs, channel_index, data_format, output_channels, initializers, partitioners, regularizers): bias_shape = (output_channels,) if "b" not in initializers: initializers["b"] = create_bias_initializer(bias_shape, dtype=in...
Initialize and apply a bias to the outputs. Figures out the shape of the bias vector, initialize it, and applies it. Args: inputs: A Tensor of shape `data_format`. outputs: A Tensor of shape `data_format`. channel_index: The index of the channel dimension in `inputs`. data_format: Format of `input...
370,475
def lerfcc(x): z = abs(x) t = 1.0 / (1.0+0.5*z) ans = t * math.exp(-z*z-1.26551223 + t*(1.00002368+t*(0.37409196+t*(0.09678418+t*(-0.18628806+t*(0.27886807+t*(-1.13520398+t*(1.48851587+t*(-0.82215223+t*0.17087277))))))))) if x >= 0: return ans else: return 2.0 - ans
Returns the complementary error function erfc(x) with fractional error everywhere less than 1.2e-7. Adapted from Numerical Recipies. Usage: lerfcc(x)
370,476
def parse_authn_request_response(self, xmlstr, binding, outstanding=None, outstanding_certs=None, conv_info=None): if not getattr(self.config, , None): raise SAMLError("Missing entity_id specification") if not xmlstr: return None ...
Deal with an AuthnResponse :param xmlstr: The reply as a xml string :param binding: Which binding that was used for the transport :param outstanding: A dictionary with session IDs as keys and the original web request from the user before redirection as values. :p...
370,477
def calc_smoothpar_logistic2(metapar): if metapar <= 0.: return 0. return optimize.newton(_error_smoothpar_logistic2, .3 * metapar**.84, _smooth_logistic2_derivative, args=(metapar,))
Return the smoothing parameter corresponding to the given meta parameter when using |smooth_logistic2|. Calculate the smoothing parameter value corresponding the meta parameter value 2.5: >>> from hydpy.auxs.smoothtools import calc_smoothpar_logistic2 >>> smoothpar = calc_smoothpar_logistic2(2.5) ...
370,478
def _init(frame, log_level=ERROR): s inner logger level (equivalent to logging pkg) t the __main__, stop and return. pkg = main_globals.get() file_ = main_globals.get() if pkg or not file_: _log_debug( % (pkg, file_)) return try: _solve_...
Enables explicit relative import in sub-modules when ran as __main__ :param log_level: module's inner logger level (equivalent to logging pkg)
370,479
def is_frameshift_len(mut_df): if in mut_df.columns: indel_len = mut_df[] else: indel_len = compute_indel_length(mut_df) is_fs = (indel_len%3)>0 is_indel = (mut_df[]==) | (mut_df[]==) is_fs[~is_indel] = False return is_fs
Simply returns a series indicating whether each corresponding mutation is a frameshift. This is based on the length of the indel. Thus may be fooled by frameshifts at exon-intron boundaries or other odd cases. Parameters ---------- mut_df : pd.DataFrame mutation input file as a datafra...
370,480
def network_details(): ipv4_addresses = [ info[4][0] for info in socket.getaddrinfo( socket.gethostname(), None, socket.AF_INET ) ] ipv4_addresses.extend( info[4][0] for info in socket.getaddr...
Returns details about the network links
370,481
def is_image(self, key): data = self.model.get_data() return isinstance(data[key], Image)
Return True if variable is a PIL.Image image
370,482
def apply_heuristic(self, node_a, node_b, heuristic=None): if not heuristic: heuristic = self.heuristic return heuristic( abs(node_a.x - node_b.x), abs(node_a.y - node_b.y))
helper function to apply heuristic
370,483
def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: + name, formatvarkw=lambda name: + name, formatvalue=lambda value: + repr(value), join=joinseq): def convert(name, l...
Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional functio...
370,484
def stitch_block_rows(block_list): stitched = list(itertools.chain(*block_list)) max_length = max(len(row) for row in stitched) for row in stitched: if len(row) < max_length: row += [None] * (max_length - len(row)) return stitched
Stitches blocks together into a single block rowwise. These blocks are 2D tables usually generated from tableproc. The final block will be of dimensions (sum(num_rows), max(num_cols)).
370,485
def von_mises_strain(self): eps = self - 1/3 * np.trace(self) * np.identity(3) return np.sqrt(np.sum(eps * eps) * 2/3)
Equivalent strain to Von Mises Stress
370,486
def is_diacritic(char, strict=True): if char in chart.diacritics: return True if not strict: return (unicodedata.category(char) in [, , ]) \ and (not is_suprasegmental(char)) \ and (not is_tie_bar(char)) \ and (not 0xA700 <= ord(char) <= 0xA71F) return False
Check whether the character is a diacritic (as opposed to a letter or a suprasegmental). In strict mode return True only if the diacritic is part of the IPA spec.
370,487
def open(self, filename): if self._initialized: raise pycdlibexception.PyCdlibInvalidInput() fp = open(filename, ) self._managing_fp = True try: self._open_fp(fp) except Exception: fp.close() raise
Open up an existing ISO for inspection and modification. Parameters: filename - The filename containing the ISO to open up. Returns: Nothing.
370,488
def highlight(string, keywords, cls_name=): if not keywords: return string if not string: return include, exclude = get_text_tokenizer(keywords) highlighted = highlight_text(include, string, cls_name) return highlighted
Given an list of words, this function highlights the matched text in the given string.
370,489
def finish_operation(self, conn_or_internal_id, success, *args): data = { : conn_or_internal_id, : success, : args } action = ConnectionAction(, data, sync=False) self._actions.put(action)
Finish an operation on a connection. Args: conn_or_internal_id (string, int): Either an integer connection id or a string internal_id success (bool): Whether the operation was successful failure_reason (string): Optional reason why the operation failed ...
370,490
def load(self): filters = [Filter(self.field, , self.rid)] store = goldman.sess.store self._is_loaded = True self.models = store.search(self.rtype, filters=filters) return self.models
Return the model from the store
370,491
def mark_deactivated(self,request,queryset): rows_updated = queryset.update(Active=False, End=datetime.date.today() ) if rows_updated == 1: message_bit = "1 cage was" else: message_bit = "%s cages were" % rows_updated self.message_user(request, "%s succes...
An admin action for marking several cages as inactive. This action sets the selected cages as Active=False and Death=today. This admin action also shows as the output the number of mice sacrificed.
370,492
def extract_date(value): dtime = value.to_datetime() dtime = (dtime - timedelta(hours=dtime.hour) - timedelta(minutes=dtime.minute) - timedelta(seconds=dtime.second) - timedelta(microseconds=dtime.microsecond)) return dtime
Convert timestamp to datetime and set everything to zero except a date
370,493
def get_metabolite_compartments(self): warn(, DeprecationWarning) return {met.compartment for met in self.metabolites if met.compartment is not None}
Return all metabolites' compartments.
370,494
def read_configuration(self): self.configured = True backend = (getattr(settings, , None) or getattr(settings, , None)) if not backend: settings.CELERY_RESULT_BACKEND = return DictAttribute(settings)
Load configuration from Django settings.
370,495
def retyped(self, new_type): return ParseNode(new_type, children=list(self.children), consumed=self.consumed, position=self.position, ignored=self.ignored)
Returns a new node with the same contents as self, but with a new node_type.
370,496
def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None: meta = MetaData(bind=engine) writeline_nl(fileobj, sql_comment(.format(meta)))
Dumps some connection info, as an SQL comment. Obscures passwords. Args: engine: the SQLAlchemy :class:`Engine` to dump metadata information from fileobj: the file-like object (default ``sys.stdout``) to write information to
370,497
def _is_dirty(self, xblock): if self not in xblock._dirty_fields: return False baseline = xblock._dirty_fields[self] return baseline is EXPLICITLY_SET or xblock._field_data_cache[self.name] != baseline
Return whether this field should be saved when xblock.save() is called
370,498
def check_ressources(sess): cpu_value = get_data(sess, cpu_oid, helper) memory_value = get_data(sess, memory_oid, helper) filesystem_value = get_data(sess, filesystem_oid, helper) helper.add_summary("Controller Status") helper.add_long_output...
check the Ressources of the Fortinet Controller all thresholds are currently hard coded. should be fine.
370,499
def delete(self, image_file, delete_thumbnails=True): if delete_thumbnails: self.delete_thumbnails(image_file) self._delete(image_file.key)
Deletes the reference to the ``image_file`` and deletes the references to thumbnails as well as thumbnail files if ``delete_thumbnails`` is `True``. Does not delete the ``image_file`` is self.