Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
352,800
def analysis_add_tags(object_id, input_params={}, always_retry=True, **kwargs): return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /analysis-xxxx/addTags API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Workflows-and-Analyses#API-method%3A-%2Fanalysis-xxxx%2FaddTags
352,801
def state(self, time=None): if time is None: return max(self.infos(type=State), key=attrgetter()) else: states = [ s for s in self.infos(type=State) if s.creation_time < time] return max(states, key=attrgetter())
The most recently-created info of type State at the specfied time. If time is None then it returns the most recent state as of now.
352,802
def check_neighbors(self, start, end, grid, open_list, open_value=True, backtrace_by=None): node = heapq.nsmallest(1, open_list)[0] open_list.remove(node) node.closed = True if not backtrace_by and node == end: ...
find next path segment based on given node (or return path if we found the end)
352,803
def _validate_signing_cert(ca_certificate, certificate, crl=None): pyopenssl_cert = load_certificate(FILETYPE_PEM, certificate) pyopenssl_ca_cert = load_certificate(FILETYPE_PEM, ca_certificate) cert_store = X509Store() cert_store.add_cert(pyopenssl_ca_cert) if crl: pyopenssl_crl = loa...
Validate an X509 certificate using pyOpenSSL. .. note:: pyOpenSSL is a short-term solution to certificate validation. pyOpenSSL is basically in maintenance mode and there's a desire in upstream to move all the functionality into cryptography. Args: ca_certificate (str): A PEM-e...
352,804
def listen(self): with Consumer(self.connection, queues=self.queue, on_message=self.on_message, auto_declare=False): for _ in eventloop(self.connection, timeout=1, ignore_timeouts=True): pass
Listens to messages
352,805
def record(*fields): @six.add_metaclass(_RecordMetaClass) class RecordType(object): _record_sentinel = True _record_fields = fields return RecordType
Constructs a type that can be extended to create immutable, value types. Examples: A typical declaration looks like:: class MyRecord(record('a', ('b', 1))): pass The above would make a sub-class of ``collections.namedtuple`` that was named ``MyRecord`` with a c...
352,806
def Environ(variable, default): precondition.AssertType(variable, Text) value = os.environ.get(variable, default) if value is None: return default if PY2: value = value.decode("utf-8") return value
A wrapper for `os.environ.get` that works the same way in both Pythons. Args: variable: A name of the variable to get the value of. default: A default value to return in case no value for the given variable is set. Returns: An environment value of the given variable.
352,807
def add_static_route(self, method: Union[str, Methods], route: str, handler: Callable, skip_middleware=False): if isinstance(method, str): method = Methods(method.upper()) route = self._prefix + route route = route.strip() if route not in sel...
Adds a static route. A static route is a special route that doesnt follow any of the normal rules, and never has any path parameters. Ideally, this is used for non-public facing endpoints such as "/healthcheck", or "/stats" or something of that nature. All static routes SKIP mid...
352,808
def scp_push(self, src, dest, progress=False, preserve_times=True): if progress is True: self._scp._progress = self._copy_status elif hasattr(progress, ): self._scp._progress = progress else: self._scp._progress = None ...
Purpose: Makes an SCP push request for the specified file(s)/dir. @param src: string containing the source file or directory @type src: str @param dest: destination string of where to put the file(s)/dir @type dest: str @param progress: set to `True` to have the progress callbac...
352,809
def scale(self, scalar, ignored_variables=None, ignored_interactions=None, ignore_offset=False): if ignored_variables is None: ignored_variables = set() elif not isinstance(ignored_variables, abc.Container): ignored_variables = set(ignored_variables) ...
Multiply by the specified scalar all the biases and offset of a binary quadratic model. Args: scalar (number): Value by which to scale the energy range of the binary quadratic model. ignored_variables (iterable, optional): Biases associated with these va...
352,810
def execute(self, *args, **kwargs): kwargs.pop(, None) parent_ctx = click.get_current_context(silent=True) with self.make_context(, list(args), parent=parent_ctx) as ctx: opt_mapping = dict(self.map_names()) arg_options = {opt_mapping.get(ke...
Called when run through `call_command`. `args` are passed through, while `kwargs` is the __dict__ of the return value of `self.create_parser('', name)` updated with the kwargs passed to `call_command`.
352,811
def _glob_find(self, path, processor, include_toplevel): t add the found children to the result, but traverse into paths that did have a match. t return "/" if first_magic == 1: check_path = "/" else: check_path = "/".join(path_elements[:first_magic]) ...
Handle globs in paths. This is done by listing the directory before a glob and checking which node matches the initial glob. If there are more globs in the path, we don't add the found children to the result, but traverse into paths that did have a match.
352,812
def print_benchmark(elapsed): print % (elapsed, ) keys = [, , , ] for key in keys: if key in options.counters: print % ( options.counters[key] / elapsed, key, options.counters[key])
Print benchmark numbers.
352,813
def frame_size(self): if self.sample_type == SampleType.S16NativeEndian: return self.sample_size * self.channels else: raise ValueError(, self.sample_type)
The byte size of a single frame of this format.
352,814
def add(self,keybind,kbname,handler,mod=True): keybind = keybind.lower() if mod: if keybind not in self.keybinds: self.keybinds[keybind]=[] self.keybinds[keybind].append(kbname) else: if keybind not in self.keybinds_nm: ...
Adds a keybind to the internal registry. Keybind names should be of the format ``namespace:category.subcategory.name``\ e.g. ``peng3d:actor.player.controls.forward`` for the forward key combo for the player actor. :param str keybind: Keybind string, as described above :param st...
352,815
def pages(self): if self.per_page == 0 or self.total is None: pages = 0 else: pages = int(ceil(self.total / float(self.per_page))) return pages
The total number of pages
352,816
def cs_bahdanau_attention(key, context, hidden_size, depth, projected_align=False): if hidden_size % 2 != 0: raise ValueError("hidden size must be dividable by two") batch_size = tf.shape(context)[0] max_num_tokens, token_size = context.get_shape().as_list()[-2:] r_context = tf.reshape(con...
It is a implementation of the Bahdanau et al. attention mechanism. Based on the papers: https://arxiv.org/abs/1409.0473 "Neural Machine Translation by Jointly Learning to Align and Translate" https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy...
352,817
def get(self, request, *args, **kwargs): activated_user = self.activate(*args, **kwargs) if activated_user: users_signals.user_activated.send( sender=self.__class__, user=activated_user, request=request ) return...
The base activation logic; subclasses should leave this method alone and implement activate(), which is called from this method.
352,818
def lf_conflicts(L, normalize_by_overlaps=False): conflicts = (L != 0).T @ _conflicted_data_points(L) / L.shape[0] if normalize_by_overlaps: conflicts /= lf_overlaps(L) return np.nan_to_num(conflicts)
Return the **fraction of items each LF labels that are also given a different (non-abstain) label by at least one other LF.** Note that the maximum possible conflict fraction for an LF is the LF's overlaps fraction, unless `normalize_by_overlaps=True`, in which case it is 1. Args: ...
352,819
def load_exon_bulk(self, exon_objs): try: result = self.exon_collection.insert_many(transcript_objs) except (DuplicateKeyError, BulkWriteError) as err: raise IntegrityError(err) return result
Load a bulk of exon objects to the database Arguments: exon_objs(iterable(scout.models.hgnc_exon))
352,820
def dalignbedqueriesseq2dalignbedstats(cfg): datatmpd=cfg[] dalignbedqueriesseq=del_Unnamed(pd.read_csv(cfg[],sep=)) dalignbedstatsp=cfg[] logging.info(basename(dalignbedstatsp)) if not exists(dalignbedstatsp) or cfg[]: df=dalignbedqueriesseq.apply(lambda x: align(x[],x[], ...
Gets scores for queries step#7 :param cfg: configuration dict
352,821
def open_with_encoding(filename, encoding=None, mode=, limit_byte_check=-1): if not encoding: encoding = detect_encoding(filename, limit_byte_check=limit_byte_check) return io.open(filename, mode=mode, encoding=encoding, newline=)
Return opened file with a specific encoding.
352,822
def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): return self._findOne(self.findNextSiblings, name, attrs, text, **kwargs)
Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.
352,823
def element_by_href_as_smcresult(href, params=None): if href: element = fetch_json_by_href(href, params=params) if element: return element
Get specified element returned as an SMCResult object :param href: href direct link to object :return: :py:class:`smc.api.web.SMCResult` with etag, href and element field holding json, else None
352,824
def _read_time_from_string(str1): full_time = [float(x) for x in str1.split()] hour = int(full_time[0]) minute = int(full_time[1]) if full_time[2] > 59.99: minute += 1 second = 0 else: second = int(full_time[2]) microseconds = int((full_time[2] - floor(full_time[2]))...
Reads the time from a string in the format HH:MM:SS.S and returns :class: datetime.time
352,825
def plot_rb_data(xdata, ydatas, yavg, yerr, fit, survival_prob, ax=None, show_plt=True): if not HAS_MATPLOTLIB: raise ImportError( ) if ax is None: plt.figure() ax = plt.gca() for ydata in ydatas: ax.plot(xdata, ydat...
Plot randomized benchmarking data. Args: xdata (list): list of subsequence lengths ydatas (list): list of lists of survival probabilities for each sequence yavg (list): mean of the survival probabilities at each sequence length yerr (list): error of the survi...
352,826
def sync(self): LOGGER.debug("IPAddress.sync") params = None if self.id is not None: params = {: self.id} elif self.ip_address is not None: params = {: self.ip_address} if params is not None: args = {: , : , : params} resp...
synchronize self from Ariane server according its id (priority) or name :return:
352,827
def get_local_filter_directives(ast, current_schema_type, inner_vertex_fields): result = [] if ast.directives: if not is_vertex_field_type(current_schema_type): raise GraphQLCompilationError( ...
Get all filter directives that apply to the current field. This helper abstracts away the fact that some vertex field filtering operators apply on the inner scope (the scope of the inner vertex field on which they are applied), whereas some apply on the outer scope (the scope that contains the inner vertex...
352,828
def iterrowproxy(self, cls=RowProxy): row_proxy = None headers = None for row in self: if not headers: headers = row row_proxy = cls(headers) continue yield row_proxy.set_row(row)
Iterate over the resource as row proxy objects, which allow acessing colums as attributes. Like iterrows, but allows for setting a specific RowProxy class.
352,829
def fatal(self, msg): if not self.log_to_file: msg = strip_whitespace(colors[] + "[+] " + msg + colors[]) else: msg = "[" + time.strftime("%c") + "] " + msg raise RuntimeError(msg)
For errors so grave that the program (or thread) cannot continue.
352,830
def get_metadata(path_or_module, metadata_version=None): if isinstance(path_or_module, ModuleType): try: return Installed(path_or_module, metadata_version) except (ValueError, IOError): pass try: __import__(path_or_module) except ImportError: pa...
Try to create a Distribution 'path_or_module'. o 'path_or_module' may be a module object. o If a string, 'path_or_module' may point to an sdist file, a bdist file, an installed package, or a working checkout (if it contains PKG-INFO). o Return None if 'path_or_module' can't be parsed.
352,831
def filename_command(): try: config = get_config_obj(file_error=True) except IOError as e: safeprint(e, write_to_stderr=True) click.get_current_context().exit(1) else: safeprint(config.filename)
Executor for `globus config filename`
352,832
def replace_namespaced_ingress(self, name, namespace, body, **kwargs): kwargs[] = True if kwargs.get(): return self.replace_namespaced_ingress_with_http_info(name, namespace, body, **kwargs) else: (data) = self.replace_namespaced_ingress_with_http_info(name, name...
replace the specified Ingress This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_ingress(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req b...
352,833
def run_in_greenlet(callable): @wraps(callable) async def _(*args, **kwargs): green = greenlet(callable) result = green.switch(*args, **kwargs) while isawaitable(result): try: result = green.switch((await result)) ...
Decorator to run a ``callable`` on a new greenlet. A ``callable`` decorated with this decorator returns a coroutine
352,834
def showFileHeaderData(peInstance): fileHeaderFields = peInstance.ntHeaders.fileHeader.getFields() print "[+] IMAGE_FILE_HEADER values:\n" for field in fileHeaderFields: print "--> %s = 0x%08x" % (field, fileHeaderFields[field].value)
Prints IMAGE_FILE_HEADER fields.
352,835
def default_filter_filename(filename): if filename is None: return None elif filename.startswith(TOP_DIR): if filename.startswith(TOP_DIR_DOT): return None else: return filename[TOP_DIR_LEN:].lstrip(os.sep) elif filename.sta...
Default filter for filenames. Returns either a normalized filename or None. You can pass your own filter to init_types_collection().
352,836
def _collate_data(collation, first_axis, second_axis): if first_axis not in collation: collation[first_axis] = {} collation[first_axis]["create"] = 0 collation[first_axis]["modify"] = 0 collation[first_axis]["delete"] = 0 first = collation[first_axis] first[second_axis...
Collects information about the number of edit actions belonging to keys in a supplied dictionary of object or changeset ids. Parameters ---------- collation : dict A dictionary of OpenStreetMap object or changeset ids. first_axis : string An object or changeset key for the collatio...
352,837
def init_logger(log_requests=False): logger = logging.getLogger(__name__.split(".")[0]) for handler in logger.handlers: logger.removeHandler(handler) formatter = coloredlogs.ColoredFormatter(fmt="%(asctime)s: %(message)s") handler = logging.StreamHandler() handler.setLevel(logging.D...
Initialize the logger
352,838
def _readFromUrl(cls, url, writable): with open(cls._extractPathFromUrl(url), ) as readable: shutil.copyfileobj(readable, writable, length=cls.BUFFER_SIZE)
Writes the contents of a file to a source (writes url to writable) using a ~10Mb buffer. :param str url: A path as a string of the file to be read from. :param object writable: An open file object to write to.
352,839
def validate_pathname(filepath): if filepath == : return ValidatePathState.OK if len(filepath) > 1000: return ValidatePathState.LENGTH_ERROR filter2 = for c in filter2: if c in filepath: return ValidatePathState.CHAR_ERROR2 paths = rec_split_path(filepath) ...
检查路径中是否包含特殊字符. 百度网盘对路径/文件名的要求很严格: 1. 路径长度限制为1000 2. 路径中不能包含以下字符:\\ ? | " > < : * 3. 文件名或路径名开头结尾不能是“.”或空白字符,空白字符包括: \r, \n, \t, 空格, \0, \x0B @return, 返回的状态码: 0 表示正常
352,840
def load_module(self, name): if name in sys.modules: return sys.modules[name] raise DisabledIncludeError( % (self._module_prefix, name))
Load and return a module If the module is already loaded, the existing module is returned. Otherwise, raises :py:exc:`DisabledIncludeError`.
352,841
def augustus(args): p = OptionParser(augustus.__doc__) p.add_option("--species", default="maize", help="Use species model for prediction") p.add_option("--hintsfile", help="Hint-guided AUGUSTUS") p.add_option("--nogff3", default=False, action="store_true", help="Tu...
%prog augustus fastafile Run parallel AUGUSTUS. Final results can be reformatted using annotation.reformat.augustus().
352,842
def view(self, request, **kwargs): s video viewerseek self.method_check(request, allowed=[]) self.is_authenticated(request) response = None file_item_name = kwargs.get(, None) if file_item_name: mime = MimeTypes() url = urllib.pa...
allow a file to be viewed as opposed to download. This is particularly needed when a video file is stored in the fileservice and user wants to be able to use a view the video as opposed to having to download it first. It passes the serving of the file to nginx/apache which will return all the proper hea...
352,843
def wait(self, timeout=None): if timeout is None: timeout = self._timeout with self._cond: self._enter() index = self._count self._count += 1 try: if index + 1 == self._parties: ...
Wait for the barrier. When the specified number of threads have started waiting, they are all simultaneously awoken. If an 'action' was provided for the barrier, one of the threads will have executed that callback prior to returning. Returns an individual index number from 0 to 'parties...
352,844
def save(self, *args, **kwargs): old_instance = None if self.pk: old_instance = self.__class__._default_manager.get(pk=self.pk) self.slug = slugify(force_text(self.subject), allow_unicode=True) super().save(*args, **kwargs) ...
Saves the topic instance.
352,845
def parse_package(self, inputstring, addhash=True): if addhash: use_hash = self.genhash(True, inputstring) else: use_hash = None return self.parse(inputstring, self.file_parser, {"nl_at_eof_check": True}, {"header": "package", "use_hash": use_hash})
Parse package code.
352,846
def save_pickles(savefilename,*args,**kwargs): saving= True interrupted= False file, tmp_savefilename= tempfile.mkstemp() os.close(file) while saving: try: savefile= open(tmp_savefilename,) file_open= True if kwargs.get(,False) and not interrupted: ...
NAME: save_pickles PURPOSE: relatively safely save things to a pickle INPUT: savefilename - name of the file to save to; actual save operation will be performed on a temporary file and then that file will be shell mv'ed to savefilename +things to pickle (as many as you want!) OUT...
352,847
def reverse_file(infile, outfile): with open(infile, ) as inf: with open(outfile, ) as outf: reverse_fd(inf, outf)
Reverse the content of infile, write to outfile. Both infile and outfile are filenames or filepaths.
352,848
def active_io(self, iocb): if _debug: IOController._debug("active_io %r", iocb) if (iocb.ioState != IDLE) and (iocb.ioState != PENDING): raise RuntimeError("invalid state transition (currently %d)" % (iocb.ioState,)) iocb.ioState = ACTIVE
Called by a handler to notify the controller that a request is being processed.
352,849
def header(*msg, level=, separator=" ", print_out=print): out_string = separator.join(str(x) for x in msg) if level == : box_len = 80 print_out( + * (box_len + 2)) print_out("| %s" % out_string) print_out( + * (box_len + 2)) elif level == : print_out("...
Print header block in text mode
352,850
def iter_def_argspec(self): started_kwargs = False seen_vars = set() for var, value in self.argpairs: if var is None: var = value value = None if started_kwargs: raise SyntaxError( ...
Interpreting this literal as a function definition, yields pairs of (variable name as a string, default value as an AST node or None).
352,851
def async_steps(self, n): assert len(self._agents_to_act) == 0 for _ in range(n): self.async_step()
Progress simulation by running all agents *n* times asynchronously.
352,852
def detectTizenTV(self): return UAgentInfo.deviceTizen in self.__userAgent \ and UAgentInfo.smartTV1 in self.__userAgent
Return detection of a Tizen smart TV Detects if the current browser is on a Tizen smart TV.
352,853
def get_repo(repo, **kwargs): * _check_apt() ppa_auth = kwargs.get(, None) if repo.startswith() and __grains__[] in (, , ): dist = __grains__[] owner_name, ppa_name = repo[4:].split() if ppa_auth: auth_info = .format(ppa_auth) r...
Display a repo from the sources.list / sources.list.d The repo passed in needs to be a complete repo entry. CLI Examples: .. code-block:: bash salt '*' pkg.get_repo "myrepo definition"
352,854
def prepare_delete(self, node, method, position=None, save=True): if method is None: method = node._cte_node_delete_method if method == self.DELETE_METHOD_NONE: method = self.DEFAULT_DELETE_METHOD getattr(self, "prepare_delete_%s" % met...
Prepares a given :class:`CTENode` `node` for deletion, by executing the required deletion semantics (Pharaoh, Grandmother, or Monarchy). The `method` argument can be one of the valid :const:`DELETE_METHODS` choices. If it is :const:`DELETE_METHOD_NONE` or ``None``, then ...
352,855
def removerepeats(consens, arrayed): consens = "".join(consens).replace("-", "N") try: cons1, cons2 = consens.split("nnnn") split = consens.index("nnnn") arr1 = arrayed[:, :split] arr2 = arrayed[:, split+4:] except ValueError: cons1 = consens ...
Checks for interior Ns in consensus seqs and removes those that are at low depth, here defined as less than 1/3 of the average depth. The prop 1/3 is chosen so that mindepth=6 requires 2 base calls that are not in [N,-].
352,856
def stream_array(self, generator): def chunkify(generator): log.debug() yield .encode() try: yield jsonify(next(generator)).encode() except StopIteration: pass while True: ...
Helper function to stream content as an array of JSON values.
352,857
def describe(self, bucket, descriptor=None): if descriptor is not None: self.__descriptors[bucket] = descriptor else: descriptor = self.__descriptors.get(bucket) if descriptor is None: dataframe = self.__dataframes[bucket] ...
https://github.com/frictionlessdata/tableschema-pandas-py#storage
352,858
def jarFlags(target, source, env, for_signature): jarflags = env.subst(, target=target, source=source) for src in source: contents = src.get_text_contents() if contents[:16] == "Manifest-Version": if not in jarflags: return jarflags + break retu...
If we have a manifest, make sure that the 'm' flag is specified.
352,859
def set(self, section, option, value=None): if self._optcre is self.OPTCRE or value: if not isinstance(value, basestring): raise TypeError("option values must be strings") if value is not None: ...
Set an option. Extend ConfigParser.set: check for string values.
352,860
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): self.name = name self.fileExtension = extension with open(path, ) as f: self.text = f.read()
Generic File Read from File Method
352,861
def queue(self): queue = NotificationQueue() self._listeners.add(queue) yield queue self._listeners.remove(queue)
Get a queue of notifications Use it with Python with
352,862
def send_message(self, body, to, quiet=False, html_body=None): if to.get(): to[].append(body) else: if not quiet: logger.info( % (self.name, to[], body)) message = xmpp.protocol.Message(to=to[], body=body, typ=) if html_body: ...
Send a message to a single member
352,863
def _logoutclient(self, useruuid, clientuuid): self.log("Cleaning up client of logged in user.", lvl=debug) try: self._users[useruuid].clients.remove(clientuuid) if len(self._users[useruuid].clients) == 0: self.log("Last client of user disconnected.", lv...
Log out a client and possibly associated user
352,864
def overlay_images(self, canvas, data, whence=0.0): if not hasattr(canvas, ): return for obj in canvas.get_objects(): if hasattr(obj, ): obj.draw_image(self, data, whence=whence) elif obj.is_compound() and (obj != canvas): ...
Overlay data from any canvas image objects. Parameters ---------- canvas : `~ginga.canvas.types.layer.DrawingCanvas` Canvas containing possible images to overlay. data : ndarray Output array on which to overlay image data. whence See :meth:...
352,865
def sample(self, X, y, quantity=, sample_at_X=None, weights=None, n_draws=100, n_bootstraps=5, objective=): if quantity not in {, , }: raise ValueError("`quantity` must be one of , , ;" " got {}".format(quantity)) coef_draws = self._sampl...
Simulate from the posterior of the coefficients and smoothing params. Samples are drawn from the posterior of the coefficients and smoothing parameters given the response in an approximate way. The GAM must already be fitted before calling this method; if the model has not been fitted, ...
352,866
def stops(self, rt, direction): url = self.endpoint(, dict(rt=rt, dir=direction)) return self.response(url)
Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `s...
352,867
def _execute_for_run_dates(self, run_dates, ti_status, executor, pickle_id, start_date, session=None): for next_run_date in run_dates: dag_run = self._get_dag_run(next_run_date, session=session) tis_map = self._task_instances_for_dag_run(dag_run, ...
Computes the dag runs and their respective task instances for the given run dates and executes the task instances. Returns a list of execution dates of the dag runs that were executed. :param run_dates: Execution dates for dag runs :type run_dates: list :param ti_status: interna...
352,868
def task_list(task_array): tasks = [] for item, completed in task_array: task = "- [ ] " + esc_format(item) if completed: task = task[:3] + "X" + task[4:] tasks.append(task) return "\n".join(tasks)
Return a task list. The task_array should be 2-dimensional; the first item should be the task text, and the second the boolean completion state. >>> task_list([["Be born", True], ["Be dead", False]]) '- [X] Be born\\n- [ ] Be dead' When displayed using `print`, this will appear as: - [X]...
352,869
def turbulent_Petukhov_Kirillov_Popov(Re=None, Pr=None, fd=None): r C = 1.07 + 900./Re - (0.63/(1. + 10.*Pr)) return (fd/8.)*Re*Pr/(C + 12.7*(fd/8.)**0.5*(Pr**(2/3.) - 1.))
r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [2]_ and [3]_ as in [1]_. .. math:: Nu = \frac{(f/8)RePr}{C+12.7(f/8)^{1/2}(Pr^{2/3}-1)}\\ C = 1.07 + 900/Re - [0.63/(1+10Pr)] Parameters ---------- Re : float Reynolds number, [-] ...
352,870
def course_unregister_user(self, course, username=None): if username is None: username = self.session_username() self._database.aggregations.find_one_and_update( {"courseid": course.get_id(), "groups.students": username}, {"$pull": {"groups.$.studen...
Unregister a user to the course :param course: a Course object :param username: The username of the user that we want to unregister. If None, uses self.session_username()
352,871
def star_import_used_line_numbers(messages): for message in messages: if isinstance(message, pyflakes.messages.ImportStarUsed): yield message.lineno
Yield line number of star import usage.
352,872
def execute(self): from nbformat import read from nbconvert.exporters import export_script from cStringIO import StringIO notebook = read(StringIO(self.record.unpacked_contents), 4) script, resources = export_script(notebook) env_dict = {} exec (comp...
Convert the notebook to a python script and execute it, returning the local context as a dict
352,873
def is_wow64(self): try: wow64 = self.__wow64 except AttributeError: if (win32.bits == 32 and not win32.wow64): wow64 = False else: wow64 = self.get_process().is_wow64() self.__wow64 = wow64 return wow64
Determines if the thread is running under WOW64. @rtype: bool @return: C{True} if the thread is running under WOW64. That is, it belongs to a 32-bit application running in a 64-bit Windows. C{False} if the thread belongs to either a 32-bit application r...
352,874
def total_receipts(pronac, dt): dataframe = data.planilha_comprovacao project = dataframe.loc[dataframe[] == pronac] segment_id = project.iloc[0]["idSegmento"] segments_cache = data.segment_projects_agg segments_cache = segments_cache.to_dict(orient="index") mean = segments_cache[segment_...
This metric calculates the project total of receipts and compare it to projects in the same segment output: is_outlier: True if projects receipts is not compatible to others projects in the same segment total_receipts: absolute number of receipts maxim...
352,875
def index(self): root_dir = os.path.dirname(__file__) template_dir = os.path.join(root_dir, "templates", "gnotty") with open(os.path.join(template_dir, "base.html"), "r") as f: base = f.read() with open(os.path.join(template_dir, "chat.html"), "r") as f: ...
Loads the chat interface template when Django isn't being used, manually dealing with the Django template bits.
352,876
def write_contents(self, root_target, reduced_dependencies, chroot): def write_target_source(target, src): chroot.copy(os.path.join(get_buildroot(), target.target_base, src), os.path.join(self.SOURCE_ROOT, src)) while True: src = os.path.dirname(src) ...
Write contents of the target.
352,877
def add_permission_role(self, role, perm_view): if perm_view not in role.permissions: try: role.permissions.append(perm_view) role.save() log.info( c.LOGMSG_INF_SEC_ADD_PERMROLE.format(str(perm_view), role.name) ...
Add permission-ViewMenu object to Role :param role: The role object :param perm_view: The PermissionViewMenu object
352,878
def assert_has_calls(self, calls, any_order=False): if not any_order: if calls not in self.mock_calls: raise AssertionError( % (calls, self.mock_calls) ) return all_calls = list(self.mock_calls) ...
assert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. If `any_order` is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls. If `any_order` is True then the calls...
352,879
def _restore_expansion_state(self): def restore_tree_expansion(child_tree_iter, expansion_state): tree_item_path = self.history_tree_store.get_path(child_tree_iter) history_item = self.get_history_item_for_tree_iter(child_tree_iter) if tree_item_path a...
Iter recursively all tree items and restore expansion state
352,880
def validate_name(self, key, name): if not slug_pattern.match(name) or len(name) > 20: raise ValueError( ) return name
Validate name.
352,881
def database_backup(self, data_directory, *args, **kwargs): upload_good = False backup_stop_good = False while_offline = False start_backup_info = None if in kwargs: while_offline = kwargs.pop() try: if not while_offline: ...
Uploads a PostgreSQL file cluster to S3 or Windows Azure Blob Service Mechanism: just wraps _upload_pg_cluster_dir with start/stop backup actions with exception handling. In particular there is a 'finally' block to stop the backup in most situations.
352,882
def save_all(self): initial_index = self.currentIndex() for i in range(self.count()): try: self.setCurrentIndex(i) self.save_current() except AttributeError: pass self.setCurrentIndex(initial_index)
Save all editors.
352,883
def log_print_request(logger, method, url, query_params=None, headers=None, body=None): log_msg = log_msg += % method log_msg += % url if query_params is not None: log_msg += .format(str(query_params)) if headers is not None: log_msg += .format(str(headers)) if body is n...
Log an HTTP request data. :param logger: Logger to use :param method: HTTP method :param url: URL :param query_params: Query parameters in the URL :param headers: Headers (dict) :param body: Body (raw body, string) :return: None
352,884
def load(self, executable): if self.status == : warnings.warn("Overwriting previously loaded executable.") assert self.status in [, , ] self._variables_shim = {} self._executable = executable self._bitstrings = None self.status = return self
Initialize a QAM into a fresh state. :param executable: Load a compiled executable onto the QAM.
352,885
def connect(self, attempts=20, delay=0.5): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) with closing(sock): sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) discover_packet = build_packet(REQ_GATEWAY, ...
Connects to a gateway, blocking until a connection is made and bulbs are found. Step 1: send a gateway discovery packet to the broadcast address, wait until we've received some info about the gateway. Step 2: connect to a discovered gateway, wait until the connection has been c...
352,886
def path_helper(self, operations, view, app=None, **kwargs): rule = self._rule_for_view(view, app=app) operations.update(yaml_utils.load_operations_from_docstring(view.__doc__)) if hasattr(view, ) and issubclass(view.view_class, MethodView): for method in view.methods: ...
Path helper that allows passing a Flask view function.
352,887
def date_browser_selection_changed(self, selected_indexes): partial_date_filters = list() for index, parent_row, parent_id in selected_indexes: item_model_controller = self.item_model_controller tree_node = item_model_controller.item_value("tree_node", index, parent_id)...
Called to handle selection changes in the tree widget. This method should be connected to the on_selection_changed event. This method builds a list of keys represented by all selected items. It then provides date_filter to filter data items based on the list of keys. It then sets th...
352,888
def create_uber_client(credentials): oauth2credential = OAuth2Credential( client_id=credentials.get(), access_token=credentials.get(), expires_in_seconds=credentials.get(), scopes=credentials.get(), grant_type=credentials.get(), redirect_url=credentials.get(), ...
Create an UberRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (UberRidesClient) An authorized UberRidesClient to access API resources.
352,889
def wait_for_ilo_after_reset(ilo_object): is_ilo_up_after_reset = lambda: ilo_object.get_product_name() is not None is_ilo_up_after_reset.__name__ = wait_for_operation_to_complete( is_ilo_up_after_reset, failover_exc=exception.IloConnectionError, failover_msg= )
Continuously polls for iLO to come up after reset.
352,890
def update_sums(self, r, i, j, data1, data2, sum1, sum2, N=None, centers_sum=None): sum1_ij, sum2_ij = compute_sum_values(i, j, data1, data2) digr = self.digitize(r, i, j, data1, data2) if len(digr) == 3 and isinstance(digr[1], dict): dig, paircoords, wei...
The main function that digitizes the pair counts, calls bincount for the appropriate `sum1` and `sum2` values, and adds them to the input arrays, will modify sum1, sum2, N, and centers_sum inplace.
352,891
def get_owned_repo_issues(self, tag): issues = {} for issue in self.client.get_issues(*tag.split()): issues[issue[]] = (tag, issue) return issues
Grab all the issues
352,892
def record(self, ekey, entry, diff=False): if ekey not in self.entities: self.entities[ekey] = [] if diff and len(self.entities[ekey]) > 0: from acorn.logging.diff import cascade, compress sequence = [e["c"] for e in self.en...
Records the specified entry to the key-value store under the specified entity key. Args: ekey (str): fqdn/uuid of the method/object to store the entry for. entry (dict): attributes and values gleaned from the execution. diff (bool): when True, the "c" element of `ent...
352,893
def _get_model_fitting(self, con_est_id): for (mpe_id, pe_ids), contrasts in self.contrasts.items(): for contrast in contrasts: if contrast.estimation.id == con_est_id: model_fitting_id = mpe_id pe_map_ids = pe_ids ...
Retreive model fitting that corresponds to contrast with identifier 'con_id' from the list of model fitting objects stored in self.model_fittings
352,894
def close_connection(self): if self.port: self.stop() self.logger.debug("Close port " % self.comport, extra={: }) self.port.close() self.port = False
Closes serial port connection. :return: Nothing
352,895
def select(self, cmd, *args, **kwargs): self.cursor.execute(cmd, *args, **kwargs) return self.cursor.fetchall()
Execute the SQL command and return the data rows as tuples
352,896
def tag(tagger, args): for l in args.input: words = l.strip().split() line_annotations = [u"{:<16}{:<5}".format(w,p) for w, p in tagger.annotate(words)] _print(u"\n".join(line_annotations)) _print(u"")
Chunk named entities.
352,897
def to_otu(self, biom_id=None): otu_format = "Biological Observation Matrix 1.0.0" otu_url = "http://biom-format.org" otu = OrderedDict( { "id": biom_id, "format": otu_format, "format_url": otu_url, "...
Converts a list of objects associated with a classification result into a `dict` resembling an OTU table. Parameters ---------- biom_id : `string`, optional Optionally specify an `id` field for the generated v1 BIOM file. Returns ------- otu_table : ...
352,898
def create_command_history_subscription(self, on_data=None, timeout=60): return self._client.create_command_history_subscription( issued_command=self, on_data=on_data, timeout=timeout)
Create a new command history subscription for this command. :param on_data: Function that gets called with :class:`.CommandHistory` updates. :param float timeout: The amount of seconds to wait for the request to complete. :return: Future th...
352,899
def mean_interval(self, name, alpha=_alpha, **kwargs): data = self.get(name,**kwargs) return mean_interval(data,alpha)
Interval assuming gaussian posterior.