Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
387,400
def press_key(self, key, mode=0): if isinstance(key, str): assert key in KEYS, .format(key) key = KEYS[key] _LOGGER.info(, self.__get_key_name(key)) return self.rq(, OrderedDict([(, key), (, mode)]))
modes: 0 -> simple press 1 -> long press 2 -> release after long press
387,401
def start_vm(access_token, subscription_id, resource_group, vm_name): endpoint = .join([get_rm_endpoint(), , subscription_id, , resource_group, , vm_name, , , COMP_API...
Start a virtual machine. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. Returns: HTTP response.
387,402
def add_execution_data(self, context_id, data): if context_id not in self._contexts: LOGGER.warning("Context_id not in contexts, %s", context_id) return False context = self._contexts.get(context_id) context.add_execution_data(data) return True
Within a context, append data to the execution result. Args: context_id (str): the context id returned by create_context data (bytes): data to append Returns: (bool): True if the operation is successful, False if the context_id doesn't reference a kn...
387,403
def get_max_instances_of_storage_bus(self, chipset, bus): if not isinstance(chipset, ChipsetType): raise TypeError("chipset can only be an instance of type ChipsetType") if not isinstance(bus, StorageBus): raise TypeError("bus can only be an instance of type StorageBus")...
Returns the maximum number of storage bus instances which can be configured for each VM. This corresponds to the number of storage controllers one can have. Value may depend on chipset type used. in chipset of type :class:`ChipsetType` The chipset type to get the value for. ...
387,404
def p_expression_sra(self, p): p[0] = Sra(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
expression : expression RSHIFTA expression
387,405
def get_cutout(self, token, channel, x_start, x_stop, y_start, y_stop, z_start, z_stop, t_start=0, t_stop=1, resolution=1, block_size=DEFAULT_BLOCK_SIZE, neariso=False): ...
Get volumetric cutout data from the neurodata server. Arguments: token (str): Token to identify data to download channel (str): Channel resolution (int): Resolution level Q_start (int): The lower bound of dimension 'Q' Q_stop (int): The upper bound of...
387,406
def _warning_handler(self, code: int): if code == 300: warnings.warn( "ExpireWarning", RuntimeWarning, stacklevel=3 ) elif code == 301: warnings.warn( "ExpireStreamWarning", Runti...
处理300~399段状态码,抛出对应警告. Parameters: (code): - 响应的状态码 Return: (bool): - 已知的警告类型则返回True,否则返回False
387,407
def WriteProtoFile(self, printer): self.Validate() extended_descriptor.WriteMessagesFile( self.__file_descriptor, self.__package, self.__client_info.version, printer)
Write the messages file to out as proto.
387,408
def get_algorithm(alg: str) -> Callable: if alg not in algorithms: raise ValueError(.format(alg)) return algorithms[alg]
:param alg: The name of the requested `JSON Web Algorithm <https://tools.ietf.org/html/rfc7519#ref-JWA>`_. `RFC7518 <https://tools.ietf.org/html/rfc7518#section-3.2>`_ is related. :type alg: str :return: The requested algorithm. :rtype: Callable :raises: ValueError
387,409
def get_nearest_nodes(G, X, Y, method=None): start_time = time.time() if method is None: nn = [get_nearest_node(G, (y, x), method=) for x, y in zip(X, Y)] elif method == : if not cKDTree: raise ImportError() ...
Return the graph nodes nearest to a list of points. Pass in points as separate vectors of X and Y coordinates. The 'kdtree' method is by far the fastest with large data sets, but only finds approximate nearest nodes if working in unprojected coordinates like lat-lng (it precisely finds the nearest node ...
387,410
def remove_timedim(self, var): if self.pps and var.dims[0] == : data = var[0, :, :] data.attrs = var.attrs var = data return var
Remove time dimension from dataset
387,411
def _zp_decode(self, msg): zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]] return {: zone_partitions}
ZP: Zone partitions.
387,412
def create_win32tz_map(windows_zones_xml): coming_comment = None win32_name = None territory = None parser = genshi.input.XMLParser(StringIO(windows_zones_xml)) map_zones = {} zone_comments = {} for kind, data, _ in parser: if kind == genshi.core.START and str(data[0]) == "mapZone": attrs = ...
Creates a map between Windows and Olson timezone names. Args: windows_zones_xml: The CLDR XML mapping. Yields: (win32_name, olson_name, comment)
387,413
def set_enumerated_subtypes(self, subtype_fields, is_catch_all): assert self._enumerated_subtypes is None, \ assert isinstance(is_catch_all, bool), type(is_catch_all) self._is_catch_all = is_catch_all self._enumerated_subtypes = [] if self.parent_type: ...
Sets the list of "enumerated subtypes" for this struct. This differs from regular subtyping in that each subtype is associated with a tag that is used in the serialized format to indicate the subtype. Also, this list of subtypes was explicitly defined in an "inner-union" in the specifica...
387,414
def mcc(y, z): tp, tn, fp, fn = contingency_table(y, z) return (tp * tn - fp * fn) / K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
Matthews correlation coefficient
387,415
def intersection(l1, l2): if len(l1) == 0 or len(l2) == 0: return [] out = [] l2_pos = 0 for l in l1: while l2_pos < len(l2) and l2[l2_pos].end < l.start: l2_pos += 1 if l2_pos == len(l2): break while l2_pos < len(l2) and l.intersects(l2[l...
Returns intersection of two lists. Assumes the lists are sorted by start positions
387,416
def init_request(self): builder = Request.Builder() builder.url(self.url) for k, v in self.headers.items(): builder.addHeader(k, v) body = self.body if body: media_type = MediaType( __id_...
Init the native request using the okhttp3.Request.Builder
387,417
def _read_python_source(self, filename): try: f = open(filename, "rb") except IOError as err: self.log_error("Can't open %s: %s", filename, err) return None, None try: encoding = tokenize.detect_encoding(f.readline)[0] finally: ...
Do our best to decode a Python source file correctly.
387,418
def named(self, name): name name = self.serialize(name) return self.get_by(, name)
Returns .get_by('name', name)
387,419
def getDarkCurrentAverages(exposuretimes, imgs): x, imgs_p = sortForSameExpTime(exposuretimes, imgs) s0, s1 = imgs[0].shape imgs = np.empty(shape=(len(x), s0, s1), dtype=imgs[0].dtype) for i, ip in zip(imgs, imgs_p): if len(ip) == 1: i[:] = ip[0] ...
return exposure times, image averages for each exposure time
387,420
def projScatter(lon, lat, **kwargs): hp.projscatter(lon, lat, lonlat=True, **kwargs)
Create a scatter plot on HEALPix projected axes. Inputs: lon (deg), lat (deg)
387,421
def _string_from_ip_int(self, ip_int=None): if not ip_int and ip_int != 0: ip_int = int(self._ip) if ip_int > self._ALL_ONES: raise ValueError() hex_str = % ip_int hextets = [] for x in range(0, 32, 4): hextets.append( % int(hex_str...
Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones.
387,422
def publish(self, rawtx): tx = deserialize.signedtx(rawtx) if not self.dryrun: self.service.send_tx(tx) return serialize.txid(tx.hash())
Publish signed <rawtx> to bitcoin network.
387,423
def pgettext(msgctxt, message): key = msgctxt + + message translation = get_translation().gettext(key) return message if translation == key else translation
Particular gettext' function. It works with 'msgctxt' .po modifiers and allow duplicate keys with different translations. Python 2 don't have support for this GNU gettext function, so we reimplement it. It works by joining msgctx and msgid by '4' byte.
387,424
def add_droplets(self, droplet): droplets = droplet if not isinstance(droplets, list): droplets = [droplet] resources = self.__extract_resources_from_droplets(droplets) if len(resources) > 0: return self.__add_resources(resources) retur...
Add the Tag to a Droplet. Attributes accepted at creation time: droplet: array of string or array of int, or array of Droplets.
387,425
def set_webconfiguration_settings(name, settings, location=): r*IIS:\nameenabledfiltersystem.webServer/security/authentication/anonymousAuthenticationvalue ps_cmd = [] if not settings: log.warning() return False settings = _prepare_settings(name, settings) for idx, setting i...
r''' Set the value of the setting for an IIS container. Args: name (str): The PSPath of the IIS webconfiguration settings. settings (list): A list of dictionaries containing setting name, filter and value. location (str): The location of the settings (optional) Returns: boo...
387,426
def show(self): if self._future: self._job.poll_once() return if self._model_json is None: print("No model trained yet") return if self.model_id is None: print("This H2OEstimator has been removed.") return m...
Print innards of model, without regards to type.
387,427
def _validate_class(self, cl): if cl not in self.schema_def.attributes_by_class: search_string = self._build_search_string(cl) err = self.err( "{0} - invalid class", self._field_name_from_uri(cl), search_string=search_string) return Va...
return error if class `cl` is not found in the ontology
387,428
def git_path_valid(git_path=None): if git_path is None and GIT_PATH is None: return False if git_path is None: git_path = GIT_PATH try: call([git_path, ]) return True except OSError: return False
Check whether the git executable is found.
387,429
def _handle_consent_response(self, context): consent_state = context.state[STATE_KEY] saved_resp = consent_state["internal_resp"] internal_response = InternalData.from_dict(saved_resp) hash_id = self._get_consent_id(internal_response.requester, internal_response.subject_id, ...
Endpoint for handling consent service response :type context: satosa.context.Context :rtype: satosa.response.Response :param context: response context :return: response
387,430
def elements(self): ABCABCAABBCCs count has been set to zero or is a negative number, elements() will ignore it. ' for elem, count in iteritems(self): for _ in range(count): yield elem
Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] If an element's count has been set to zero or is a negative number, elements() will ignore it.
387,431
def div(self, key, value=2): return uwsgi.cache_mul(key, value, self.timeout, self.name)
Divides the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool
387,432
def walklevel(path, depth = -1, **kwargs): if depth < 0: for root, dirs, files in os.walk(path, **kwargs): yield root, dirs, files path = path.rstrip(os.path.sep) num_sep = path.count(os.path.sep) for root, dirs, files i...
It works just like os.walk, but you can pass it a level parameter that indicates how deep the recursion will go. If depth is -1 (or less than 0), the full depth is walked.
387,433
def on_configurationdone_request(self, py_db, request): self.api.run(py_db) configuration_done_response = pydevd_base_schema.build_response(request) return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True)
:param ConfigurationDoneRequest request:
387,434
def encode_for_locale(s): try: return s.encode(LOCALE_ENCODING, ) except (AttributeError, UnicodeDecodeError): return s.decode(, ).encode(LOCALE_ENCODING)
Encode text items for system locale. If encoding fails, fall back to ASCII.
387,435
def new(self, *args, **kwargs): return self.session().add(self.model(*args, **kwargs))
Create a new instance of :attr:`model` and commit it to the backend server. This a shortcut method for the more verbose:: instance = manager.session().add(MyModel(**kwargs))
387,436
def wrap_exceptions(callable): def wrapper(self, *args, **kwargs): try: return callable(self, *args, **kwargs) except EnvironmentError: err = sys.exc_info()[1] if err.errno in (errno.ENOENT, errno.ESRCH): ...
Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
387,437
def publish(self, load): payload = {: } crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets[][].value) payload[] = crypticle.dumps(load) if self.opts[]: master_pem_path = os.path.join(self.opts[], ) log.debug("Signing data packet") ...
Publish "load" to minions
387,438
def return_action(self, text, loc, ret): exshared.setpos(loc, text) if DEBUG > 0: print("RETURN:",ret) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return if not self.symtab.same_types(self.shared.function_index, ret.exp[0]): ...
Code executed after recognising a return statement
387,439
def greenlet_timeouts(self): while True: now = datetime.datetime.utcnow() for greenlet in list(self.gevent_pool): job = get_current_job(id(greenlet)) if job and job.timeout and job.datestarted: expires = job.datestarted + date...
This greenlet kills jobs in other greenlets if they timeout.
387,440
def clean_existing(self, value): existing_pk = value[self.pk_field] try: obj = self.fetch_existing(existing_pk) except ReferenceNotFoundError: raise ValidationError() orig_data = self.get_orig_data_from_existing(obj) value = sel...
Clean the data and return an existing document with its fields updated based on the cleaned values.
387,441
def update_extent_from_rectangle(self): self.show() self.canvas.unsetMapTool(self.rectangle_map_tool) self.canvas.setMapTool(self.pan_tool) rectangle = self.rectangle_map_tool.rectangle() if rectangle: self.bounding_box_group.setTitle( self....
Update extent value in GUI based from the QgsMapTool rectangle. .. note:: Delegates to update_extent()
387,442
def ensure_dir(path): dirpath = os.path.dirname(path) if dirpath and not os.path.exists(dirpath): os.makedirs(dirpath)
Ensure directory exists. Args: path(str): dir path
387,443
def _should_run(het_file): has_hets = False with open(het_file) as in_handle: for i, line in enumerate(in_handle): if i > 1: has_hets = True break return has_hets
Check for enough input data to proceed with analysis.
387,444
def type_alias(self): type_alias = self._kwargs.get(self._TYPE_ALIAS_FIELD, None) return type_alias if type_alias is not None else type(self).__name__
Return the type alias this target was constructed via. For a target read from a BUILD file, this will be target alias, like 'java_library'. For a target constructed in memory, this will be the simple class name, like 'JavaLibrary'. The end result is that the type alias should be the most natural way to re...
387,445
def _pred(aclass): isaclass = inspect.isclass(aclass) return isaclass and aclass.__module__ == _pred.__module__
:param aclass :return: boolean
387,446
def sample(self, cursor): count = cursor.count() if count == 0: self._empty = True raise ValueError("Empty collection") if self.p >= 1 and self.max_items <= 0: for item in cursor: yield item return ...
Extract records randomly from the database. Continue until the target proportion of the items have been extracted, or until `min_items` if this is larger. If `max_items` is non-negative, do not extract more than these. This function is a generator, yielding items incrementally. ...
387,447
def down(force): try: cloud_config = CloudConfig() cloud_controller = CloudController(cloud_config) cloud_controller.down(force) except CloudComposeException as ex: print(ex)
destroys an existing cluster
387,448
def package_releases(self, package, url_fmt=lambda u: u): return [{ : package, : version, : [self.get_urlhash(f, url_fmt) for f in files] } for version, files in self.storage.get(package, {}).items()]
List all versions of a package Along with the version, the caller also receives the file list with all the available formats.
387,449
def focus_up(pymux): " Move focus up. " _move_focus(pymux, lambda wp: wp.xpos, lambda wp: wp.ypos - 2)
Move focus up.
387,450
def touch(self): assert not self._has_responded self.trigger(event.TOUCH, message=self)
Respond to ``nsqd`` that you need more time to process the message.
387,451
def close(self, reason=None): with self._closing: if self._closed: return if self.is_active: _LOGGER.debug("Stopping consumer.") self._consumer.stop() self._consumer = None _LOGGE...
Stop consuming messages and shutdown all helper threads. This method is idempotent. Additional calls will have no effect. Args: reason (Any): The reason to close this. If None, this is considered an "intentional" shutdown. This is passed to the callbacks spe...
387,452
def from_string(values, separator, remove_duplicates = False): result = AnyValueArray() if values == None or len(values) == 0: return result items = str(values).split(separator) for item in items: if (item != None and len(item) > 0) or remove_duplicates...
Splits specified string into elements using a separator and assigns the elements to a newly created AnyValueArray. :param values: a string value to be split and assigned to AnyValueArray :param separator: a separator to split the string :param remove_duplicates: (optional) true to rem...
387,453
def _scan_block(self, cfg_job): addr = cfg_job.addr current_func_addr = cfg_job.func_addr if self._addr_hooked_or_syscall(addr): entries = self._scan_procedure(cfg_job, current_func_addr) else: entries = self._scan_soot_block(cfg_job, current_func_addr...
Scan a basic block starting at a specific address :param CFGJob cfg_job: The CFGJob instance. :return: a list of successors :rtype: list
387,454
def constraint(self): constraint_arr = [] if self._not_null: constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL") if self._unique: constraint_arr.append("UNIQUE") return " ".join(constraint_arr)
Constraint string
387,455
def get(self, list_id, segment_id): return self._mc_client._get(url=self._build_path(list_id, , segment_id))
returns the specified list segment.
387,456
def _safe_sendBreak_v2_7(self): result = True try: self.sendBreak() except: try: self.setBreak(False) except: result = False return result
! pyserial 2.7 API implementation of sendBreak/setBreak @details Below API is deprecated for pyserial 3.x versions! http://pyserial.readthedocs.org/en/latest/pyserial_api.html#serial.Serial.sendBreak http://pyserial.readthedocs.org/en/latest/pyserial_api.html#serial.Serial.setBreak
387,457
def init_default(m:nn.Module, func:LayerFunc=nn.init.kaiming_normal_)->None: "Initialize `m` weights with `func` and set `bias` to 0." if func: if hasattr(m, ): func(m.weight) if hasattr(m, ) and hasattr(m.bias, ): m.bias.data.fill_(0.) return m
Initialize `m` weights with `func` and set `bias` to 0.
387,458
def ip4_address(self): if self._ip4_address is None and self.network is not None: self._ip4_address = self._get_ip_address( libvirt.VIR_IP_ADDR_TYPE_IPV4) return self._ip4_address
Returns the IPv4 address of the network interface. If multiple interfaces are provided, the address of the first found is returned.
387,459
def _exec_loop(self, a, bd_all, mask): npt = bd_all.shape[0] n = self.X_ADJUSTED.shape[0] kvalues = np.zeros(npt) sigmasq = np.zeros(npt) a_inv = scipy.linalg.inv(a) for j in np.nonzero(~mask)[0]: bd = bd_all[j] if np....
Solves the kriging system by looping over all specified points. Less memory-intensive, but involves a Python-level loop.
387,460
def _flip_kron_order(mat4x4: np.ndarray) -> np.ndarray: result = np.array([[0] * 4] * 4, dtype=np.complex128) order = [0, 2, 1, 3] for i in range(4): for j in range(4): result[order[i], order[j]] = mat4x4[i, j] return result
Given M = sum(kron(a_i, b_i)), returns M' = sum(kron(b_i, a_i)).
387,461
def _push_new_tag_to_git(self): print("Pushing new version to git") subprocess.call(["git", "add", self.release_file]) subprocess.call(["git", "add", self.init_file]) subprocess.call([ "git", "commit", "-m", "Updating {}/__init__.py to version {...
tags a new release and pushes to origin/master
387,462
def get(self, byte_sig: str, online_timeout: int = 2) -> List[str]: byte_sig = self._normalize_byte_sig(byte_sig) text_sigs = self.solidity_sigs.get(byte_sig) if text_sigs is not None: return text_sigs with SQLiteDB(self.path) as cur: ...
Get a function text signature for a byte signature 1) try local cache 2) try online lookup (if enabled; if not flagged as unavailable) :param byte_sig: function signature hash as hexstr :param online_timeout: online lookup timeout :return: list of matching function text signatures
387,463
def inject_code(self, payload, lpParameter = 0): lpStartAddress = self.malloc(len(payload)) try: self.write(lpStartAddress, payload) aThread = self.start_thread(lpStartAddress, lpParameter, ...
Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} @type payload: str @param payload: Relocatable code to run i...
387,464
def calc_bhhh_hessian_approximation_mixed_logit(params, design_3d, alt_IDs, rows_to_obs, rows_to_alts, ...
Parameters ---------- params : 1D ndarray. All elements should by ints, floats, or longs. Should have 1 element for each utility coefficient being estimated (i.e. num_features + num_coefs_being_mixed). design_3d : 3D ndarray. All elements should be ints, floats, or longs. Sh...
387,465
def check_spelling(spelling_lang, txt): if os.name == "nt": assert(not "check_spelling() not available on Windows") return with _ENCHANT_LOCK: words_dict = enchant.request_dict(spelling_lang) try: tknzr = enchant.tokenize.get_tokenizer(spelling_lang) ...
Check the spelling in the text, and compute a score. The score is the number of words correctly (or almost correctly) spelled, minus the number of mispelled words. Words "almost" correct remains neutral (-> are not included in the score) Returns: A tuple : (fixed text, score)
387,466
def get_date_datetime_param(self, request, param): if param in request.GET: param_value = request.GET.get(param, None) date_match = dateparse.date_re.match(param_value) if date_match: return timezone.datetime.combine( ...
Check the request for the provided query parameter and returns a rounded value. :param request: WSGI request object to retrieve query parameter data. :param param: the name of the query parameter.
387,467
def get_traceback_data(self): default_template_engine = None if default_template_engine is None: template_loaders = [] frames = self.get_traceback_frames() for i, frame in enumerate(frames): if in frame: frame_vars = [] ...
Return a dictionary containing traceback information.
387,468
def add_source_get_correlated(gta, name, src_dict, correl_thresh=0.25, non_null_src=False): if gta.roi.has_source(name): gta.zero_source(name) gta.update_source(name) test_src_name = "%s_test" % name else: test_src_name = name gta.add_source(test_src_name, src_dict)...
Add a source and get the set of correlated sources Parameters ---------- gta : `fermipy.gtaanalysis.GTAnalysis` The analysis object name : str Name of the source we are adding src_dict : dict Dictionary of the source parameters correl_thresh : float Threshold...
387,469
def get_info(self, wiki=None, show=True, proxy=None, timeout=0): if wiki: self.params.update({: wiki}) self._get(, show=False, proxy=proxy, timeout=timeout) self._get(, show, proxy, timeout) return self
GET site info (general, statistics, siteviews, mostviewed) via https://www.mediawiki.org/wiki/API:Siteinfo, and https://www.mediawiki.org/wiki/Extension:PageViewInfo Optional arguments: - [wiki]: <str> alternate wiki site (default=en.wikipedia.org) - [show]: <bool> echo page dat...
387,470
def elliptical_arc_to(x1, y1, rx, ry, phi, large_arc_flag, sweep_flag, x2, y2): rx = abs(rx) ry = abs(ry) phi = phi % 360 if x1==x2 and y1==y2: return [] if rx == 0 or ry == 0: return [(x2,y2)] rphi = radians(phi) cphi = cos(rphi) sphi = sin(rphi) dx = 0.5*(x1 - x2) dy = ...
An elliptical arc approximated with Bezier curves or a line segment. Algorithm taken from the SVG 1.1 Implementation Notes: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
387,471
def main(): firstline,itilt,igeo,linecnt,key=1,0,0,0,"" out="" data,k15=[],[] dir= ofile="" if in sys.argv: ind=sys.argv.index() dir=sys.argv[ind+1]+ if in sys.argv: print(main.__doc__) sys.exit() if in sys.argv: file=input("Input file name...
NAME k15_s.py DESCRIPTION converts .k15 format data to .s format. assumes Jelinek Kappabridge measurement scheme SYNTAX k15_s.py [-h][-i][command line options][<filename] OPTIONS -h prints help message and quits -i allows interactive entry of options...
387,472
def contains_some_of(self, elements): if all(e not in self._subject for e in elements): raise self._error_factory(_format("Expected {} to have some of {}", self._subject, elements)) return ChainInspector(self._subject)
Ensures :attr:`subject` contains at least one of *elements*, which must be an iterable.
387,473
def random_state(state=None): if is_integer(state): return np.random.RandomState(state) elif isinstance(state, np.random.RandomState): return state elif state is None: return np.random else: raise ValueError("random_state must be an integer, a numpy " ...
Helper function for processing random_state arguments. Parameters ---------- state : int, np.random.RandomState, None. If receives an int, passes to np.random.RandomState() as seed. If receives an np.random.RandomState object, just returns object. If receives `None`, returns np.rand...
387,474
def write_sampler_metadata(self, sampler): self.attrs[] = sampler.name self[self.sampler_group].attrs[] = sampler.nwalkers sampler.model.write_metadata(self)
Writes the sampler's metadata.
387,475
def get_dist(dist): from scipy import stats dc = getattr(stats, dist, None) if dc is None: e = "Statistical distribution `{}` is not in scipy.stats.".format(dist) raise ValueError(e) return dc
Return a distribution object from scipy.stats.
387,476
def _get_prefixes(self, metric_type): prefixes = [] if self._prepend_metric_type: prefixes.append(self.METRIC_TYPES[metric_type]) return prefixes
Get prefixes where applicable Add metric prefix counters, timers respectively if :attr:`prepend_metric_type` flag is True. :param str metric_type: The metric type :rtype: list
387,477
def cleanTempDirs(job): if job is CWLJob and job._succeeded: for tempDir in job.openTempDirs: if os.path.exists(tempDir): shutil.rmtree(tempDir) job.openTempDirs = []
Remove temporarly created directories.
387,478
def drop_if_exists(self, table): blueprint = self._create_blueprint(table) blueprint.drop_if_exists() self._build(blueprint)
Drop a table from the schema. :param table: The table :type table: str
387,479
def get_events(fd, timeout=None): (rlist, _, _) = select([fd], [], [], timeout) if not rlist: return [] events = [] while True: buf = os.read(fd, _BUF_LEN) i = 0 while i < len(buf): (wd, mask, cookie, len_) = struct.unpack_from(_EVENT_FMT, buf, i) ...
get_events(fd[, timeout]) Return a list of InotifyEvent instances representing events read from inotify. If timeout is None, this will block forever until at least one event can be read. Otherwise, timeout should be an integer or float specifying a timeout in seconds. If get_events times out waiting...
387,480
def encode_dict(dynamizer, value): encoded_dict = {} for k, v in six.iteritems(value): encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_dict[k] = { encoded_type: encoded_value, } return , encoded_dict
Encode a dict for the DynamoDB format
387,481
def _count_spaces_startswith(line): if line.split()[0].strip() == "": return None spaces = 0 for i in line: if i.isspace(): spaces += 1 else: return spaces
Count the number of spaces before the first character
387,482
def _get_mro(cls): if not isinstance(cls, type): class cls(cls, object): pass return cls.__mro__[1:] return cls.__mro__
Get an mro for a type or classic class
387,483
def plot(self, joints, ax, target=None, show=False): from . import plot_utils if ax is None: ax = plot_utils.init_3d_figure() plot_utils.plot_chain(self, joints, ax) plot_utils.plot_basis(ax, self._length) if target is not None: ...
Plots the Chain using Matplotlib Parameters ---------- joints: list The list of the positions of each joint ax: matplotlib.axes.Axes A matplotlib axes target: numpy.array An optional target show: bool Display the axe. Defau...
387,484
def img_from_vgg(x): x = x.transpose((1, 2, 0)) x[:, :, 0] += 103.939 x[:, :, 1] += 116.779 x[:, :, 2] += 123.68 x = x[:,:,::-1] return x
Decondition an image from the VGG16 model.
387,485
def _parse_byte_data(self, byte_data): chunks = unpack(, byte_data[:self.size]) det_id, run, time_slice, time_stamp, ticks = chunks self.det_id = det_id self.run = run self.time_slice = time_slice self.time_stamp = time_stamp self.ticks = ticks
Extract the values from byte string.
387,486
def is_contained_in(pe_pe, root): if not pe_pe: return False if type(pe_pe).__name__ != : pe_pe = one(pe_pe).PE_PE[8001]() ep_pkg = one(pe_pe).EP_PKG[8000]() c_c = one(pe_pe).C_C[8003]() if root in [ep_pkg, c_c]: return True elif is_contained_in(e...
Determine if a PE_PE is contained within a EP_PKG or a C_C.
387,487
def _get_signed_predecessors(im, node, polarity): signed_pred_list = [] for pred in im.predecessors(node): pred_edge = (pred, node) yield (pred, _get_edge_sign(im, pred_edge) * polarity)
Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediate predecessors. Parameters ---------- im...
387,488
def zoneToRegion(zone): from toil.lib.context import Context return Context.availability_zone_re.match(zone).group(1)
Get a region (e.g. us-west-2) from a zone (e.g. us-west-1c).
387,489
def add_user_to_group(user_name, group_name, region=None, key=None, keyid=None, profile=None): user = get_user(user_name, region, key, keyid, profile) if not user: log.error(, user_name) return False if user_exists_in_group(user_name, group_name, region=region, key...
Add user to group. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.add_user_to_group myuser mygroup
387,490
def maxsize(self, size): if size < 0: raise ValueError() with self._lock: self._enforce_size_limit(size) self._maxsize = size
Resize the cache, evicting the oldest items if necessary.
387,491
def time_report(self, include_overhead=False, header=None, include_server=True, digits=4): try: self._timestamps.setdefault(, time.time()) header = header or [, , , , ] ret = [] if include_overhead: ret.append(self.tim...
Returns a str table of the times for this api call :param include_overhead: bool if True include information from overhead, such as the time for this class code :param header: bool if True includes the column header :param include_server: bool if True...
387,492
def get_byte(self, i): value = [] for x in range(2): c = next(i) if c.lower() in _HEX: value.append(c) else: raise SyntaxError( % (i.index - 1)) return .join(value)
Get byte.
387,493
def pi_zoom_origin(self, viewer, event, msg=True): origin = (event.data_x, event.data_y) return self._pinch_zoom_rotate(viewer, event.state, event.rot_deg, event.scale, msg=msg, origin=origin)
Like pi_zoom(), but pans the image as well to keep the coordinate under the cursor in that same position relative to the window.
387,494
def get_netloc(self): if self.proxy: scheme = self.proxytype host = self.proxyhost port = self.proxyport else: scheme = self.scheme host = self.host port = self.port return (scheme, host, port)
Determine scheme, host and port for this connection taking proxy data into account. @return: tuple (scheme, host, port) @rtype: tuple(string, string, int)
387,495
def deserialize(self, value, **kwargs): for validator in self.validators: validator.validate(value, **kwargs) return value
Deserialization of value. :return: Deserialized value. :raises: :class:`halogen.exception.ValidationError` exception if value is not valid.
387,496
def _reciprocal_condition_number(lu_mat, one_norm): r if _scipy_lapack is None: raise OSError("This function requires SciPy for calling into LAPACK.") rcond, info = _scipy_lapack.dgecon(lu_mat, one_norm) if info != 0: raise RuntimeError( "The reciprocal 1-norm cond...
r"""Compute reciprocal condition number of a matrix. Args: lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been LU-factored, with the non-diagonal part of :math:`L` stored in the strictly lower triangle and :math:`U` stored in the upper triangle. one_norm (...
387,497
def set_user_attribute(self, user_name, key, value): res = self._make_ocs_request( , self.OCS_SERVICE_CLOUD, + parse.quote(user_name), data={: self._encode_string(key), : self._encode_string(value)} ) if res.status_cod...
Sets a user attribute :param user_name: name of user to modify :param key: key of the attribute to set :param value: value to set :returns: True if the operation succeeded, False otherwise :raises: HTTPResponseError in case an HTTP error status was returned
387,498
def get_content(self, obj): serializer = ContentSerializer( instance=obj.contentitem_set.all(), many=True, context=self.context, ) return serializer.data
Obtain the QuerySet of content items. :param obj: Page object. :return: List of rendered content items.
387,499
def p_elseif_list(p): if len(p) == 2: p[0] = [] else: p[0] = p[1] + [ast.ElseIf(p[4], p[6], lineno=p.lineno(2))]
elseif_list : empty | elseif_list ELSEIF LPAREN expr RPAREN statement