Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
361,900
def connection_made(self, transport): self.port = transport.serial.port logger.debug(, self.port, transport) self.transport = transport self.connected.set() self.disconnected.clear()
Called when reader thread is started
361,901
def load_file_as_yaml(path): with open(path, "r") as f: raw_yaml = f.read() parsed_dict = yaml.load(raw_yaml) return parsed_dict
Given a filepath, loads the file as a dictionary from YAML :param path: The path to a YAML file
361,902
def filterAll(self, **kwargs): --no-deps if canFilterTags is False: raise NotImplementedError() allNodes = self.getAllNodes() filterableNodes = FilterableTagCollection(allNodes) return filterableNodes.filterAnd(**kwargs)
filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, use "filter" or "filterAnd" on a TagCollection For specia...
361,903
def volume(self): sizes = self.compute_cell_sizes(length=False, area=False, volume=True) return np.sum(sizes.cell_arrays[])
Mesh volume Returns ------- volume : float Total volume of the mesh.
361,904
def append(self, passes, ignore_requires=None, ignore_preserves=None, max_iteration=None, **flow_controller_conditions): passset_options = {: ignore_requires, : ignore_preserves, : max_iteration} options = self._join_options...
Args: passes (list[BasePass] or BasePass): pass(es) to be added to schedule ignore_preserves (bool): ignore the preserves claim of passes. Default: False ignore_requires (bool): ignore the requires need of passes. Default: False max_iteration (int): max number of iteratio...
361,905
def compute_checksum(stream, algo, message_digest, chunk_size=None, progress_callback=None): chunk_size = chunk_size_or_default(chunk_size) bytes_read = 0 while 1: chunk = stream.read(chunk_size) if not chunk: if progress_callback: progr...
Get helper method to compute checksum from a stream. :param stream: File-like object. :param algo: Identifier for checksum algorithm. :param messsage_digest: A message digest instance. :param chunk_size: Read at most size bytes from the file at a time. :param progress_callback: Function accepting o...
361,906
def from_dict(input_dict): import copy input_dict = copy.deepcopy(input_dict) mapping_class = input_dict.pop() input_dict["name"] = str(input_dict["name"]) import GPy mapping_class = eval(mapping_class) return mapping_class._build_from_input_dict(mapping_...
Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_from_input_dict of the derived class. Note: This method should n...
361,907
def ConvertSupportedOSToConditions(src_object): if src_object.supported_os: conditions = " OR ".join("os == " % o for o in src_object.supported_os) return conditions
Turn supported_os into a condition.
361,908
def get_by_start_id(self, start_id): url = % (self.scan_id, start_id) code, page = self.conn.send_request(url, method=) if code != 200: message = page.get(, ) args = (code, message) raise APIException( % args) ...
:yield: Log entries starting from :start_id: and ending 200 entries after. In most cases easier to call than the paginate one because there is no need to keep track of the already read entries in a specific page.
361,909
def wave(self, wave_first=True, thread_id=None, thread_type=None): thread_id, thread_type = self._getThread(thread_id, thread_type) data = self._getSendData(thread_id=thread_id, thread_type=thread_type) data["action_type"] = "ma-type:user-generated-message" data["lightweight_act...
Says hello with a wave to a thread! :param wave_first: Whether to wave first or wave back :param thread_id: User/Group ID to send to. See :ref:`intro_threads` :param thread_type: See :ref:`intro_threads` :type thread_type: models.ThreadType :return: :ref:`Message ID <intro_messa...
361,910
def from_data(cls, data): messages = [] filename = data[][] for m in data[]: for l in m[]: location = l[] if not location.startswith(filename): location = filename + + location if l[] != -1: ...
Create a list of Messages from deserialized epubcheck json output. :param dict data: Decoded epubcheck json data :return list[Message]: List of messages
361,911
def sqlwhere(criteria=None): if not criteria: return (, []) fields = sorted(criteria.keys()) validate_names(fields) values = [criteria[field] for field in fields] parts = [field + for field in fields] sql = .join(parts) return (sql, values)
Generates SQL where clause. Returns (sql, values). Criteria is a dictionary of {field: value}. >>> sqlwhere() ('', []) >>> sqlwhere({'id': 5}) ('id=%s', [5]) >>> sqlwhere({'id': 3, 'name': 'toto'}) ('id=%s and name=%s', [3, 'toto']) >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2...
361,912
def initiate(self, mechanism, payload=None): if self._state != SASLState.INITIAL: raise RuntimeError("initiate has already been called") try: next_state, payload = yield from self.interface.initiate( mechanism, payload=payload) e...
Initiate the SASL handshake and advertise the use of the given `mechanism`. If `payload` is not :data:`None`, it will be base64 encoded and sent as initial client response along with the ``<auth />`` element. Return the next state of the state machine as tuple (see :class:`SASLS...
361,913
def get_variants(self, ref_sequence_name, allowed_ctg_coords, allowed_ref_coords, nucmer_matches=None): npD2E mummer_variants = self._get_mummer_variants(self.nucmer_snp_file) variants = {} seq_type, is_variant_only = self.refdata.sequence_type(ref_sequence_name) ref_sequence = s...
Nucmr coords = dict. Key=contig name. Value = list of intervals of ref coords that match the contig. Made by assembly_compare.AssemblyCompare.nucmer_hits_to_ref_coords Returns dictionary. Key=contig name. Value = list of variants. Each variant is a tuple: ( 0 = position, ...
361,914
def user_info(self, verbose=False): url = .format(self.rest_url, ) return self.__auth_req_get(url, verbose=verbose)
Get information about the currently authenticated user http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information
361,915
def bbox_from_point(point, distance=1000, project_utm=False, return_crs=False): lat, lng = point point_proj, crs_proj = project_geometry(Point((lng, lat))) buffer_proj = point_proj.buffer(distance) if project_utm: west, south, east, north = buffer_proj.bounds log(.format...
Create a bounding box some distance in each direction (north, south, east, and west) from some (lat, lng) point. Parameters ---------- point : tuple the (lat, lon) point to create the bounding box around distance : int how many meters the north, south, east, and west sides of the bo...
361,916
def add_new_peers( self, count, new_peers, current_peers, con=None, path=None, peer_table=None ): if self.ping_timeout is None: self.ping_timeout = atlas_ping_timeout() if path is None: path = self.atlasdb_path cnt = 0 i = 0 added = [...
Ping up to @count new peers from @new_peers that aren't already known to us. If they respond, then add them to the peer set. Return the (list of peers added, the list of peers already known, list of peers ignored)
361,917
def config_(cls, key, default=None): return cls._app.config.get(key, default)
Shortcut to access the config in your class :param key: The key to access :param default: The default value when None :returns mixed:
361,918
def delete(self): if self.parent is None: raise RuntimeError( "Current statement has no parent, so it cannot " + "be deleted form a procmailrc structure" ) elif self.id is None: raise RuntimeError("id not set but have a parent,...
Remove the statement from a ProcmailRC structure, raise a RuntimeError if the statement is not inside a ProcmailRC structure return the parent id
361,919
def get_series_as_of_date(self, series_id, as_of_date): as_of_date = pd.to_datetime(as_of_date) df = self.get_series_all_releases(series_id) data = df[df[] <= as_of_date] return data
Get latest data for a Fred series id as known on a particular date. This includes any revision to the data series before or on as_of_date, but ignores any revision on dates after as_of_date. Parameters ---------- series_id : str Fred series id such as 'GDP' as_of_dat...
361,920
def activate(locale): if INSTALL_JINJA_TRANSLATIONS: install_jinja_translations() if django.VERSION >= (1, 3): django_trans._active.value = _activate(locale) else: from django.utils.thread_support import currentThread django_trans._active[currentThread()] = _activate(lo...
Override django's utils.translation.activate(). Django forces files to be named django.mo (http://code.djangoproject.com/ticket/6376). Since that's dumb and we want to be able to load different files depending on what part of the site the user is in, we'll make our own function here.
361,921
def get_special_inds(sample, label_store, aux_note): s0_inds = np.where(sample == np.int64(0))[0] note_inds = np.where(label_store == np.int64(22))[0] potential_definition_inds = set(s0_inds).intersection(note_inds) notann_inds = np.where(label_store == np.int64(0))[0] rm_ind...
Get the indices of annotations that hold definition information about the entire annotation file, and other empty annotations to be removed. Note: There is no need to deal with SKIP annotations (label_store=59) which were already dealt with in proc_core_fields and hence not included here.
361,922
def add_dyn(system, model, data): if model == : bus = data[0] data = data[3:] if bus in system.PV.bus: dev = gen_idx = system.PV.idx[system.PV.bus.index(bus)] elif bus in system.SW.bus: dev = gen_idx = system.SW.idx[system.SW.bus...
helper function to elem_add a device element to system
361,923
def fromcolumns(cols, header=None, missing=None): return ColumnsView(cols, header=header, missing=missing)
View a sequence of columns as a table, e.g.:: >>> import petl as etl >>> cols = [[0, 1, 2], ['a', 'b', 'c']] >>> tbl = etl.fromcolumns(cols) >>> tbl +----+-----+ | f0 | f1 | +====+=====+ | 0 | 'a' | +----+-----+ | 1 | 'b' | +---...
361,924
def angular_distance_fast(ra1, dec1, ra2, dec2): lon1 = np.deg2rad(ra1) lat1 = np.deg2rad(dec1) lon2 = np.deg2rad(ra2) lat2 = np.deg2rad(dec2) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon /2.0)**2 c = 2 * np.arcsin(np.sq...
Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for antipodes. :param lon1: :param lat1: :param lon2: :param lat2: :r...
361,925
def ssh_key_info_from_key_data(key_id, priv_key=None): if FINGERPRINT_RE.match(key_id) and priv_key: key_info = {"fingerprint": key_id, "priv_key": priv_key} else: key_info = load_ssh_key(key_id) key = None try: key = serialization.load_pem_private_key( ...
Get/load SSH key info necessary for signing. @param key_id {str} Either a private ssh key fingerprint, e.g. 'b3:f0:a1:6c:18:3b:42:63:fd:6e:57:42:74:17:d4:bc', or the path to an ssh private key file (like ssh's IdentityFile config option). @param priv_key {str} Optional. SSH private key file dat...
361,926
def down_the_wabbit_hole(session, class_name): auth_redirector_url = AUTH_REDIRECT_URL.format(class_name=class_name) r = session.get(auth_redirector_url) logging.debug(, auth_redirector_url) try: r.raise_for_status() except requests.exceptions.HTTPError as e: ...
Authenticate on class.coursera.org
361,927
def get_pull_request(project, num, auth=False): url = "https://api.github.com/repos/{project}/pulls/{num}".format(project=project, num=num) if auth: header = make_auth_header() else: header = None response = requests.get(url, headers=header) response.raise_for_status() retur...
get pull request info by number
361,928
def get_current_waypoints(boatd=None): if boatd is None: boatd = Boatd() content = boatd.get() return [Point(*coords) for coords in content.get()]
Get the current set of waypoints active from boatd. :returns: The current waypoints :rtype: List of Points
361,929
def GetElementNSdict(self, elt): d = self.ns_cache.get(id(elt)) if not d: if elt != self.dom: d = self.GetElementNSdict(elt.parentNode) for a in _attrs(elt): if a.namespaceURI == XMLNS.BASE: if a.localName == "xmlns": ...
Get a dictionary of all the namespace attributes for the indicated element. The dictionaries are cached, and we recurse up the tree as necessary.
361,930
def _init_header(self, string): taf_header_pattern = metar_header_pattern = header_taf = re.match(taf_header_pattern, string, re.VERBOSE) header_metar = re.match(metar_header_pattern, string, re.VERBOSE) else: raise MalformedTAF("No va...
Extracts header part from TAF/METAR string and populates header dict Args: TAF/METAR report string Raises: MalformedTAF: An error parsing the report Returns: Header dictionary
361,931
def build(self): if self.es_version == : if len(self.filters) > 0: return { : { : self.query, : { : self.filters } } } ...
Builds the query string, which can be used for a search query :return: the query string
361,932
def zadd(self, key, *members, **kwargs): xx = kwargs.pop(, False) nx = kwargs.pop(, False) ch = kwargs.pop(, False) incr = kwargs.pop(, False) command = [b, key] if xx: command += [] if nx: command += [] if ch: ...
Adds all the specified members with the specified scores to the sorted set stored at key. It is possible to specify multiple score / member pairs. If a specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position to ensure ...
361,933
async def handle_client_kill_job(self, client_addr, message: ClientKillJob): if (client_addr, message.job_id) in self._waiting_jobs: del self._waiting_jobs[(client_addr, message.job_id)] await ZMQUtils.send_with_addr(self._client_socket, client_addr, Backen...
Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent.
361,934
def _parse_scheme_file(self): schemes = json.loads(self.scheme_file.read(), object_pairs_hook=OrderedDict) scheme_list = [] scheme_dict = defaultdict(list) for scheme_len, scheme_group in schemes.items(): for scheme_str, _count in scheme_group: scheme...
Initialize redundant data structures for lookup optimization
361,935
def satisfiable(self, extra_constraints=(), exact=None): if exact is False and o.VALIDATE_APPROXIMATIONS in self.state.options: er = self._solver.satisfiable(extra_constraints=self._adjust_constraint_list(extra_constraints)) ar = self._solver.satisfiable(extra_constraints=self._...
This function does a constraint check and checks if the solver is in a sat state. :param extra_constraints: Extra constraints (as ASTs) to add to s for this solve :param exact: If False, return approximate solutions. :return: True if sat, otherwise false
361,936
def conflicted(path_to_file): for line in open(path_to_file, ): for marker in : if line.startswith(marker * 8): return True return False
Whether there are any conflict markers in that file
361,937
def parse(readDataInstance): dosHdr = DosHeader() dosHdr.e_magic.value = readDataInstance.readWord() dosHdr.e_cblp.value = readDataInstance.readWord() dosHdr.e_cp.value = readDataInstance.readWord() dosHdr.e_crlc.value = readDataInstance.readWord() dosHdr.e_...
Returns a new L{DosHeader} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{DosHeader} object. @rtype: L{DosHeader} @return: A new L{DosHeader} object.
361,938
def getWindowByTitle(self, wildcard, order=0): for w in self._get_window_list(): if "kCGWindowName" in w and re.search(wildcard, w["kCGWindowName"], flags=re.I): if order == 0: return w["kCGWindowNumber"] else: ...
Returns a handle for the first window that matches the provided "wildcard" regex
361,939
def _attribute_definition(self, attrid): attrs = self._schema["attributes"] try: return dict(attrs[attrid]) except KeyError: attr_names = self._schema["attribute_names"] attrdef = attrs.get(attr_names.get(str(attrid).lower())) ...
Returns the attribute definition dict of a given attribute ID, can be the name or the integer ID
361,940
def __init(self): params = { "f" : "json", } json_dict = self._get(self._url, params, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_...
initializes the service
361,941
def is_directed(self): r if self._directed is None: self._directed = (self.W != self.W.T).nnz != 0 return self._directed
r"""Check if the graph has directed edges (cached). In this framework, we consider that a graph is directed if and only if its weight matrix is not symmetric. Returns ------- directed : bool True if the graph is directed, False otherwise. Examples -...
361,942
def __get_form_data(self, soup): elements = self.__get_valid_form_data_elements(soup) form_data = self.__get_default_form_data_input(elements) callback = self.options.callbacks.form_before_autofill action = callback(self.queue_item, elements, form_data) if action == Cr...
Build a form data dict from the given form. Args: soup (obj): The BeautifulSoup form. Returns: obj: The form data (key/value).
361,943
def forward(self, x): features = self.conv(x).mean(dim=2) return self.dense(features)
Passing data through the network. :param x: 2d tensor containing both (x,y) Variables :return: output of the net
361,944
def x_grid(self, grid=None): if grid is None: return self._x_grid else: if not isinstance(grid, bool): raise TypeError("grid must be boolean, not " % grid) self._x_grid = grid
The horizontal lines that run accross the chart from the x-ticks. If a boolean value is given, these gridlines will be turned on or off. Otherwise, the method will return their current state. :param bool grid: Turns the gridlines on or off. :rtype: ``bool``
361,945
async def get_name_endpoint(request: web.Request) -> web.Response: return web.json_response( data={: request.app[DEVICE_NAME_VARNAME]}, status=200)
Get the name of the robot. This information is also accessible in /server/update/health, but this endpoint provides symmetry with POST /server/name. GET /server/name -> 200 OK, {'name': robot name}
361,946
def split_pdb_residue(s): if s.isdigit(): return (int(s), ) else: assert(s[:-1].isdigit()) return ((s[:-1], s[-1]))
Splits a PDB residue into the numeric and insertion code components.
361,947
def notify(self, method, params=None): log.debug(, method, params) message = { : JSONRPC_VERSION, : method, } if params is not None: message[] = params self._consumer(message)
Send a JSON RPC notification to the client. Args: method (str): The method name of the notification to send params (any): The payload of the notification
361,948
def Emulation_setPageScaleFactor(self, pageScaleFactor): assert isinstance(pageScaleFactor, (float, int) ), "Argument must be of type floatint. Received type: " % type( pageScaleFactor) subdom_funcs = self.synchronous_command(, pageScaleFactor=pageScaleFactor) return subdom_funcs
Function path: Emulation.setPageScaleFactor Domain: Emulation Method name: setPageScaleFactor WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'pageScaleFactor' (type: number) -> Page scale factor. No return value. Description: Sets a specified page sc...
361,949
def alpha2(self, code): code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): ...
Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string.
361,950
def _dataset_create_resources(self): if in self.data: self.old_data[] = self._copy_hdxobjects(self.resources, hdx.data.resource.Resource, ) self.init_resources() self.separate_resources()
Creates resource objects in dataset
361,951
def fixed_point(is_zero, plus, minus, f, x): @memo_Y def _fixed_point(fixed_point_fun): def __fixed_point(collected, new): diff = minus(new, collected) if is_zero(diff): return collected return fixed_point_fun(plus(collected, diff), f(diff)) ...
Get the least fixed point when it can be computed piecewise. .. testsetup:: from proso.func import fixed_point .. doctest:: >>> sorted(fixed_point( ... is_zero=lambda xs: len(xs) == 0, ... plus=lambda xs, ys: xs + ys, ... minus=lambda xs, ys: [x for x in xs i...
361,952
def list_container_objects(self, container, limit=None, marker=None, prefix=None, delimiter=None, end_marker=None, full_listing=False): if full_listing: return self._manager.object_listing_iterator(container, prefix=prefix) return self._manager.list_o...
Return a list of StorageObjects representing the objects in the container. You can use the marker, end_marker, and limit params to handle pagination, and the prefix and delimiter params to filter the objects returned. Also, by default only the first 10,000 objects are returned; if you s...
361,953
def from_list(cls, database, key, data, clear=False): lst = cls(database, key) if clear: lst.clear() lst.extend(data) return lst
Create and populate a List object from a data list.
361,954
def learn(*, network, env, total_timesteps, timesteps_per_batch=1024, max_kl=0.001, cg_iters=10, gamma=0.99, lam=1.0, seed=None, ent_coef=0.0, cg_damping=1e-2, vf_stepsize=3e-4, vf_iters =3, max_episodes=0,...
learn a policy function with TRPO algorithm Parameters: ---------- network neural network to learn. Can be either string ('mlp', 'cnn', 'lstm', 'lnlstm' for basic types) or function that takes input placeholder and returns tuple (output, None) for feedforward ne...
361,955
def _coltype_to_typeengine(coltype: Union[TypeEngine, VisitableType]) -> TypeEngine: if isinstance(coltype, VisitableType): coltype = coltype() assert isinstance(coltype, TypeEngine) return coltype
An example is simplest: if you pass in ``Integer()`` (an instance of :class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in ``Integer`` (an instance of :class:`VisitableType`), you'll also get ``Integer()`` back. The function asserts that its return type is an instance of :class:`TypeEngine...
361,956
def cmp(cls, v1: , v2: ) -> int: if v1._version > v2._version: return 1 elif v1._version == v2._version: return 0 else: return -1
Compares two instances.
361,957
def is_attribute_deprecated(self, attribute): rule_set = self._attribute_rule_sets.get(attribute) if rule_set.version_deprecated: if self._version >= rule_set.version_deprecated: return True else: return False else: ret...
Check if the attribute is deprecated by the current KMIP version. Args: attribute (string): The name of the attribute (e.g., 'Unique Identifier'). Required.
361,958
def make_posix(path): if not isinstance(path, six.string_types): raise TypeError("Expected a string for path, received {0!r}...".format(path)) starts_with_sep = path.startswith(os.path.sep) separated = normalize_path(path).split(os.path.sep) if isinstance(separated, (list, tuple)): ...
Convert a path with possible windows-style separators to a posix-style path (with **/** separators instead of **\\** separators). :param Text path: A path to convert. :return: A converted posix-style path :rtype: Text >>> make_posix("c:/users/user/venvs/some_venv\\Lib\\site-packages") "c:/user...
361,959
def plot_lines_to(self, other, index=None, **kwds): start, end = self._get_samples_shared_with(other, index=index) segments = [[start[i, :], end[i, :]] for i in range(start.shape[0])] ax = plt.gca() ax.add_artist(LineCollection(segments=segments, **kwds)) return ax
Plot lines from samples shared between this projection and another dataset. Args: other (:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame` or `array-like`): The other dataset to plot lines to. If other is an instance of ...
361,960
def fold_path(path, width=30): assert isinstance(path, six.string_types) if len(path) > width: path.replace(".", ".\n ") return path
Fold a string form of a path so that each element is on separate line
361,961
async def update_api(request: web.Request) -> web.Response: log.debug() data = await request.post() try: res0 = await install_py( data[], request.loop) reslist = [res0] if in data.keys(): res1 = await install_py( data[], request.loop) ...
This handler accepts a POST request with Content-Type: multipart/form-data and file fields in the body named "whl", "serverlib", and "fw". The "whl" and "serverlib" files should be valid Python wheels to be installed ("whl" is expected generally to be the API server wheel, and "serverlib" is expected to...
361,962
def as_crispy_errors(form, template_pack=TEMPLATE_PACK): if isinstance(form, BaseFormSet): template = get_template( % template_pack) c = Context({: form}).flatten() else: template = get_template( % template_pack) c = Context({: form}).flatten() return template.render(c)
Renders only form errors the same way as django-crispy-forms:: {% load crispy_forms_tags %} {{ form|as_crispy_errors }} or:: {{ form|as_crispy_errors:"bootstrap" }}
361,963
def newton_refine_solve(jac_both, x_val, surf_x, y_val, surf_y): r a_val, b_val, c_val, d_val = jac_both[:, 0] e_val = x_val - surf_x f_val = y_val - surf_y denom = a_val * d_val - b_val * c_val delta_s = (d_val * e_val - c_val * f_val) / denom delta_t = (a_val * f_val - b_val * e_...
r"""Helper for :func:`newton_refine`. We have a system: .. code-block:: rest [A C][ds] = [E] [B D][dt] [F] This is not a typo, ``A->B->C->D`` matches the data in ``jac_both``. We solve directly rather than using a linear algebra utility: .. code-block:: rest ds = (D E - ...
361,964
def _get_creds(self, req): self._validate_auth_scheme(req) try: creds = naked(req.auth.split()[1]) creds = b64decode(creds) username, password = creds.split() return username, password except IndexError: raise InvalidAuthSyn...
Get the username & password from the Authorization header If the header is actually malformed where Basic Auth was indicated by the request then an InvalidAuthSyntax exception is raised. Otherwise an AuthRequired exception since it's unclear in this scenario if the requestor was even aw...
361,965
def interface_options(score=False, raw=False, features=None, rgb=None): interface = sc_pb.InterfaceOptions() interface.score = score interface.raw = raw if features: interface.feature_layer.width = 24 interface.feature_layer.resolution.x = features interface.feature_layer.resolution.y = features ...
Get an InterfaceOptions for the config.
361,966
def maxStmId(proc): maxId = 0 for stm in proc.statements: maxId = max(maxId, getMaxStmIdForStm(stm)) return maxId
get max statement id, used for sorting of processes in architecture
361,967
def get_house_detail(self, html): if "It parse bedroom from %r" % text text = span_list[1].text try: bathroom = float_filter(text) data["bathroom"] = bathroom except: data["errors"][ "bathroom"] = "...
Get bedroom, bathroom, sqft and more information. Example: http://www.zillow.com/homedetails/8510-Whittier-Blvd-Bethesda-MD-20817/37183103_zpid/
361,968
def get(self, label, default=None): if label in self.index: loc = self.index.get_loc(label) return self._get_val_at(loc) else: return default
Returns value occupying requested label, default to specified missing value if not present. Analogous to dict.get Parameters ---------- label : object Label value looking for default : object, optional Value to return if label not in index Return...
361,969
def accounts(self): return account.HPEAccountCollection( self._conn, utils.get_subresource_path_by(self, ), redfish_version=self.redfish_version)
Property to provide instance of HPEAccountCollection
361,970
def collection_updated_percolator(mapper, connection, target): delete_collection_percolator(target) if target.dbquery is not None: new_collection_percolator(target)
Create percolator when collection is created. :param mapper: Not used. It keeps the function signature. :param connection: Not used. It keeps the function signature. :param target: Collection where the percolator should be updated.
361,971
def base_install(): scwrl = {} print( .format(**text_colours)) scwrl_path = get_user_path(, required=False) scwrl[] = str(scwrl_path) pack_mode = get_user_option( , [, ]) if pack_mode == : scwrl[] = True else: scwrl[] = False ...
Generates configuration setting for required functionality of ISAMBARD.
361,972
def get_version(): pkg_dir = get_package_dir() with open(os.path.join(pkg_dir, )) as ver_file: string = ver_file.read() return string.strip().replace(, ).replace(')
Get single-source __version__.
361,973
async def create_conversation(self, create_conversation_request): response = hangouts_pb2.CreateConversationResponse() await self._pb_request(, create_conversation_request, response) return response
Create a new conversation.
361,974
def save_species_count(self, delimiter=, filename=): with open(filename, ) as f: w = csv.writer(f, delimiter=delimiter) for s in self.get_species_sizes(): w.writerow(s)
Log speciation throughout evolution.
361,975
def find_tendril(cls, proto, addr): proto = proto.lower() return cls._tendrils[proto][addr]
Finds the tendril corresponding to the protocol and address tuple. Returns the Tendril object, or raises KeyError if the tendril is not tracked. The address tuple is the tuple of the local address and the remote address for the tendril.
361,976
def _check_rev_dict(tree, ebt): ebs = defaultdict(dict) for edge in ebt.values(): source_id = edge[] edge_id = edge[] ebs[source_id][edge_id] = edge assert ebs == tree[]
Verifyies that `ebt` is the inverse of the `edgeBySourceId` data member of `tree`
361,977
def connect_to_database_odbc_sqlserver(self, odbc_connection_string: str = None, dsn: str = None, database: str = None, user: str = None, ...
Connects to an SQL Server database via ODBC.
361,978
def get_X_slice(self, rmind): if self.forest.optimize_memory_use: return self.forest.X[:, rmind][self.subsample] else: return self.X[:, rmind]
get X with slicing
361,979
def from_Z(z: int): for sym, data in _pt_data.items(): if data["Atomic no"] == z: return Element(sym) raise ValueError("No element with this atomic number %s" % z)
Get an element from an atomic number. Args: z (int): Atomic number Returns: Element with atomic number z.
361,980
def search_clans(self, **params: clansearch): url = self.api.CLAN return self._get_model(url, PartialClan, **params)
Search for a clan. At least one of the filters must be present Parameters ---------- name: Optional[str] The name of a clan (has to be at least 3 characters long) locationId: Optional[int] A location ID minMembers: Optional[int] ...
361,981
def verify_permitted_to_read(gs_path): from . import _bucket bucket, prefix = _bucket.parse_name(gs_path) credentials = None if google.datalab.Context._is_signed_in(): credentials = google.datalab.Context.default().credentials args = { : Api._MAX_RESULTS, : ...
Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read.
361,982
def verify(token, public_key, validate_nonce=None, algorithms=[DEFAULT_ALGORITHM]): try: token_data = jwt.decode(token, public_key, algorithms=algorithms) except jwt.InvalidTokenError: logger.debug() return False claimed_username = token_data.get() claimed_time = token_data...
Verify the validity of the given JWT using the given public key. :param token: JWM claim :param public_key: Public key to use when verifying the claim's signature. :param validate_nonce: Callable to use to validate the claim's nonce. :param algorithms: Allowable signing algorithms. Defaults to ['RS512'...
361,983
def _from_binary_volname(cls, binary_stream): name = binary_stream.tobytes().decode("utf_16_le") _MOD_LOGGER.debug("Attempted to unpack VOLUME_NAME Entry from \"%s\"\nResult: %s", binary_stream.tobytes(), name) return cls(name)
See base class.
361,984
def check_input(self, token): if isinstance(token.payload, Instance): return raise Exception(self.full_name + ": Unhandled data type: " + str(token.payload.__class__.__name__))
Performs checks on the input token. Raises an exception if unsupported. :param token: the token to check :type token: Token
361,985
def can_handle(self, input_dict): return input_dict is not None \ and isinstance(input_dict, dict) \ and len(input_dict) == 1 \ and self.intrinsic_name in input_dict
Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise
361,986
def _get_total_read_size(self): if self.read_size: read_size = EVENT_SIZE * self.read_size else: read_size = EVENT_SIZE return read_size
How much event data to process at once.
361,987
def _GetIntersectingRanges(self, partition_key): partitionkey_ranges = set() intersecting_ranges = set() if partition_key is None: return list(self.partition_map.keys()) if isinstance(partition_key, prange.Range): partitionkey_ranges.add(partition_key) ...
Gets the intersecting ranges based on the partition key.
361,988
def _required_segments(self, sampfrom, sampto): if self.layout == : startseg = 0 else: startseg = 1 cumsumlengths = list(np.cumsum(self.seg_len[startseg:])) seg_numbers = [[sampfrom < cs for cs in cumsumlengths].index(True)] ...
Determine the segments and the samples within each segment in a multi-segment record, that lie within a sample range. Parameters ---------- sampfrom : int The starting sample number to read for each channel. sampto : int The sample number at which to stop...
361,989
def rollback(self): try: self.check_connection() except NullDatabaseConnectionError: return logger.debug("rollback: path=".format(self.database_path)) self.connection.rollback()
.. seealso:: :py:meth:`sqlite3.Connection.rollback`
361,990
def format_cmdline(args, maxwidth=80): maxwidth -= 2 def lines(): line = for a in (shell_quote(a) for a in args): if len(line) + len(a) + 1 > maxwidth: yield line line = if ...
Format args into a shell-quoted command line. The result will be wrapped to maxwidth characters where possible, not breaking a single long argument.
361,991
def _readable_flags(transport): if not in transport: return None _flag_list = [] flags = transport[] if flags & dpkt.tcp.TH_SYN: if flags & dpkt.tcp.TH_ACK: _flag_list.append() else: _flag_list.append() ...
Method that turns bit flags into a human readable list Args: transport (dict): transport info, specifically needs a 'flags' key with bit_flags Returns: list: a list of human readable flags (e.g. ['syn_ack', 'fin', 'rst', ...]
361,992
def filter_data(self, min_len, max_len): logging.info(f) initial_len = len(self.src) filtered_src = [] for src in self.src: if min_len <= len(src) <= max_len: filtered_src.append(src) self.src = filtered_src filtered_len = len(self.s...
Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
361,993
def usage(self, subcommand): usage = .join([, subcommand, ]) if self.args: usage = % (usage, str(self.args)) return usage
Returns *how to use command* text.
361,994
def date_convert(string, match, ymd=None, mdy=None, dmy=None, d_m_y=None, hms=None, am=None, tz=None, mm=None, dd=None): groups = match.groups() time_only = False if mm and dd: y=datetime.today().year m=groups[mm] d=groups[dd] elif ymd is not None: y, m, d = ...
Convert the incoming string containing some date / time info into a datetime instance.
361,995
def validate(cls, value): if value not in cls._valid_settings: raise ValueError( "%s not a member of %s enumeration" % (value, cls.__name__) )
Raise |ValueError| if *value* is not an assignable value.
361,996
def update_caseid(self, case_obj, family_id): new_case = deepcopy(case_obj) new_case[] = family_id for case_variants in [, ]: new_variantids = [] for variant_id in case_obj.get(case_variants, []): case_variant = self.variant(variant_id) ...
Update case id for a case across the database. This function is used when a case is a rerun or updated for another reason. Args: case_obj(dict) family_id(str): The new family id Returns: new_case(dict): The updated case object
361,997
def multinomial(data, shape=_Null, get_prob=False, out=None, dtype=, **kwargs): return _internal._sample_multinomial(data, shape, get_prob, out=out, dtype=dtype, **kwargs)
Concurrent sampling from multiple multinomial distributions. .. note:: The input distribution must be normalized, i.e. `data` must sum to 1 along its last dimension. Parameters ---------- data : NDArray An *n* dimensional array whose last dimension has length `k`, where `...
361,998
def _read_opt_pdm(self, code, *, desc): _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size != 10: raise ProtocolError(f) _stlr = self._read_unpack(1) _stls = self._read_unpack(1) _psnt = self._read_unpack(2) _psnl = self._...
Read HOPOPT PDM option. Structure of HOPOPT PDM option [RFC 8250]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ...
361,999
def handle_readable(client): data = client.recv(1028) if data == b: return False client.sendall(b + data) print(threading.active_count()) return True
Return True: The client is re-registered to the selector object. Return False: The server disconnects the client.