Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
385,200
def proxy_uri(self, value): option = Option() option.number = defines.OptionRegistry.PROXY_URI.number option.value = str(value) self.add_option(option)
Set the Proxy-Uri option of a request. :param value: the Proxy-Uri value
385,201
def stereo_bm_preset(self, value): if value in (cv2.STEREO_BM_BASIC_PRESET, cv2.STEREO_BM_FISH_EYE_PRESET, cv2.STEREO_BM_NARROW_PRESET): self._bm_preset = value else: raise InvalidBMPresetError("Stereo BM preset must be defined a...
Set private ``_stereo_bm_preset`` and reset ``_block_matcher``.
385,202
def add_val(self, subj: Node, pred: URIRef, json_obj: JsonObj, json_key: str, valuetype: Optional[URIRef] = None) -> Optional[BNode]: if json_key not in json_obj: print("Expecting to find object named in JSON:".format(json_key)) print(json_obj._as_json_dumps()) ...
Add the RDF representation of val to the graph as a target of subj, pred. Note that FHIR lists are represented as a list of BNODE objects with a fhir:index discrimanant :param subj: graph subject :param pred: predicate :param json_obj: object containing json_key :param json_key:...
385,203
def run_dssp(pdb, path=True, outfile=None): if not path: if type(pdb) == str: pdb = pdb.encode() try: temp_pdb = tempfile.NamedTemporaryFile(delete=False) temp_pdb.write(pdb) temp_pdb.seek(0) dssp_out = subprocess.check_output( ...
Uses DSSP to find helices and extracts helices from a pdb file or string. Parameters ---------- pdb : str Path to pdb file or string. path : bool, optional Indicates if pdb is a path or a string. outfile : str, optional Filepath for storing the dssp output. Returns ...
385,204
def resolve(self, obj): if not isinstance(obj, str): return obj if in obj: return resolve_reference(obj) value = self._entrypoints.get(obj) if value is None: raise LookupError(.format(self.namespace, obj)) if isinstance(value, Entry...
Resolve a reference to an entry point or a variable in a module. If ``obj`` is a ``module:varname`` reference to an object, :func:`resolve_reference` is used to resolve it. If it is a string of any other kind, the named entry point is loaded from this container's namespace. Otherwise, ``obj`` i...
385,205
def get_amount_of_tweets(self): if not self.__response: raise TwitterSearchException(1013) return (len(self.__response[][]) if self.__order_is_search else len(self.__response[]))
Returns current amount of tweets available within this instance :returns: The amount of tweets currently available :raises: TwitterSearchException
385,206
def format(self, formatter, subset=None): if subset is None: row_locs = range(len(self.data)) col_locs = range(len(self.data.columns)) else: subset = _non_reducing_slice(subset) if len(subset) == 1: subset = subset, self.data.colum...
Format the text display value of cells. .. versionadded:: 0.18.0 Parameters ---------- formatter : str, callable, or dict subset : IndexSlice An argument to ``DataFrame.loc`` that restricts which elements ``formatter`` is applied to. Returns ...
385,207
def archive(self): ids = self.rpc_model.search(self.domain, context=self.context) if ids: self.rpc_model.write(ids, {: False})
Archives (soft delete) all the records matching the query. This assumes that the model allows archiving (not many do - especially transactional documents). Internal implementation sets the active field to False.
385,208
def get_window(window, Nx, fftbins=True): s the name of the window function (e.g., ``) - If tuple, itkaiserkaisers a function that accepts one integer argument (the window length) - If list-like, it if six.callable(window): return window(Nx) elif (isinstance(window, (six.s...
Compute a window function. This is a wrapper for `scipy.signal.get_window` that additionally supports callable or pre-computed windows. Parameters ---------- window : string, tuple, number, callable, or list-like The window specification: - If string, it's the name of the window f...
385,209
def _read_opt_ilnp(self, code, *, desc): _type = self._read_opt_type(code) _size = self._read_unpack(1) _nval = self._read_fileng(_size) opt = dict( desc=desc, type=_type, length=_size + 2, value=_nval, ) return o...
Read HOPOPT ILNP Nonce option. Structure of HOPOPT ILNP Nonce option [RFC 6744]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
385,210
def _populate_user(self): self._populate_user_from_attributes() self._populate_user_from_group_memberships() self._populate_user_from_dn_regex() self._populate_user_from_dn_regex_negation()
Populates our User object with information from the LDAP directory.
385,211
def etree_write(tree, stream): try: tree.write(stream, encoding="utf-8", xml_declaration=True) except TypeError: tree.write(stream, encoding="unicode", xml_declaration=True)
Write XML ElementTree 'root' content into 'stream'. :param tree: XML ElementTree object :param stream: File or file-like object can write to
385,212
def artist_update(self, artist_id, name=None, urls=None, alias=None, group=None): params = { : artist_id, : name, : urls, : alias, : group } return self._get(, params, method=)
Function to update artists (Requires Login) (UNTESTED). Only the artist_id parameter is required. The other parameters are optional. Parameters: artist_id (int): The id of thr artist to update (Type: INT). name (str): The artist's name. urls (str): A list of...
385,213
def get_connection_info(connection_file=None, unpack=False, profile=None): if connection_file is None: cf = get_connection_file() else: cf = find_connection_file(connection_file, profile=profile) with open(cf) as f: info = f.read() if unpack: ...
Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, ...
385,214
def process(self, now): if self._pn_connection is None: LOG.error("Connection.process() called on destroyed connection!") return 0 if self._pn_connection.state & proton.Endpoint.LOCAL_UNINIT: return 0 if self._pn_sasl and not self._sasl_don...
Perform connection state processing.
385,215
def lookupAll(data, configFields, lookupType, db, histObj={}): for field in data.keys(): if field in configFields.keys() and data[field]!=: if lookupType in configFields[field]["lookup"]: if lookupType in [, , ]: fieldValNew, histObj = DataLookup(fie...
Return a record after having cleaning rules of specified type applied to all fields in the config :param dict data: single record (dictionary) to which cleaning rules should be applied :param dict configFields: "fields" object from DWM config (see DataDictionary) :param string lookupType: Type of lookup to...
385,216
def hdb_disk_interface(self, hdb_disk_interface): self._hdb_disk_interface = hdb_disk_interface log.info(.format(name=self._name, id=self._id, ...
Sets the hda disk interface for this QEMU VM. :param hdb_disk_interface: QEMU hdb disk interface
385,217
def choices(self): if not self._choices: gandi = self.gandi or GandiContextHelper() self._choices = self._get_choices(gandi) if not self._choices: api = gandi.get_api_connector() gandi.echo( "api and that it...
Retrieve choices from API if possible
385,218
def read(self, file_p): if not isinstance(file_p, basestring): raise TypeError("file_p can only be an instance of type basestring") progress = self._call("read", in_p=[file_p]) progress = IProgress(progress) return progress
Reads an OVF file into the appliance object. This method succeeds if the OVF is syntactically valid and, by itself, without errors. The mere fact that this method returns successfully does not mean that VirtualBox supports all features requested by the appliance; this can only be examin...
385,219
def get_Tsys(calON_obs,calOFF_obs,calflux,calfreq,spec_in,oneflux=False,**kwargs): return diode_spec(calON_obs,calOFF_obs,calflux,calfreq,spec_in,average=False,oneflux=False,**kwargs)[1]
Returns frequency dependent system temperature given observations on and off a calibrator source Parameters ---------- (See diode_spec())
385,220
def get_celery_app( name=os.getenv( "CELERY_NAME", "worker"), auth_url=os.getenv( "BROKER_URL", "redis://localhost:6379/9"), backend_url=os.getenv( "BACKEND_URL", "redis://localhost:6379/10"), include_tasks=[], ...
get_celery_app :param name: name for this app :param auth_url: celery broker :param backend_url: celery backend :param include_tasks: list of modules containing tasks to add :param ssl_options: security options dictionary :param trasport_options: transport options dictionary :param path_to_...
385,221
def get_option_lists(self): return [self.get_option_list()] + \ [option_list for name, description, option_list in self.get_option_groups()]
A hook to override the option lists used to generate option names and defaults.
385,222
def _get_imports_h(self, data_types): if not isinstance(data_types, list): data_types = [data_types] import_classes = [] for data_type in data_types: if is_user_defined_type(data_type): import_classes.append(fmt_class_prefix(data_type)) ...
Emits all necessary header file imports for the given Stone data type.
385,223
def p_term_var(self, p): _LOGGER.debug("term -> VAR") if p[1] not in self._VAR_VALUES: if self._autodefine_vars: self._VAR_VALUES[p[1]] = TypedClass(None, TypedClass.UNKNOWN) if p[1] in self._VAR_VALUES: _LOGGER....
term : VAR
385,224
def split(pattern, string, maxsplit=0, flags=0): return _compile(pattern, flags).split(string, maxsplit)
Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings.
385,225
def align_texts(source_blocks, target_blocks, params = LanguageIndependent): if len(source_blocks) != len(target_blocks): raise ValueError("Source and target texts do not have the same number of blocks.") return [align_blocks(source_block, target_block, params) for source_block, t...
Creates the sentence alignment of two texts. Texts can consist of several blocks. Block boundaries cannot be crossed by sentence alignment links. Each block consists of a list that contains the lengths (in characters) of the sentences in this block. @param source_blocks: The list of blocks ...
385,226
def make_graph_pygraphviz(self, recs, nodecolor, edgecolor, dpi, draw_parents=True, draw_children=True): import pygraphviz as pgv grph = pgv.AGraph(name="GO tree") edgeset = set() for rec in recs: if draw_...
Draw AMIGO style network, lineage containing one query record.
385,227
def mean_min_time_distance(item_a, item_b, max_value): times_a = item_a.times.reshape((item_a.times.size, 1)) times_b = item_b.times.reshape((1, item_b.times.size)) distance_matrix = (times_a - times_b) ** 2 mean_min_distances = np.sqrt(distance_matrix.min(axis=0).mean() + distance_matrix.min(axis=...
Calculate the mean time difference among the time steps in each object. Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as scaling value and upper constraint. Returns: Distance...
385,228
def do_dir(self, args, unknown): if unknown: self.perror("dir does not take any positional arguments:", traceback_war=False) self.do_help() self._last_result = cmd2.CommandResult(, ) return contents = os.listdir(self.cwd) ...
List contents of current directory.
385,229
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): if allow_dotted_names: attrs = attr.split() else: attrs = [attr] for i in attrs: if i.startswith(): raise AttributeError( % i ) else: obj = getatt...
resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are not supported and this function operates similar to getattr(obj, attr...
385,230
def get_rendered_objects(self): objects = self.objects if isinstance(objects, str): objects = getattr(self.object, objects).all() return [ self.get_rendered_object(obj) for obj in objects ]
Render objects
385,231
def set(self, document_data, merge=False): batch = self._client.batch() batch.set(self, document_data, merge=merge) write_results = batch.commit() return _first_write_result(write_results)
Replace the current document in the Firestore database. A write ``option`` can be specified to indicate preconditions of the "set" operation. If no ``option`` is specified and this document doesn't exist yet, this method will create it. Overwrites all content for the document with the ...
385,232
def _dict_from_terse_tabular( names: List[str], inp: str, transformers: Dict[str, Callable[[str], Any]] = {})\ -> List[Dict[str, Any]]: res = [] for n in names: if n not in transformers: transformers[n] = lambda s: s for line in inp.split(): i...
Parse NMCLI terse tabular output into a list of Python dict. ``names`` is a list of strings of field names to apply to the input data, which is assumed to be colon separated. ``inp`` is the input as a string (i.e. already decode()d) from nmcli ``transformers`` is a dict mapping field names to callabl...
385,233
def resnet_v2(inputs, block_fn, layer_blocks, filters, data_format="channels_first", is_training=False, is_cifar=False, use_td=False, targeting_rate=None, keep_prob=None): inputs = block_la...
Resnet model. Args: inputs: `Tensor` images. block_fn: `function` for the block to use within the model. Either `residual_block` or `bottleneck_block`. layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include in each of the 3 or 4 block groups. Each group consists of blo...
385,234
def help_center_articles_search(self, category=None, label_names=None, locale=None, query=None, section=None, updated_after=None, updated_before=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/search api_path = "/api/v2/help_center/articles/search.json" api_query = {} ...
https://developer.zendesk.com/rest_api/docs/help_center/search#search-articles
385,235
def select_many_with_correspondence( self, collection_selector=identity, result_selector=KeyedElement): if self.closed(): raise ValueError("Attempt to call " "select_many_with_correspondence() on a closed Queryable.") if not is_c...
Projects each element of a sequence to an intermediate new sequence, and flattens the resulting sequence, into one sequence and uses a selector function to incorporate the corresponding source for each item in the result sequence. Note: This method uses deferred execution. Args...
385,236
def gfuds(udfuns, udqdec, relate, refval, adjust, step, nintvls, cnfine, result): relate = stypes.stringToCharP(relate) refval = ctypes.c_double(refval) adjust = ctypes.c_double(adjust) step = ctypes.c_double(step) nintvls = ctypes.c_int(nintvls) libspice.gfuds_c(udfuns, udqdec, relat...
Perform a GF search on a user defined scalar quantity. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfuds_c.html :param udfuns: Name of the routine that computes the scalar quantity of interest at some time. :type udfuns: ctypes.CFunctionType :param udqdec: Name of the routine that compute...
385,237
def all(self, axis=None, *args, **kwargs): nv.validate_all(args, kwargs) values = self.sp_values if len(values) != len(self) and not np.all(self.fill_value): return False return values.all()
Tests whether all elements evaluate True Returns ------- all : bool See Also -------- numpy.all
385,238
def setValues(nxG, nyG, iBeg, iEnd, jBeg, jEnd, data): nxGHalf = nxG/2. nyGHalf = nyG/2. nxGQuart = nxGHalf/2. nyGQuart = nyGHalf/2. for i in range(data.shape[0]): iG = iBeg + i di = iG - nxG for j in range(data.shape[1]): jG = jBeg + j dj = jG - ...
Set setValues @param nxG number of global cells in x @param nyG number of global cells in y @param iBeg global starting index in x @param iEnd global ending index in x @param jBeg global starting index in y @param jEnd global ending index in y @param data local array
385,239
def find_children(self, linespec): res = [] for parent in self.find_objects(linespec): res.append(parent.line) res.extend([child.line for child in parent.children]) return res
Find lines and immediate children that match the linespec regex. :param linespec: regular expression of line to match :returns: list of lines. These correspond to the lines that were matched and their immediate children
385,240
def GET_AUTH(self, courseid): course, __ = self.get_course_and_check_rights(courseid) return self.page(course)
GET request
385,241
def translate_bit_for_bit(data): headers = sorted(data.get("Headers", [])) table = .replace(, data.get("Title", "table")) table += n_cols = "c"*(len(headers)+1) table += .replace("$NCOLS", n_cols) table += " Variable &" for header in headers: table += .replace(, head...
Translates data where data["Type"]=="Bit for Bit"
385,242
def ring(surf, xy, r, width, color): r2 = r - width x0, y0 = xy x = r2 y = 0 err = 0 right = {} while x >= y: right[x] = y right[y] = x right[-x] = y right[-y] = x y += 1 if err <= 0: err += 2 * y + 1 if err > ...
Draws a ring
385,243
def put_property(elt, key, value, ttl=None, ctx=None): return put_properties(elt=elt, properties={key: value}, ttl=ttl, ctx=ctx)
Put properties in elt. :param elt: properties elt to put. Not None methods. :param number ttl: If not None, property time to leave. :param ctx: elt ctx from where put properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is d...
385,244
def _request(self, lat_min, lon_min, lat_max, lon_max, start, end, picture_size=None, set_=None, map_filter=None): if not isinstance(lat_min, float): raise PynoramioException( .format(self.__class__.__name__)) if not isinstance(lon_min, float): raise Pyno...
Internal method to send requests to the Panoramio data API. :param lat_min: Minimum latitude of the bounding box :type lat_min: float :param lon_min: Minimum longitude of the bounding box :type lon_min: float :param lat_max: Maximum latitude o...
385,245
def send_custom_host_notification(self, host, options, author, comment): logger.warning("The external command " "is not currently implemented in Alignak. If you really need it, " "request for its implementation in the project repository: " ...
DOES NOTHING (Should send a custom notification) Format of the line that triggers function call:: SEND_CUSTOM_HOST_NOTIFICATION;<host_name>;<options>;<author>;<comment> :param host: host to send notif for :type host: alignak.object.host.Host :param options: notification options...
385,246
def delta(self, signature): "Generates delta for remote file via API using local filepath/sync/delta', self.path, signature=signature)
Generates delta for remote file via API using local file's signature.
385,247
def run_gatk(self, params, tmp_dir=None, log_error=True, data=None, region=None, memscale=None, parallel_gc=False, ld_preload=False): needs_java7 = LooseVersion(self.get_gatk_version()) < LooseVersion("3.6") if needs_java7: setpath.remove_bcbiopath() ...
Top level interface to running a GATK command. ld_preload injects required libraries for Java JNI calls: https://gatkforums.broadinstitute.org/gatk/discussion/8810/something-about-create-pon-workflow
385,248
def reset(self, document, parent, level): self.language = languages.get_language( document.settings.language_code) self.memo.document = document self.memo.reporter = document.reporter self.memo.language = self.language self.memo.section_level = level...
Reset the state of state machine. After reset, self and self.state can be used to passed to docutils.parsers.rst.Directive.run Parameters ---------- document: docutils document Current document of the node. parent: parent node Parent node that wi...
385,249
def _writeGpoScript(psscript=False): t set, then it is in the GUI WINDIRSystem32GroupPolicyMachineScriptsscripts.iniWINDIRSystem32GroupPolicyMachineScriptspsscripts.iniWINDIRSystem32GroupPolicyUserScriptsscripts.iniWINDIRSystem32GroupPolicyUserScriptspsscripts.ini')
helper function to write local GPO startup/shutdown script scripts are stored in scripts.ini and psscripts.ini files in ``WINDIR\\System32\\GroupPolicy\\Machine|User\\Scripts`` these files have the hidden attribute set files have following format: empty line [Startup] 0CmdLine...
385,250
def addResourceFile(self, pid, resource_file, resource_filename=None, progress_callback=None): url = "{url_base}/resource/{pid}/files/".format(url_base=self.url_base, pid=pid) params = {} close_fd = self._prepareFileForUpload(para...
Add a new file to an existing resource :param pid: The HydroShare ID of the resource :param resource_file: a read-only binary file-like object (i.e. opened with the flag 'rb') or a string representing path to file to be uploaded as part of the new resource :param resource_filename: ...
385,251
def _repos_checked(self, worker, output, error): if worker.repo in self._checking_repos: self._checking_repos.remove(worker.repo) if output: self._valid_repos.append(worker.repo) if len(self._checking_repos) == 0: self._download_repodata(self._valid...
Callback for _check_repos.
385,252
def do_update(pool,request,models): "unlike *_check() below, update doesn't worry about missing children" return {k:fkapply(models,pool,process_update,missing_update,k,v) for k,v in request.items()}
unlike *_check() below, update doesn't worry about missing children
385,253
def combinations(iterable, r): pool = tuple(iterable) n = len(pool) if r > n: return indices = list(range(r)) yield list(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: ...
Calculate combinations >>> list(combinations('ABCD',2)) [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']] >>> list(combinations(range(4), 3)) [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]] Args: iterable: Any iterable object. r: Size of combination. Yield...
385,254
def get_generated_project_files(self, tool): exporter = ToolsSupported().get_tool(tool) return exporter(self.generated_files[tool], self.settings).get_generated_project_files()
Get generated project files, the content depends on a tool. Look at tool implementation
385,255
def destroy(self, eip_or_aid, disassociate=False): if "." in eip_or_aid: return "true" == self.call("ReleaseAddress", response_data_key="return", PublicIp=eip_or_aid) else: ...
Release an EIP. If the EIP was allocated for a VPC instance, an AllocationId(aid) must be provided instead of a PublicIp. Setting disassociate to True will attempt to disassociate the IP before releasing it (required for associated nondefault VPC instances).
385,256
def compute_toc_line_indentation_spaces( header_type_curr: int = 1, header_type_prev: int = 0, no_of_indentation_spaces_prev: int = 0, parser: str = , ordered: bool = False, list_marker: str = , list_marker_log: list = build_list_marker_log(, ), index: int...
r"""Compute the number of indentation spaces for the TOC list element. :parameter header_type_curr: the current type of header (h[1-Inf]). Defaults to ``1``. :parameter header_type_prev: the previous type of header (h[1-Inf]). Defaults to ``0``. :parameter no_of_indentation_spaces_prev: t...
385,257
def realimag_files(xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, paths=None, g=None, **kwargs): return files(xscript, yscript, eyscript, exscript, plotter=realimag_databoxes, paths=paths, g=g, **kwargs)
This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's real and imaginary parts versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y ...
385,258
def create_cloud_integration(self, **kwargs): kwargs[] = True if kwargs.get(): return self.create_cloud_integration_with_http_info(**kwargs) else: (data) = self.create_cloud_integration_with_http_info(**kwargs) return data
Create a cloud integration # 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.create_cloud_integration(async_req=True) >>> result = thread.get() :param a...
385,259
def get(self, url, params=None): url = self.escapeUrl(url) content = six.BytesIO(self.raw(url, params=params)) content.seek(0,2) contentlen = content.tell() content.seek(0) MAX_BUFFER_SIZE=1024*1024*200 if c...
Make a GET request for url and return the response content as a generic lxml.objectify object
385,260
def delete(self, r=None, w=None, dw=None, pr=None, pw=None, timeout=None): self.client.delete(self, r=r, w=w, dw=dw, pr=pr, pw=pw, timeout=timeout) self.clear() return self
Delete this object from Riak. :param r: R-value, wait for this many partitions to read object before performing the put :type r: integer :param w: W-value, wait for this many partitions to respond before returning to client. :type w: integer :param dw: DW-value...
385,261
def saveWallet(self, wallet, fpath): if not fpath: raise ValueError("empty path") _fpath = self._normalize(fpath) _dpath = _fpath.parent try: _dpath.relative_to(self._baseDir) except ValueError: raise ValueError( "pat...
Save wallet into specified localtion. Returns the canonical path for the ``fpath`` where ``wallet`` has been stored. Error cases: - ``fpath`` is not inside the keyrings base dir - ValueError raised - directory part of ``fpath`` exists and it's not a directory - ...
385,262
def spawn(self, *cmds: str) -> List[SublemonSubprocess]: if not self._is_running: raise SublemonRuntimeError( ) subprocs = [SublemonSubprocess(self, cmd) for cmd in cmds] for sp in subprocs: asyncio.ensure_future(sp.spawn()) return subpro...
Coroutine to spawn shell commands. If `max_concurrency` is reached during the attempt to spawn the specified subprocesses, excess subprocesses will block while attempting to acquire this server's semaphore.
385,263
def download_static_assets(doc, destination, base_url, request_fn=make_request, url_blacklist=[], js_middleware=None, css_middleware=None, derive_filename=_derive_filename): if not isinstance(doc, BeautifulSoup): doc = BeautifulSoup(doc, "html.parser") def download_assets(sele...
Download all static assets referenced from an HTML page. The goal is to easily create HTML5 apps! Downloads JS, CSS, images, and audio clips. Args: doc: The HTML page source as a string or BeautifulSoup instance. destination: The folder to download the static assets to! base_url: Th...
385,264
def evaluate_ising(linear, quad, state): if _numpy and isinstance(state, np.ndarray): return evaluate_ising(linear, quad, state.tolist()) energy = 0.0 for index, value in uniform_iterator(linear): energy += state[index] * value for (index_a, index_b), value in six.iterit...
Calculate the energy of a state given the Hamiltonian. Args: linear: Linear Hamiltonian terms. quad: Quadratic Hamiltonian terms. state: Vector of spins describing the system state. Returns: Energy of the state evaluated by the given energy function.
385,265
def _eq(left, right): if isinstance(left, (tuple, list)) and isinstance(right, (tuple, list)): return len(left) == len(right) and all(_eq(*pair) for pair in zip(left, right)) else: return left == right
Equality comparison that allows for equality between tuple and list types with equivalent elements.
385,266
def _set_base_dn(self): results = self._search( , , [], scope=ldap.SCOPE_BASE ) if results and type(results) is list: dn, attrs = results[0] r = attrs[][0].decode() else: raise Exception ...
Get Base DN from LDAP
385,267
def create(cls, mr_spec, shard_number, shard_attempt, _writer_state=None): writer_spec = cls.get_params(mr_spec.mapper, allow_old=False) key = cls._generate_filename(writer_spec, mr_spec.name, mr_spec.mapreduce_id, shard_number, shard_...
Inherit docs.
385,268
def set_multivar(self, section, option, value=): s value to a list if applicable. If "value" is a list, then any existing values for the specified section and option will be replaced with the list being passed. ' self._string_check(value, allow_list=True) if not ...
This function is unique to the GitConfigParser. It will add another value for the option if it already exists, converting the option's value to a list if applicable. If "value" is a list, then any existing values for the specified section and option will be replaced with the list being ...
385,269
def get_context(): pid = os.getpid() if pid not in context: context[pid] = zmq.Context() logger.debug(, pid) return context[pid]
Provide the context to use. This function takes care of creating new contexts in case of forks.
385,270
def undo_sign_in(entry, session=None): if session is None: session = Session() else: session = session entry_to_delete = ( session .query(Entry) .filter(Entry.uuid == entry.uuid) .one_or_none() ) if entry_to_delete: logger.info(.format(...
Delete a signed in entry. :param entry: `models.Entry` object. The entry to delete. :param session: (optional) SQLAlchemy session through which to access the database.
385,271
def submit(self, command="", blocksize=1, job_name="parsl.auto"): if blocksize < self.nodes_per_block: blocksize = self.nodes_per_block job_name = "{0}.{1}".format(job_name, time.time()) script_path = "{0}/{1}.submit".format(self.script...
The submit method takes the command string to be executed upon instantiation of a resource most often to start a pilot (such as IPP engine or even Swift-T engines). Args : - command (str) : The bash command string to be executed. - blocksize (int) : Blocksize to be req...
385,272
def set(self, newvalue): def setter(state): return self._optic.set(state, newvalue) return setter
Set the focus to `newvalue`. >>> from lenses import lens >>> set_item_one_to_four = lens[1].set(4) >>> set_item_one_to_four([1, 2, 3]) [1, 4, 3]
385,273
def walk(self, address): for step in self._walk_to_address(address): node = step yield node.address, node.data to_process = deque() to_process.extendleft( node.children) while to_process: node = to_process.pop() yi...
Returns a stream of pairs of node addresses and data, raising AddressNotInTree if ADDRESS is not in the tree. First the ancestors of ADDRESS (including itself) are yielded, earliest to latest, and then the descendants of ADDRESS are yielded in an unspecified order. Arguments: ...
385,274
def is_same_channel(self, left, right): return self.normalize(left) == self.normalize(right)
Check if given nicknames are equal in the server's case mapping.
385,275
def memoize(func): class Memodict(dict): def __getitem__(self, *key): return dict.__getitem__(self, key) def __missing__(self, key): ret = self[key] = func(*key) return ret return Memodict().__getitem__
Memoization decorator for a function taking one or more arguments.
385,276
def get_queryset(qs=None, app=DEFAULT_APP, db_alias=None): if isinstance(qs, (djmodels.Manager, djmodels.query.QuerySet)): qs = qs.all() else: qs = get_model(qs, app=app).objects.all() if db_alias: return qs.using(db_alias) else: return qs
>>> get_queryset('Permission', app='django.contrib.auth').count() > 0 True
385,277
async def health_check(self) -> Iterator[HealthCheckFail]: ds_class = getattr(settings, , ) forbidden_defaults = [None, , ] if ds_class in forbidden_defaults: yield HealthCheckFail( , f f f f ...
Perform the checks. So far: - Make a list of the unique destination states from the transitions list, then check the health of each of them.
385,278
def parse_share_url(share_url): *__, group_id, share_token = share_url.rstrip().split() return group_id, share_token
Return the group_id and share_token in a group's share url. :param str share_url: the share url of a group
385,279
def telegram(self) -> list: telegram_controls = [control.telegram() for control in self.controls] return telegram_controls
Returns list of Telegram compatible states of the RichMessage instance nested controls. Returns: telegram_controls: Telegram representation of RichMessage instance nested controls.
385,280
async def peek(self, task_id): args = (task_id,) res = await self.conn.call(self.__funcs[], args) return self._create_task(res.body)
Get task without changing its state :param task_id: Task id :return: Task instance
385,281
def rooms_info(self, room_id=None, room_name=None): if room_id is not None: return self.__call_api_get(, roomId=room_id) elif room_name is not None: return self.__call_api_get(, roomName=room_name) else: raise RocketMissingParamException()
Retrieves the information about the room.
385,282
def avail_images(kwargs=None, call=None): if call == : raise SaltCloudSystemExit( ) if not isinstance(kwargs, dict): kwargs = {} if in kwargs: owner = kwargs[] else: provider = get_configured_provider() owner = config.get...
Return a dict of all available VM images on the cloud provider.
385,283
def get_ip_addresses(): LOGGER.debug("IPAddressService.get_ip_addresses") args = {: , : } response = IPAddressService.requester.call(args) ret = None if response.rc == 0: ret = [] for ipAddress in response.response_content[]: ret.a...
:return: all knows IP Address
385,284
def filter_backends(backends, filters=None, **kwargs): def _match_all(obj, criteria): return all(getattr(obj, key_, None) == value_ for key_, value_ in criteria.items()) configuration_filters = {} status_filters = {} for key, value in kwargs.items...
Return the backends matching the specified filtering. Filter the `backends` list by their `configuration` or `status` attributes, or from a boolean callable. The criteria for filtering can be specified via `**kwargs` or as a callable via `filters`, and the backends must fulfill all specified conditions...
385,285
def collapse(self, id_user): c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id, id_user=id_user) db.session.add(c) db.session.commit()
Collapse comment beloging to user.
385,286
def set_cookie(self, kaka, request): if not kaka: return part = urlparse(request.url) _domain = part.hostname logger.debug("%s: ", _domain, kaka) for cookie_name, morsel in kaka.items(): std_attr = ATTRS.copy() std_attr["name"] = co...
Returns a http_cookiejar.Cookie based on a set-cookie header line
385,287
def make_private(self, recursive=False, future=False, client=None): self.acl.all().revoke_read() self.acl.save(client=client) if future: doa = self.default_object_acl if not doa.loaded: doa.reload(client=client) doa.all().revoke_read(...
Update bucket's ACL, revoking read access for anonymous users. :type recursive: bool :param recursive: If True, this will make all blobs inside the bucket private as well. :type future: bool :param future: If True, this will make all objects created in the ...
385,288
def show(self, dump=False, indent=3, lvl="", label_lvl=""): return self._show_or_dump(dump, indent, lvl, label_lvl)
Prints or returns (when "dump" is true) a hierarchical view of the packet. :param dump: determine if it prints or returns the string value :param int indent: the size of indentation for each layer :param str lvl: additional information about the layer lvl :param str label_lvl: a...
385,289
def is_declared(self, expression_var): if not isinstance(expression_var, Variable): raise ValueError(f) return any(expression_var is x for x in self.get_declared_variables())
True if expression_var is declared in this constraint set
385,290
def get_lock(lockfile): pidfile = open(lockfile, "a+") try: fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB) except IOError,e: raise RuntimeError, "failed to lock %s: %s" % (lockfile, e) pidfile.seek(0) pidfile_pid = pidfile.readline().strip() ...
Tries to write a lockfile containing the current pid. Excepts if the lockfile already contains the pid of a running process. Although this should prevent a lock from being granted twice, it can theoretically deny a lock unjustly in the unlikely event that the original process is gone but another unrel...
385,291
async def check_permissions(self, action: str, **kwargs): for permission in await self.get_permissions(action=action, **kwargs): if not await ensure_async(permission.has_permission)( scope=self.scope, consumer=self, action=action, **kwargs): raise Permis...
Check if the action should be permitted. Raises an appropriate exception if the request is not permitted.
385,292
def autohide(obj): for name, item in six.iteritems(vars(obj)): if callable(item) and name in (, ): item = hide(item) for name, subclass in class_members(obj): autohide(subclass)
Automatically hide setup() and teardown() methods, recursively.
385,293
def migrate_config(self, current_config, config_to_migrate, always_update, update_defaults): value = self._search_config_for_possible_names(current_config) self._update_config(config_to_migrate, value, always_update, update_defaults)
Migrate config value in current_config, updating config_to_migrate. Given the current_config object, it will attempt to find a value based on all the names given. If no name could be found, then it will simply set the value to the default. If a value is found and is in the list of prev...
385,294
def get_apo(self, symbol, interval=, series_type=, fastperiod=None, slowperiod=None, matype=None): _FUNCTION_KEY = "APO" return _FUNCTION_KEY, ,
Return the absolute price oscillator values in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, ...
385,295
def _get_method_kwargs(self): method_kwargs = { : self.user, : self.ctype, : self.content_object.pk, } return method_kwargs
Helper method. Returns kwargs needed to filter the correct object. Can also be used to create the correct object.
385,296
def set_value(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: timeout = self.__get_new_timeout(timeout) if page_utils.is_xpath_selector(selector): by = By....
This method uses JavaScript to update a text field.
385,297
def load_ref_spectra(): data_dir = "/Users/annaho/Data/AAOmega/ref_spectra" ff = glob.glob("%s/*.txt" %data_dir) nstars = len(ff) print("We have %s training objects" %nstars) f = ff[0] data = Table.read(f, format="ascii.fast_no_header") wl = data[] npix = len(wl) ...
Pull out wl, flux, ivar from files of training spectra
385,298
def index_buffer(self, buffer, index_element_size=4): if not type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes]: raise VAOError("buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance") if isinstance(buffer, numpy.ndarray): buffer = self.ctx.bu...
Set the index buffer for this VAO Args: buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes`` Keyword Args: index_element_size (int): Byte size of each element. 1, 2 or 4
385,299
def DeserializeForImport(self, reader): super(Block, self).Deserialize(reader) self.Transactions = [] transaction_length = reader.ReadVarInt() for i in range(0, transaction_length): tx = Transaction.DeserializeFrom(reader) self.Transactions.append(tx) ...
Deserialize full object. Args: reader (neo.IO.BinaryReader):