Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
4,800
def connect_ssh(*args, **kwargs): client = SSHClient() client.connect(*args, **kwargs) return client
Create a new connected :class:`SSHClient` instance. All arguments are passed to :meth:`SSHClient.connect`.
4,801
def _iflat_tasks_wti(self, status=None, op="==", nids=None, with_wti=True): nids = as_set(nids) if status is None: for wi, work in enumerate(self): for ti, task in enumerate(work): if nids and task.node_id not in nids: continue ...
Generators that produces a flat sequence of task. if status is not None, only the tasks with the specified status are selected. nids is an optional list of node identifiers used to filter the tasks. Returns: (task, work_index, task_index) if with_wti is True else task
4,802
def check_network_health(self): r health = HealthDict() health[] = [] health[] = [] health[] = [] health[] = [] health[] = [] health[] = [] health[] = [] hits = sp.where(self[] > self.Np - 1)[0] if sp.size(hits) > 0: ...
r""" This method check the network topological health by checking for: (1) Isolated pores (2) Islands or isolated clusters of pores (3) Duplicate throats (4) Bidirectional throats (ie. symmetrical adjacency matrix) (5) Headless throats Return...
4,803
def cli(ctx, timeout, proxy, output, quiet, lyric, again): ctx.obj = NetEase(timeout, proxy, output, quiet, lyric, again)
A command tool to download NetEase-Music's songs.
4,804
def flush_to_index(self): assert self._smref is not None assert not isinstance(self._file_or_files, BytesIO) sm = self._smref() if sm is not None: index = self._index if index is None: index = sm.repo.index ...
Flush changes in our configuration file to the index
4,805
def _getphoto_location(self,pid): logger.debug(%(pid)) lat=None lon=None accuracy=None resp=self.fb.photos_geo_getLocation(photo_id=pid) if resp.attrib[]!=: logger.error("%s - fb: photos_geo_getLocation failed with status: %s",\ ...
Asks fb for photo location information returns tuple with lat,lon,accuracy
4,806
def view_page(name=None): if request.method == : if name is None: if len(request.forms.filename) > 0: name = request.forms.filename if name is not None: filename = "{0}.rst".format(name) file_handle = open(filename, ) ...
Serve a page name. .. note:: this is a bottle view * if the view is called with the POST method, write the new page content to the file, commit the modification and then display the html rendering of the restructured text file * if the view is called with the GET method, directly display the ...
4,807
def send(node_name): my_data = nago.core.get_my_info() if not node_name: node_name = nago.settings.get() node = nago.core.get_node(node_name) json_params = {} json_params[] = node_name json_params[] = "node_info" for k, v in my_data.items(): nago.core.log("sending %s to ...
Send our information to a remote nago instance Arguments: node -- node_name or token for the node this data belongs to
4,808
def logger_init(level): levellist = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] handler = logging.StreamHandler() fmt = ( ) handler.setFormatter(logging.Formatter(fmt)) logger = logging.root logger.addHandler(handler) logger.setLevel(levellist[level])
Initialize the logger for this thread. Sets the log level to ERROR (0), WARNING (1), INFO (2), or DEBUG (3), depending on the argument `level`.
4,809
def serialize(self): result = self.to_project_config(with_packages=True) result.update(self.to_profile_info(serialize_credentials=True)) result[] = deepcopy(self.cli_vars) return result
Serialize the full configuration to a single dictionary. For any instance that has passed validate() (which happens in __init__), it matches the Configuration contract. Note that args are not serialized. :returns dict: The serialized configuration.
4,810
def traverse(self, id_=None): if id_ is None: id_ = self.group nodes = r_client.smembers(_children_key(id_)) while nodes: current_id = nodes.pop() details = r_client.get(current_id) if details is None: r_...
Traverse groups and yield info dicts for jobs
4,811
async def connect( self, hostname: str = None, port: int = None, source_address: DefaultStrType = _default, timeout: DefaultNumType = _default, loop: asyncio.AbstractEventLoop = None, use_tls: bool = None, validate_certs: bool = None, client_cert: ...
Initialize a connection to the server. Options provided to :meth:`.connect` take precedence over those used to initialize the class. :keyword hostname: Server name (or IP) to connect to :keyword port: Server port. Defaults to 25 if ``use_tls`` is False, 465 if ``use_tls`` i...
4,812
def update(self, other=None, **kwargs): if other is None: other = () if hasattr(other, ): for key in other: self._update(key, other[key]) else: for key,value in other: self._update(key, value) for key,value in...
x.update(E, **F) -> None. update x from trie/dict/iterable E or F. If E has a .keys() method, does: for k in E: x[k] = E[k] If E lacks .keys() method, does: for (k, v) in E: x[k] = v In either case, this is followed by: for k in F: x[k] = F[k]
4,813
def formatted(text, *args, **kwargs): if not text or "{" not in text: return text strict = kwargs.pop("strict", True) max_depth = kwargs.pop("max_depth", 3) objects = list(args) + [kwargs] if kwargs else args[0] if len(args) == 1 else args if not objects: return text definit...
Args: text (str | unicode): Text to format *args: Objects to extract values from (as attributes) **kwargs: Optional values provided as named args Returns: (str): Attributes from this class are expanded if mentioned
4,814
def _isstring(dtype): return dtype.type == numpy.unicode_ or dtype.type == numpy.string_
Given a numpy dtype, determines whether it is a string. Returns True if the dtype is string or unicode.
4,815
def parse(self) -> Statement: self.opt_separator() start = self.offset res = self.statement() if res.keyword not in ["module", "submodule"]: self.offset = start raise UnexpectedInput(self, " or ") if self.name is not None and res.argument != self....
Parse a complete YANG module or submodule. Args: mtext: YANG module text. Raises: EndOfInput: If past the end of input. ModuleNameMismatch: If parsed module name doesn't match `self.name`. ModuleRevisionMismatch: If parsed revision date doesn't match `se...
4,816
def username(anon, obj, field, val): return anon.faker.user_name(field=field)
Generates a random username
4,817
def max_brightness(self): self._max_brightness, value = self.get_cached_attr_int(self._max_brightness, ) return value
Returns the maximum allowable brightness value.
4,818
def snyder_opt(self, structure): nsites = structure.num_sites volume = structure.volume num_density = 1e30 * nsites / volume return 1.66914e-23 * \ (self.long_v(structure) + 2.*self.trans_v(structure))/3. \ / num_density ** (-2./3.) * (1 - nsites ** (-1./...
Calculates Snyder's optical sound velocity (in SI units) Args: structure: pymatgen structure object Returns: Snyder's optical sound velocity (in SI units)
4,819
def set_gss_host(self, gss_host, trust_dns=True, gssapi_requested=True): if not gssapi_requested: return if gss_host is None: gss_host = self.hostname if trust_dns and gss_host is not None: gss_host = socket.getfqdn...
Normalize/canonicalize ``self.gss_host`` depending on various factors. :param str gss_host: The explicitly requested GSS-oriented hostname to connect to (i.e. what the host's name is in the Kerberos database.) Defaults to ``self.hostname`` (which will be the 'real' target ho...
4,820
def rnaseq2ga(quantificationFilename, sqlFilename, localName, rnaType, dataset=None, featureType="gene", description="", programs="", featureSetNames="", readGroupSetNames="", biosampleId=""): readGroupSetName = "" if readGroupSetNames: readGroupSetName = r...
Reads RNA Quantification data in one of several formats and stores the data in a sqlite database for use by the GA4GH reference server. Supports the following quantification output types: Cufflinks, kallisto, RSEM.
4,821
def get_links(self, recall, timeout): for _ in range(recall): try: soup = BeautifulSoup(self.source) out_links = [] for tag in soup.findAll(["a", "link"], href=True): tag["href"] = urljoin(self.url, tag["href"]) ...
Gets links in page :param recall: max times to attempt to fetch url :param timeout: max times :return: array of out_links
4,822
def disable_signing(self): self.mav.signing.secret_key = None self.mav.signing.sign_outgoing = False self.mav.signing.allow_unsigned_callback = None self.mav.signing.link_id = 0 self.mav.signing.timestamp = 0
disable MAVLink2 signing
4,823
def view_hmap(token, dstore): try: poe = valid.probability(token.split()[1]) except IndexError: poe = 0.1 mean = dict(extract(dstore, ))[] oq = dstore[] hmap = calc.make_hmap_array(mean, oq.imtls, [poe], len(mean)) dt = numpy.dtype([(, U32)] + [(imt, F32) for imt in oq.imtls...
Display the highest 20 points of the mean hazard map. Called as $ oq show hmap:0.1 # 10% PoE
4,824
def _popup(self): res = () for child in self.formulas: if type(child) == type(self): superchilds = child.formulas res += superchilds else: res += (child, ) return tuple(res)
recursively find commutative binary operator among child formulas and pop up them at the same level
4,825
def load_config(path): path = os.path.abspath(path) if os.path.isdir(path): config, wordlists = _load_data(path) elif os.path.isfile(path): config = _load_config(path) wordlists = {} else: raise InitializationError(.format(path)) for name, wordlist in wordlists.i...
Loads configuration from a path. Path can be a json file, or a directory containing config.json and zero or more *.txt files with word lists or phrase lists. Returns config dict. Raises InitializationError when something is wrong.
4,826
def to_json(self): return json.dumps({ "statistics": self.get_statistics() , "authors": [json.loads(author.to_json()) for author in self.get_authors()] }, indent=2)
Serialises the content of the KnowledgeBase as JSON. :return: TODO
4,827
def start(self, *args, **kwargs): if self.is_running(): raise RuntimeError() self._running = self.run(*args, **kwargs) try: yielded = next(self._running) except StopIteration: raise TypeError() if yielded is not None: raise...
Starts the instance. :raises RuntimeError: has been already started. :raises TypeError: :meth:`run` is not canonical.
4,828
def multchoicebox(message=, title=, choices=[]): return psidialogs.multi_choice(message=message, title=title, choices=choices)
Original doc: Present the user with a list of choices. allow him to select multiple items and return them in a list. if the user doesn't choose anything from the list, return the empty list. return None if he cancelled selection.
4,829
def count(self): return functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds))
Total number of array cells
4,830
def get_resource_siblings(raml_resource): path = raml_resource.path return [res for res in raml_resource.root.resources if res.path == path]
Get siblings of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode.
4,831
def nsx_controller_connection_addr_port(self, **kwargs): config = ET.Element("config") nsx_controller = ET.SubElement(config, "nsx-controller", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(nsx_controller, "name") name_key.text = kwargs.pop() con...
Auto Generated Code
4,832
def mag_to_fnu(self, mag): if len(band) != 2 or band[1] != : raise ValueError( + band) return abmag_to_fnu_cgs(mag)
SDSS *primed* magnitudes to F_ν. The primed magnitudes are the "USNO" standard-star system defined in Smith+ (2002AJ....123.2121S) and Fukugita+ (1996AJ....111.1748F). This system is anchored to the AB magnitude system, and as far as I can tell it is not known to have measurable offsets ...
4,833
def loads(string, triples=False, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) return list(codec.iterdecode(string, triples=triples))
Deserialize a list of PENMAN-encoded graphs from *string*. Args: string: a string containing graph data triples: if True, read graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns: a li...
4,834
def search_dashboard_deleted_for_facet(self, facet, **kwargs): kwargs[] = True if kwargs.get(): return self.search_dashboard_deleted_for_facet_with_http_info(facet, **kwargs) else: (data) = self.search_dashboard_deleted_for_facet_with_http_info(facet, **kwarg...
Lists the values of a specific facet over the customer's deleted dashboards # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_dashboard_deleted_for_facet(facet, a...
4,835
def analyze_text( self, text, **kwargs ): SYHSYHBIOs text; Regardless the return type, a layer named NOUN_CHUNKS will be added to the input Text containing noun phrase annotations; cutPhrasesforce_parsingsyntax_layercutMaxThresholdreturn_type Unex...
Analyzes given Text for noun phrase chunks. As result of analysis, a layer NOUN_CHUNKS will be attached to the input Text object, containing a noun phrases detected from the Text; Note: for preprocessing the Text, MaltParser is used by default. In order to obtain a de...
4,836
def output_to_table(obj, olist=, oformat=, table_ends=False, prefix=""): para = "" property_list = [] if olist == : property_list = obj.inputs elif olist == : for item in obj.__dict__: if "_" != item[0]: property_list.append(item) for item in property...
Compile the properties to a table. :param olist: list, Names of the parameters to be in the output table :param oformat: str, The type of table to be output :param table_ends: bool, Add ends to the table :param prefix: str, A string to be added to the start of each parameter name :return: para, str...
4,837
def main(): parser = OptionParser() parser.add_option(, , help=, dest=, type=, default=) parser.add_option(, , help=, dest=, type=, ...
Main entry point
4,838
def get_filepath(self, filename): return os.path.join(self.parent_folder, self.product_id, self.add_file_extension(filename)).replace(, )
Creates file path for the file. :param filename: name of the file :type filename: str :return: filename with path on disk :rtype: str
4,839
async def _connect(self, connection_lost_callbk=None): self.connection_lost_callbk = connection_lost_callbk url = self._config[] LOG.info("Connecting to ElkM1 at %s", url) scheme, dest, param, ssl_context = parse_url(url) conn = partial(Connection, self.loop, self._conne...
Asyncio connection to Elk.
4,840
def add_install_defaults(args): if attr == "genomes" and len(args.genomes) > 0: continue for x in default_args.get(attr, []): x = str(x) new_val = getattr(args, attr) if x not in getattr(args, attr): new_val.append(x) ...
Add any saved installation defaults to the upgrade.
4,841
def set_line_join(self, line_join): cairo.cairo_set_line_join(self._pointer, line_join) self._check_status()
Set the current :ref:`LINE_JOIN` within the cairo context. As with the other stroke parameters, the current line cap style is examined by :meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`, but does not have any effect during path construction. The default line c...
4,842
def get_blank_row(self, filler="-", splitter="+"): return self.get_pretty_row( ["" for _ in self.widths], filler, splitter, )
Gets blank row :param filler: Fill empty columns with this char :param splitter: Separate columns with this char :return: Pretty formatted blank row (with no meaningful data in it)
4,843
def filter_by_analysis_period(self, analysis_period): self._check_analysis_period(analysis_period) _filtered_data = self.filter_by_moys(analysis_period.moys) _filtered_data.header._analysis_period = analysis_period return _filtered_data
Filter a Data Collection based on an analysis period. Args: analysis period: A Ladybug analysis period Return: A new Data Collection with filtered data
4,844
def hardware_custom_profile_kap_custom_profile_xstp_xstp_hello_interval(self, **kwargs): config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") custom_profile = ET.SubElement(hardware, "custom-profile") kap_custo...
Auto Generated Code
4,845
def setSignals(self, vehID, signals): self._connection._sendIntCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_SIGNALS, vehID, signals)
setSignals(string, integer) -> None Sets an integer encoding the state of the vehicle's signals.
4,846
def pix2vec(nside, ipix, nest=False): lon, lat = healpix_to_lonlat(ipix, nside, order= if nest else ) return ang2vec(*_lonlat_to_healpy(lon, lat))
Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.
4,847
def getSegmentOnCell(self, c, i, segIdx): segList = self.cells4.getNonEmptySegList(c,i) seg = self.cells4.getSegment(c, i, segList[segIdx]) numSyn = seg.size() assert numSyn != 0 result = [] result.append([int(segIdx), bool(seg.isSequenceSegment()), seg.getPositiveA...
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`.
4,848
def append(self, data: Union[bytes, bytearray, memoryview]) -> None: size = len(data) if size > self._large_buf_threshold: if not isinstance(data, memoryview): data = memoryview(data) self._buffers.append((True, data)) elif size > 0: i...
Append the given piece of data (should be a buffer-compatible object).
4,849
def preprocess(self): s convertible. ' self.processed_tables = [] self.flags_by_table = [] self.units_by_table = [] for worksheet, rtable in enumerate(self.raw_tables): ptable, flags, units = self.preprocess_worksheet(rtable, worksheet) self.proces...
Performs initial cell conversions to standard types. This will strip units, scale numbers, and identify numeric data where it's convertible.
4,850
def p_sigtypes(self, p): p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
sigtypes : sigtypes sigtype
4,851
def document_from_string(self, schema, request_string): key = self.get_key_for_schema_and_document_string(schema, request_string) if key not in self.cache_map: self.cache_map[key] = self.fallback_backend.document_from_string( schema, request_str...
This method returns a GraphQLQuery (from cache if present)
4,852
def get_bins_by_resource(self, resource_id): mgr = self._get_provider_manager(, local=True) lookup_session = mgr.get_bin_lookup_session(proxy=self._proxy) return lookup_session.get_bins_by_ids( self.get_bin_ids_by_resource(resource_id))
Gets the list of ``Bin`` objects mapped to a ``Resource``. arg: resource_id (osid.id.Id): ``Id`` of a ``Resource`` return: (osid.resource.BinList) - list of bins raise: NotFound - ``resource_id`` is not found raise: NullArgument - ``resource_id`` is ``null`` raise: Operati...
4,853
def calc_acceleration(xdata, dt): acceleration = _np.diff(_np.diff(xdata))/dt**2 return acceleration
Calculates the acceleration from the position Parameters ---------- xdata : ndarray Position data dt : float time between measurements Returns ------- acceleration : ndarray values of acceleration from position 2 to N.
4,854
def _get_layer_converter_fn(layer, add_custom_layers = False): layer_type = type(layer) if layer_type in _KERAS_LAYER_REGISTRY: convert_func = _KERAS_LAYER_REGISTRY[layer_type] if convert_func is _layers2.convert_activation: act_name = _layers2._get_activation_name_from_keras_la...
Get the right converter function for Keras
4,855
def text(what="sentence", *args, **kwargs): if what == "character": return character(*args, **kwargs) elif what == "characters": return characters(*args, **kwargs) elif what == "word": return word(*args, **kwargs) elif what == "words": return words(*args, **kwargs) ...
An aggregator for all above defined public methods.
4,856
def reference_to_greatcircle(reference_frame, greatcircle_frame): pole = greatcircle_frame.pole.transform_to(coord.ICRS) ra0 = greatcircle_frame.ra0 center = greatcircle_frame.center R_rot = rotation_matrix(greatcircle_frame.rotation, ) if not np.isnan(ra0): xaxis = np.array...
Convert a reference coordinate to a great circle frame.
4,857
def QA_util_code_tolist(code, auto_fill=True): if isinstance(code, str): if auto_fill: return [QA_util_code_tostr(code)] else: return [code] elif isinstance(code, list): if auto_fill: return [QA_util_code_tostr(item) for item in code] el...
转换code==> list Arguments: code {[type]} -- [description] Keyword Arguments: auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True}) Returns: [list] -- [description]
4,858
def _compute_dependencies(self): from _markerlib import compile as compile_marker dm = self.__dep_map = {None: []} reqs = [] for req in self._parsed_pkg_info.get_all() or []: distvers, mark = self._preparse_requirement(req) parsed = parse_requir...
Recompute this distribution's dependencies.
4,859
def previous(self, cli): if len(self.focus_stack) > 1: try: return self[self.focus_stack[-2]] except KeyError: pass
Return the previously focussed :class:`.Buffer` or `None`.
4,860
def foreach(self, f): from pyspark.rdd import _wrap_function from pyspark.serializers import PickleSerializer, AutoBatchedSerializer from pyspark.taskcontext import TaskContext if callable(f): def func_without_process(_, itera...
Sets the output of the streaming query to be processed using the provided writer ``f``. This is often used to write the output of a streaming query to arbitrary storage systems. The processing logic can be specified in two ways. #. A **function** that takes a row as input. This is a...
4,861
def mu(self): mu = self._models[0].mu assert all([mu == model.mu for model in self._models]) return mu
See docs for `Model` abstract base class.
4,862
def set_url_part(url, **kwargs): d = parse_url_to_dict(url) d.update(kwargs) return unparse_url_dict(d)
Change one or more parts of a URL
4,863
def add_oxidation_state_by_site_fraction(structure, oxidation_states): try: for i, site in enumerate(structure): new_sp = collections.defaultdict(float) for j, (el, occu) in enumerate(get_z_ordered_elmap(site .species)): ...
Add oxidation states to a structure by fractional site. Args: oxidation_states (list): List of list of oxidation states for each site fraction for each site. E.g., [[2, 4], [3], [-2], [-2], [-2]]
4,864
def clear_cached_values(self): self._prof_interp = None self._prof_y = None self._prof_z = None self._marg_interp = None self._marg_z = None self._post = None self._post_interp = None self._interp = None self._ret_type = None
Removes all of the cached values and interpolators
4,865
def filter_data(data, kernel, mode=, fill_value=0.0, check_normalization=False): from scipy import ndimage if kernel is not None: if isinstance(kernel, Kernel2D): kernel_array = kernel.array else: kernel_array = kernel if check_normalizatio...
Convolve a 2D image with a 2D kernel. The kernel may either be a 2D `~numpy.ndarray` or a `~astropy.convolution.Kernel2D` object. Parameters ---------- data : array_like The 2D array of the image. kernel : array-like (2D) or `~astropy.convolution.Kernel2D` The 2D kernel used t...
4,866
def register_surrogateescape(): if six.PY3: return try: codecs.lookup_error(FS_ERRORS) except LookupError: codecs.register_error(FS_ERRORS, surrogateescape_handler)
Registers the surrogateescape error handler on Python 2 (only)
4,867
def get_clients(self, limit=None, offset=None): data = {} if limit: data[] = limit if offset: data[] = offset result = self._request(, , data=json.dumps(data)) return result.json()
Returns a list of clients.
4,868
def hmget(self, name, keys, *args): "Returns a list of values ordered identically to ``keys``" args = list_or_args(keys, args) return self.execute_command(, name, *args)
Returns a list of values ordered identically to ``keys``
4,869
def p_subidentifiers(self, p): n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
subidentifiers : subidentifiers subidentifier | subidentifier
4,870
def run(path, code=None, params=None, ignore=None, select=None, **meta): complexity = params.get(, 10) no_assert = params.get(, False) show_closures = params.get(, False) visitor = ComplexityVisitor.from_code(code, no_assert=no_assert) blocks = visitor.blocks if...
Check code with Radon. :return list: List of errors.
4,871
def obj_to_json(self, file_path=None, indent=2, sort_keys=False, quote_numbers=True): data = [row.obj_to_ordered_dict(self.columns) for row in self] if not quote_numbers: for row in data: for k, v in row.items(): if isinstance...
This will return a str of a json list. :param file_path: path to data file, defaults to self's contents if left alone :param indent: int if set to 2 will indent to spaces and include line breaks. :param sort_keys: so...
4,872
def hr_size(num, suffix=) -> str: for unit in : if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit if unit != else , suffix) num /= 1024.0 return "%.1f%s%s" % (num, , suffix)
Human-readable data size From https://stackoverflow.com/a/1094933 :param num: number of bytes :param suffix: Optional size specifier :return: Formatted string
4,873
def output(self, stream, disabletransferencoding = None): if self._sendHeaders: raise HttpProtocolException() self.outputstream = stream try: content_length = len(stream) except Exception: pass else: self.header(b, str(cont...
Set output stream and send response immediately
4,874
def encrypt(self, plaintext): if not isinstance(plaintext, int): raise ValueError() if not self.in_range.contains(plaintext): raise OutOfRangeError() return self.encrypt_recursive(plaintext, self.in_range, self.out_range)
Encrypt the given plaintext value
4,875
def add_access_policy_filter(request, query, column_name): q = d1_gmn.app.models.Subject.objects.filter( subject__in=request.all_subjects_set ).values() filter_arg = .format(column_name) return query.filter(**{filter_arg: q})
Filter records that do not have ``read`` or better access for one or more of the active subjects. Since ``read`` is the lowest access level that a subject can have, this method only has to filter on the presence of the subject.
4,876
def xml_endtag (self, name): self.level -= 1 assert self.level >= 0 self.write(self.indent*self.level) self.writeln(u"</%s>" % xmlquote(name))
Write XML end tag.
4,877
def get_angle(self, verify = False): LSB = self.bus.read_byte_data(self.address, self.angle_LSB) MSB = self.bus.read_byte_data(self.address, self.angle_MSB) DATA = (MSB << 6) + LSB if not verify: return (360.0 / 2**14) * DATA else: status = self....
Retuns measured angle in degrees in range 0-360.
4,878
def interconnect_link_topologies(self): if not self.__interconnect_link_topologies: self.__interconnect_link_topologies = InterconnectLinkTopologies(self.__connection) return self.__interconnect_link_topologies
Gets the InterconnectLinkTopologies API client. Returns: InterconnectLinkTopologies:
4,879
def DiscreteUniform(n=10,LB=1,UB=99,B=100): B = 100 s = [0]*n for i in range(n): s[i] = random.randint(LB,UB) return s,B
DiscreteUniform: create random, uniform instance for the bin packing problem.
4,880
def iflatten(seq, isSeq=isSeq): r for elt in seq: if isSeq(elt): for x in iflatten(elt, isSeq): yield x else: yield elt
r"""Like `flatten` but lazy.
4,881
def _mark_started(self): log = self._params.get(, self._discard) now = time.time() self._started = now limit = self._config_running.get() try: limit = float(_fmt_context(self._get(limit, default=), self._context)) if limit > 0: l...
Set the state information for a task once it has completely started. In particular, the time limit is applied as of this time (ie after and start delay has been taking.
4,882
def get(key, value=None, conf_file=_DEFAULT_CONF): ** current_conf = _parse_conf(conf_file) stanza = current_conf.get(key, False) if value: if stanza: return stanza.get(value, False) _LOG.warning("Block not present or empty.", key) return stanza
Get the value for a specific configuration line. :param str key: The command or stanza block to configure. :param str value: The command value or command of the block specified by the key parameter. :param str conf_file: The logrotate configuration file. :return: The value for a specific configuration...
4,883
def parse_string(self, timestr, subfmts): components = (, , ) defaults = (None, 1, 1, 0) try: idot = timestr.rindex() except: fracday = 0.0 else: timestr, fracday = timestr[:idot], timestr[idot:] ...
Read time from a single string, using a set of possible formats.
4,884
def classify_tangent_intersection( intersection, nodes1, tangent1, nodes2, tangent2 ): dot_prod = np.vdot(tangent1[:, 0], tangent2[:, 0]) curvature1 = _curve_helpers.get_curvature(nodes1, tangent1, intersection.s) curvature2 = _curve_helpers.get_curvature(nodes2, tangent2, intersecti...
Helper for func:`classify_intersection` at tangencies. .. note:: This is a helper used only by :func:`classify_intersection`. Args: intersection (.Intersection): An intersection object. nodes1 (numpy.ndarray): Control points for the first curve at the intersection. ...
4,885
def get_flight_rules(vis: Number, ceiling: Cloud) -> int: if not vis: return 2 if vis.repr == or vis.repr.startswith(): vis = 10 elif vis.repr.startswith(): vis = 0 elif len(vis.repr) == 4: vis = vis.value * 0.000621371 else: vis = vis.va...
Returns int based on current flight rules from parsed METAR data 0=VFR, 1=MVFR, 2=IFR, 3=LIFR Note: Common practice is to report IFR if visibility unavailable
4,886
def calc_avr_uvr_v1(self): con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess for i in range(2): if flu.h <= (con.hm+der.hv[i]): flu.avr[i] = 0. flu.uvr[i] = 0. else: flu.avr[i]...
Calculate the flown through area and the wetted perimeter of both outer embankments. Note that each outer embankment lies beyond its foreland and that all water flowing exactly above the a embankment is added to |AVR|. The theoretical surface seperating water above the foreland from water above its...
4,887
def energy_ratio_by_chunks(x, param): res_data = [] res_index = [] full_series_energy = np.sum(x ** 2) for parameter_combination in param: num_segments = parameter_combination["num_segments"] segment_focus = parameter_combination["segment_focus"] assert segment_focus < num_...
Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole series. Takes as input parameters the number num_segments of segments to divide the series into and segment_focus which is the segment number (starting at zero) to return a feature on. ...
4,888
def connect(self, port=None, baud_rate=115200): if isinstance(port, types.StringTypes): ports = [port] else: ports = port if not ports: ports = serial_ports().index.tolist() if not ports: ...
Parameters ---------- port : str or list-like, optional Port (or list of ports) to try to connect to as a DMF Control Board. baud_rate : int, optional Returns ------- str Port DMF control board was connected on. Raises ...
4,889
def standard_parsing_functions(Block, Tx): def stream_block(f, block): assert isinstance(block, Block) block.stream(f) def stream_blockheader(f, blockheader): assert isinstance(blockheader, Block) blockheader.stream_header(f) def stream_tx(f, tx): assert isinst...
Return the standard parsing functions for a given Block and Tx class. The return value is expected to be used with the standard_streamer function.
4,890
def save(self, index=None, force=False): editorstack = self.get_current_editorstack() return editorstack.save(index=index, force=force)
Save file
4,891
def pverb(self, *args, **kwargs): if not self.verbose: return self.pstd(*args, **kwargs)
Console verbose message to STDOUT
4,892
def createPREMISEventXML(eventType, agentIdentifier, eventDetail, eventOutcome, outcomeDetail=None, eventIdentifier=None, linkObjectList=[], eventDate=None): eventXML = etree.Element(PREMIS + "event", nsmap=PREMIS_NSMAP) eventIDXML = etree.SubElement(event...
Actually create our PREMIS Event XML
4,893
def get_instance(self, payload): return NotificationInstance(self._version, payload, account_sid=self._solution[], )
Build an instance of NotificationInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.notification.NotificationInstance :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance
4,894
def _update_port_locations(self, initial_coordinates): particles = list(self.particles()) for port in self.all_ports(): if port.anchor: idx = particles.index(port.anchor) shift = particles[idx].pos - initial_coordinates[idx] port.trans...
Adjust port locations after particles have moved Compares the locations of Particles between 'self' and an array of reference coordinates. Shifts Ports in accordance with how far anchors have been moved. This conserves the location of Ports with respect to their anchor Particles, but ...
4,895
def remove_outcome_hook(self, outcome_id): for transition_id in list(self.transitions.keys()): transition = self.transitions[transition_id] if transition.to_outcome == outcome_id and transition.to_state == self.state_id: self.remove_transition(transition_id)
Removes internal transition going to the outcome
4,896
def _metric_when_multiplied_with_sig_vec(self, sig): return dot((self.B * self.D**-1.).T * sig, self.B * self.D)
return D^-1 B^T diag(sig) B D as a measure for C^-1/2 diag(sig) C^1/2 :param sig: a vector "used" as diagonal matrix :return:
4,897
def collect_modules(self): try: res = {} m = sys.modules for k in m: continue if m[k]: try: d = m[k].__dict__ if "version" in d and d["version"]: ...
Collect up the list of modules in use
4,898
def cross_validate(self, ax): cdpp_opt = self.get_cdpp_arr() for b, brkpt in enumerate(self.breakpoints): log.info("Cross-validating chunk %d/%d..." % (b + 1, len(self.breakpoints))) m = self.get_masked_chunk(b) ...
Performs the cross-validation step.
4,899
def get_products(self): products = set() for _, _, _, react, _ in self.get_kinks(): products = products.union(set([k.reduced_formula for k in react.products])) return list(products)
List of formulas of potential products. E.g., ['Li','O2','Mn'].