Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
385,300
def diff_ft(self, xt, yt): a, b = self.a, self.b ex = np.exp(a + np.matmul(b, xt)) grad = (-np.sum(ex[:, np.newaxis] * b, axis=0) + np.sum(yt.flatten()[:, np.newaxis] * b, axis=0)) hess = np.zeros((self.dx, self.dx)) for k in range(self.dy): hess -= ex[k] * np.outer(b[k,:], b[k,:]) return grad, hess
First and second derivatives (wrt x_t) of log-density of Y_t|X_t=xt
385,301
def direct_normal_radiation(self, value=9999.0): if value is not None: try: value = float(value) except ValueError: raise ValueError( .format(value)) if value < 0.0: raise ValueError( ) self._direct_normal_radiation = value
Corresponds to IDD Field `direct_normal_radiation` Args: value (float): value for IDD Field `direct_normal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
385,302
def update(self, catalog=None, dependencies=None, allow_overwrite=False): if catalog: self._providers.update(catalog, allow_overwrite=allow_overwrite) if dependencies: self._dependencies.update(dependencies)
Convenience method to update this Di instance with the specified contents. :param catalog: ICatalog supporting class or mapping :type catalog: ICatalog or collections.Mapping :param dependencies: Mapping of dependencies :type dependencies: collections.Mapping :param allow_overwrite: If True, allow overwriting existing keys. Only applies to providers. :type allow_overwrite: bool
385,303
def set_password(name, password): * cmd = "dscl . -passwd /Users/{0} ".format(name, password) try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if in exc.strerror: raise CommandExecutionError(.format(name)) raise CommandExecutionError(.format(exc.strerror)) return True
Set the password for a named user (insecure, the password will be in the process list while the command is running) :param str name: The name of the local user, which is assumed to be in the local directory service :param str password: The plaintext password to set :return: True if successful, otherwise False :rtype: bool :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-block:: bash salt '*' mac_shadow.set_password macuser macpassword
385,304
def _skw_matches_comparator(kw0, kw1): def compare(a, b): return (a > b) - (a < b) list_comparison = compare(len(kw1[1][0]), len(kw0[1][0])) if list_comparison: return list_comparison if kw0[0].isComposite() and kw1[0].isComposite(): component_avg0 = sum(kw0[1][1]) / len(kw0[1][1]) component_avg1 = sum(kw1[1][1]) / len(kw1[1][1]) component_comparison = compare(component_avg1, component_avg0) if component_comparison: return component_comparison return compare(len(str(kw1[0])), len(str(kw0[0])))
Compare 2 single keywords objects. First by the number of their spans (ie. how many times they were found), if it is equal it compares them by lenghts of their labels.
385,305
def setDeclaration(self, declaration): assert isinstance(declaration.proxy, ProxyAbstractItemView), \ "The model declaration must be a QtAbstractItemView subclass. " \ "Got {]".format(declaration) self.declaration = declaration
Set the declaration this model will use for rendering the the headers.
385,306
def break_array(a, threshold=numpy.pi, other=None): assert len(a.shape) == 1, "Only 1D arrays supported" if other is not None and a.shape != other.shape: raise ValueError("arrays must be of identical shape") breaks = numpy.where(numpy.abs(numpy.diff(a)) >= threshold)[0] breaks += 1 m = len(breaks) b = numpy.empty((len(a) + m)) b_breaks = breaks + numpy.arange(m) mask = numpy.zeros_like(b, dtype=numpy.bool) mask[b_breaks] = True b[~mask] = a b[mask] = numpy.NAN if other is not None: c = numpy.empty_like(b) c[~mask] = other c[mask] = numpy.NAN ma_c = numpy.ma.array(c, mask=mask) else: ma_c = None return numpy.ma.array(b, mask=mask), ma_c
Create a array which masks jumps >= threshold. Extra points are inserted between two subsequent values whose absolute difference differs by more than threshold (default is pi). Other can be a secondary array which is also masked according to *a*. Returns (*a_masked*, *other_masked*) (where *other_masked* can be ``None``)
385,307
def can_ignore_error(self, reqhnd=None): value = sys.exc_info()[1] try: if isinstance(value, BrokenPipeError) or \ isinstance(value, ConnectionResetError): return True except NameError: pass if not self.done: return False if not isinstance(value, socket.error): return False need_close = value.errno == 9 if need_close and reqhnd is not None: reqhnd.close_connection = 1 return need_close
Tests if the error is worth reporting.
385,308
def image_search(auth=None, **kwargs): ** cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.search_images(**kwargs)
Search for images CLI Example: .. code-block:: bash salt '*' glanceng.image_search name=image1 salt '*' glanceng.image_search
385,309
def aghmean(nums): m_a = amean(nums) m_g = gmean(nums) m_h = hmean(nums) if math.isnan(m_a) or math.isnan(m_g) or math.isnan(m_h): return float() while round(m_a, 12) != round(m_g, 12) and round(m_g, 12) != round( m_h, 12 ): m_a, m_g, m_h = ( (m_a + m_g + m_h) / 3, (m_a * m_g * m_h) ** (1 / 3), 3 / (1 / m_a + 1 / m_g + 1 / m_h), ) return m_a
Return arithmetic-geometric-harmonic mean. Iterates over arithmetic, geometric, & harmonic means until they converge to a single value (rounded to 12 digits), following the method described in :cite:`Raissouli:2009`. Parameters ---------- nums : list A series of numbers Returns ------- float The arithmetic-geometric-harmonic mean of nums Examples -------- >>> aghmean([1, 2, 3, 4]) 2.198327159900212 >>> aghmean([1, 2]) 1.4142135623731884 >>> aghmean([0, 5, 1000]) 335.0
385,310
def bulk_docs(self, docs): url = .join((self.database_url, )) data = {: docs} headers = {: } resp = self.r_session.post( url, data=json.dumps(data, cls=self.client.encoder), headers=headers ) resp.raise_for_status() return response_to_json_dict(resp)
Performs multiple document inserts and/or updates through a single request. Each document must either be or extend a dict as is the case with Document and DesignDocument objects. A document must contain the ``_id`` and ``_rev`` fields if the document is meant to be updated. :param list docs: List of Documents to be created/updated. :returns: Bulk document creation/update status in JSON format
385,311
def _compute_mean_on_rock(self, C, mag, rrup, F, HW): f1 = self._compute_f1(C, mag, rrup) f3 = self._compute_f3(C, mag) f4 = self._compute_f4(C, mag, rrup) return f1 + F * f3 + HW * f4
Compute mean value on rock (that is eq.1, page 105 with S = 0)
385,312
def setdict(self, D): self.D = np.asarray(D, dtype=self.dtype) self.DTS = self.D.T.dot(self.S) self.lu, self.piv = sl.cho_factor(self.D, self.rho) self.lu = np.asarray(self.lu, dtype=self.dtype)
Set dictionary array.
385,313
def _read_para_notification(self, code, cbit, clen, *, desc, length, version): _resv = self._read_fileng(2) _code = self._read_unpack(2) _data = self._read_fileng(2) _type = _NOTIFICATION_TYPE.get(_code) if _type is None: if 1 <= _code <= 50: _type = elif 51 <= _code <= 8191: _type = elif 8192 <= _code <= 16383: _type = elif 16384 <= _code <= 40959: _type = elif 40960 <= _code <= 65535: _type = else: raise ProtocolError(f) notification = dict( type=desc, critical=cbit, length=clen, msg_type=_type, data=_data, ) _plen = length - clen if _plen: self._read_fileng(_plen) return notification
Read HIP NOTIFICATION parameter. Structure of HIP NOTIFICATION parameter [RFC 7401]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Reserved | Notify Message Type | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | / / Notification Data / / +---------------+ / | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 notification.type Parameter Type 1 15 notification.critical Critical Bit 2 16 notification.length Length of Contents 4 32 - Reserved 6 48 notification.msg_type Notify Message Type 8 64 notification.data Notification Data ? ? - Padding
385,314
def Close(self): if self.connection is not None: try: self.connection.commit() self.connection.close() self.connection = None except Exception, e: pass
Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008
385,315
def rotateTo(self, angle): self._transmogrophy(angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV)
rotates the image to a given angle Parameters: | angle - the angle that you want the image rotated to. | Positive numbers are clockwise, negative numbers are counter-clockwise
385,316
def remove_instance(self, instance): if instance.is_external: logger.info("Request external process to stop for %s", instance.name) instance.stop_process() logger.info("External process stopped.") instance.clear_queues(self.daemon.sync_manager) self.instances.remove(instance)
Request to cleanly remove the given instance. If instance is external also shutdown it cleanly :param instance: instance to remove :type instance: object :return: None
385,317
def absent(name, driver=None): ret = {: name, : {}, : False, : } volume = _find_volume(name) if not volume: ret[] = True ret[] = {0}\.format(name) return ret try: ret[][] = __salt__[](name) ret[] = True except Exception as exc: ret[] = ({0}\ .format(name, exc)) return ret
Ensure that a volume is absent. .. versionadded:: 2015.8.4 .. versionchanged:: 2017.7.0 This state was renamed from **docker.volume_absent** to **docker_volume.absent** name Name of the volume Usage Examples: .. code-block:: yaml volume_foo: docker_volume.absent
385,318
def _get_stream_schema(fields): stream_schema = topology_pb2.StreamSchema() for field in fields: key = stream_schema.keys.add() key.key = field key.type = topology_pb2.Type.Value("OBJECT") return stream_schema
Returns a StreamSchema protobuf message
385,319
def get_arctic_version(self, symbol, as_of=None): return self._read_metadata(symbol, as_of=as_of).get(, 0)
Return the numerical representation of the arctic version used to write the last (or as_of) version for the given symbol. Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or int or `datetime.datetime` Return the data as it was as_of the point in time. `int` : specific version number `str` : snapshot name which contains the version `datetime.datetime` : the version of the data that existed as_of the requested point in time Returns ------- arctic_version : int The numerical representation of Arctic version, used to create the specified symbol version
385,320
def validateOpfJsonValue(value, opfJsonSchemaFilename): jsonSchemaPath = os.path.join(os.path.dirname(__file__), "jsonschema", opfJsonSchemaFilename) jsonhelpers.validate(value, schemaPath=jsonSchemaPath) return
Validate a python object against an OPF json schema file :param value: target python object to validate (typically a dictionary) :param opfJsonSchemaFilename: (string) OPF json schema filename containing the json schema object. (e.g., opfTaskControlSchema.json) :raises: jsonhelpers.ValidationError when value fails json validation
385,321
def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): token = self._tokengetter(refresh_token=refresh_token) if token and token.client_id == client.client_id: request.client_id = token.client_id request.user = token.user return True return False
Ensure the token is valid and belongs to the client This method is used by the authorization code grant indirectly by issuing refresh tokens, resource owner password credentials grant (also indirectly) and the refresh token grant.
385,322
def buggy_div(request): a = float(request.GET.get(, )) b = float(request.GET.get(, )) return JsonResponse({: a / b})
A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or either a or b are not float. :param request: request object :return:
385,323
def _check_suffix(self, w_string, access_string, index): prefix_as = self._membership_query(access_string) full_as = self._membership_query(access_string + w_string[index:]) prefix_w = self._membership_query(w_string[:index]) full_w = self._membership_query(w_string) length = len(commonprefix([prefix_as, full_as])) as_suffix = full_as[length:] length = len(commonprefix([prefix_w, full_w])) w_suffix = full_w[length:] if as_suffix != w_suffix: logging.debug() return True logging.debug() return False
Checks if access string suffix matches with the examined string suffix Args: w_string (str): The examined string to be consumed access_string (str): The access string for the state index (int): The index value for selecting the prefix of w Returns: bool: A boolean valuei indicating if matching was successful
385,324
def set_brightness(host, did, value, token=None): urllib3.disable_warnings() if token: scheme = "https" if not token: scheme = "http" token = "1234567890" url = ( scheme + + host + + token + + did + + str( value) + ) response = requests.get(url, verify=False) if response.status_code == : return True else: return False
Set brightness of a bulb or fixture.
385,325
def cumsum(self, axis=0, *args, **kwargs): nv.validate_cumsum(args, kwargs) if axis is not None: self._get_axis_number(axis) new_array = self.values.cumsum() return self._constructor( new_array, index=self.index, sparse_index=new_array.sp_index).__finalize__(self)
Cumulative sum of non-NA/null values. When performing the cumulative summation, any non-NA/null values will be skipped. The resulting SparseSeries will preserve the locations of NaN values, but the fill value will be `np.nan` regardless. Parameters ---------- axis : {0} Returns ------- cumsum : SparseSeries
385,326
def fdf(self, x): x = self._flatten(x) n = 1 if hasattr(x, "__len__"): n = len(x) if self._dtype == 0: retval = _functional._fdf(self, x) else: retval = _functional._fdfc(self, x) if len(retval) == n: return numpy.array(retval) return numpy.array(retval).reshape(self.npar() + 1, n // self.ndim()).transpose()
Calculate the value of the functional for the specified arguments, and the derivatives with respect to the parameters (taking any specified mask into account). :param x: the value(s) to evaluate at
385,327
def _CheckCacheFileForMatch(self, cache_filename, scopes): creds = { : sorted(list(scopes)) if scopes else None, : self.__service_account_name, } cache_file = _MultiProcessCacheFile(cache_filename) try: cached_creds_str = cache_file.LockedRead() if not cached_creds_str: return None cached_creds = json.loads(cached_creds_str) if creds[] == cached_creds[]: if creds[] in (None, cached_creds[]): return cached_creds[] except KeyboardInterrupt: raise except: pass
Checks the cache file to see if it matches the given credentials. Args: cache_filename: Cache filename to check. scopes: Scopes for the desired credentials. Returns: List of scopes (if cache matches) or None.
385,328
def get_ip_addr(self) -> str: output, _ = self._execute( , self.device_sn, , , , , , , ) ip_addr = re.findall( r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", output) if not ip_addr: raise ConnectionError( ) return ip_addr[0]
Show IP Address.
385,329
def get_guest_connection_status(self, userid): rd = .join((, userid, )) results = self._request(rd) if results[] == 1: return True else: return False
Get guest vm connection status.
385,330
def load_handgeometry(): dataset_path = _load() df = _load_csv(dataset_path, ) X = _load_images(os.path.join(dataset_path, ), df.image) y = df.target.values return Dataset(load_handgeometry.__doc__, X, y, r2_score)
Hand Geometry Dataset. The data of this dataset is a 3d numpy array vector with shape (224, 224, 3) containing 112 224x224 RGB photos of hands, and the target is a 1d numpy float array containing the width of the wrist in centimeters.
385,331
def is_zone_running(self, zone): self.update_controller_info() if self.running is None or not self.running: return False if int(self.running[0][]) == zone: return True return False
Returns the state of the specified zone. :param zone: The zone to check. :type zone: int :returns: Returns True if the zone is currently running, otherwise returns False if the zone is not running. :rtype: boolean
385,332
def Disconnect(self): device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException(, name=) device = mockobject.objects[device_path] try: device.props[AUDIO_IFACE][] = dbus.String("disconnected", variant_level=1) device.EmitSignal(AUDIO_IFACE, , , [ , dbus.String("disconnected", variant_level=1), ]) except KeyError: pass device.props[DEVICE_IFACE][] = dbus.Boolean(False, variant_level=1) device.EmitSignal(DEVICE_IFACE, , , [ , dbus.Boolean(False, variant_level=1), ])
Disconnect a device
385,333
def is_build_dir(self, folder_name): url = % urljoin(self.base_url, self.monthly_build_list_regex, folder_name) if self.application in APPLICATIONS_MULTI_LOCALE \ and self.locale != : url = % urljoin(url, self.locale) parser = self._create_directory_parser(url) pattern = re.compile(self.binary_regex, re.IGNORECASE) for entry in parser.entries: try: pattern.match(entry).group() return True except Exception: continue return False
Return whether or not the given dir contains a build.
385,334
def log(self, logger=None, label=None, eager=False): if self.closed(): raise ValueError("Attempt to call log() on a closed Queryable.") if logger is None: return self if label is None: label = repr(self) if eager: return self._create(self._eager_log_result(logger, label)) return self._create(self._generate_lazy_log_result(logger, label))
Log query result consumption details to a logger. Args: logger: Any object which supports a debug() method which accepts a str, such as a Python standard library logger object from the logging module. If logger is not provided or is None, this method has no logging side effects. label: An optional label which will be inserted into each line of logging output produced by this particular use of log eager: An optional boolean which controls how the query result will be consumed. If True, the sequence will be consumed and logged in its entirety. If False (the default) the sequence will be evaluated and logged lazily as it consumed. Warning: Use of eager=True requires use of sufficient memory to hold the entire sequence which is obviously not possible with infinite sequences. Use with care! Returns: A queryable over the unaltered source sequence. Raises: AttributeError: If logger does not support a debug() method. ValueError: If the Queryable has been closed.
385,335
def aesCCM(key, key_handle, nonce, data, decrypt=False): if decrypt: (data, saved_mac) = _split_data(data, len(data) - pyhsm.defines.YSM_AEAD_MAC_SIZE) nonce = pyhsm.util.input_validate_nonce(nonce, pad = True) mac = _cbc_mac(key, key_handle, nonce, len(data)) counter = _ctr_counter(key_handle, nonce, value = 0) ctr_aes = AES.new(key, AES.MODE_CTR, counter = counter.next) out = [] while data: (thisblock, data) = _split_data(data, pyhsm.defines.YSM_BLOCK_SIZE) if decrypt: aes_out = ctr_aes.decrypt(thisblock) mac.update(aes_out) else: mac.update(thisblock) aes_out = ctr_aes.encrypt(thisblock) out.append(aes_out) counter.value = 0 mac.finalize(counter.pack()) if decrypt: if mac.get() != saved_mac: raise pyhsm.exception.YHSM_Error() else: out.append(mac.get()) return .join(out)
Function implementing YubiHSM AEAD encrypt/decrypt in software.
385,336
def _write_single_sample(self, sample): bytes = sample.extras.get("responseHeadersSize", 0) + 2 + sample.extras.get("responseBodySize", 0) message = sample.error_msg if not message: message = sample.extras.get("responseMessage") if not message: for sample in sample.subsamples: if sample.error_msg: message = sample.error_msg break elif sample.extras.get("responseMessage"): message = sample.extras.get("responseMessage") break self.writer.writerow({ "timeStamp": int(1000 * sample.start_time), "elapsed": int(1000 * sample.duration), "Latency": 0, "label": sample.test_case, "bytes": bytes, "responseCode": sample.extras.get("responseCode"), "responseMessage": message, "allThreads": self.concurrency, "success": "true" if sample.status == "PASSED" else "false", }) self.out_stream.flush()
:type sample: Sample
385,337
def get_uids(self, filename=None): self._update() return [Abook._gen_uid(self._book[entry]) for entry in self._book.sections()]
Return a list of UIDs filename -- unused, for API compatibility only
385,338
async def _get_smallest_env(self): async def slave_task(mgr_addr): r_manager = await self.env.connect(mgr_addr, timeout=TIMEOUT) ret = await r_manager.get_agents(addr=True) return mgr_addr, len(ret) sizes = await create_tasks(slave_task, self.addrs, flatten=False) return sorted(sizes, key=lambda x: x[1])[0][0]
Get address of the slave environment manager with the smallest number of agents.
385,339
def debug_sync(self, conn_id, cmd_name, cmd_args, progress_callback): done = threading.Event() result = {} def _debug_done(conn_id, adapter_id, success, retval, reason): result[] = success result[] = reason result[] = retval done.set() self.debug_async(conn_id, cmd_name, cmd_args, progress_callback, _debug_done) done.wait() return result
Asynchronously complete a named debug command. The command name and arguments are passed to the underlying device adapter and interpreted there. If the command is long running, progress_callback may be used to provide status updates. Callback is called when the command has finished. Args: conn_id (int): A unique identifier that will refer to this connection cmd_name (string): the name of the debug command we want to invoke cmd_args (dict): any arguments that we want to send with this command. progress_callback (callable): A function to be called with status on our progress, called as: progress_callback(done_count, total_count)
385,340
def print_token(self, token_node_index): err_msg = "The given node is not a token node." assert isinstance(self.nodes[token_node_index], TokenNode), err_msg onset = self.nodes[token_node_index].onset offset = self.nodes[token_node_index].offset return self.text[onset:offset]
returns the string representation of a token.
385,341
def resolve_data_objects(objects, project=None, folder=None, batchsize=1000): if not isinstance(batchsize, int) or batchsize <= 0 or batchsize > 1000: raise ValueError("batchsize for resolve_data_objects must be a positive integer not exceeding 1000") args = {} if project: args.update({: project}) if folder: args.update({: folder}) results = [] for i in range(0, len(objects), batchsize): args.update({: objects[i:(i+batchsize)]}) results.extend(dxpy.api.system_resolve_data_objects(args)[]) return results
:param objects: Data object specifications, each with fields "name" (required), "folder", and "project" :type objects: list of dictionaries :param project: ID of project context; a data object's project defaults to this if not specified for that object :type project: string :param folder: Folder path within the project; a data object's folder path defaults to this if not specified for that object :type folder: string :param batchsize: Number of objects to resolve in each batch call to system_resolve_data_objects; defaults to 1000 and is only used for testing (must be a positive integer not exceeding 1000) :type batchsize: int :returns: List of results parallel to input objects, where each entry is a list containing 0 or more dicts, each corresponding to a resolved object :rtype: List of lists of dictionaries Each returned element is a list of dictionaries with keys "project" and "id". The number of dictionaries for each element may be 0, 1, or more.
385,342
def lookup(self, path, is_committed=True, with_proof=False) -> (str, int): assert path is not None head_hash = self.state.committedHeadHash if is_committed else self.state.headHash encoded, proof = self._get_value_from_state(path, head_hash, with_proof=with_proof) if encoded: value, last_seq_no, last_update_time = decode_state_value(encoded) return value, last_seq_no, last_update_time, proof return None, None, None, proof
Queries state for data on specified path :param path: path to data :param is_committed: queries the committed state root if True else the uncommitted root :param with_proof: creates proof if True :return: data
385,343
def download_file_with_progress_bar(url): request = requests.get(url, stream=True) if request.status_code == 404: msg = ( .format(url)) logger.error(msg) sys.exit() total_size = int(request.headers["Content-Length"]) chunk_size = 1024 bars = int(total_size / chunk_size) bytes_io = io.BytesIO() pbar = tqdm(request.iter_content(chunk_size=chunk_size), total=bars, unit="kb", leave=False) for chunk in pbar: bytes_io.write(chunk) return bytes_io
Downloads a file from the given url, displays a progress bar. Returns a io.BytesIO object
385,344
def _correct_build_location(self): if self.source_dir is not None: return assert self.req is not None assert self._temp_build_dir.path assert (self._ideal_build_dir is not None and self._ideal_build_dir.path) old_location = self._temp_build_dir.path self._temp_build_dir.path = None new_location = self.build_location(self._ideal_build_dir) if os.path.exists(new_location): raise InstallationError( % display_path(new_location)) logger.debug( , self, display_path(old_location), display_path(new_location), ) shutil.move(old_location, new_location) self._temp_build_dir.path = new_location self._ideal_build_dir = None self.source_dir = os.path.normpath(os.path.abspath(new_location)) self._egg_info_path = None if self.metadata_directory: old_meta = self.metadata_directory rel = os.path.relpath(old_meta, start=old_location) new_meta = os.path.join(new_location, rel) new_meta = os.path.normpath(os.path.abspath(new_meta)) self.metadata_directory = new_meta
Move self._temp_build_dir to self._ideal_build_dir/self.req.name For some requirements (e.g. a path to a directory), the name of the package is not available until we run egg_info, so the build_location will return a temporary directory and store the _ideal_build_dir. This is only called by self.run_egg_info to fix the temporary build directory.
385,345
def fav_songs(self): if self._fav_songs is None: songs_data = self._api.user_favorite_songs(self.identifier) self._fav_songs = [] if not songs_data: return for song_data in songs_data: song = _deserialize(song_data, NestedSongSchema) self._fav_songs.append(song) return self._fav_songs
FIXME: 支持获取所有的收藏歌曲
385,346
def extension_counts(container=None, file_list=None, return_counts=True): if file_list is None: file_list = get_container_contents(container, split_delim=)[] extensions = dict() for item in file_list: filename,ext = os.path.splitext(item) if ext == : if return_counts == False: extensions = update_dict(extensions,,item) else: extensions = update_dict_sum(extensions,) else: if return_counts == False: extensions = update_dict(extensions,ext,item) else: extensions = update_dict_sum(extensions,ext) return extensions
extension counts will return a dictionary with counts of file extensions for an image. :param container: if provided, will use container as image. Can also provide :param image_package: if provided, can be used instead of container :param file_list: the complete list of files :param return_counts: return counts over dict with files. Default True
385,347
def connections_of(self, target): return gen.chain( ((r,i) for i in self.find(target,r)) for r in self.relations_of(target) )
generate tuples containing (relation, object_that_applies)
385,348
def fast_forward(self, start_dt): if self.from_stdin: return else: max_mark = self.filesize step_size = max_mark self.filehandle.seek(0) le = self.next() if le.datetime and le.datetime >= start_dt: self.filehandle.seek(0) return le = None self.filehandle.seek(0) while abs(step_size) > 100: step_size = ceil(step_size / 2.) self.filehandle.seek(step_size, 1) le = self._find_curr_line() if not le: break if le.datetime >= start_dt: step_size = -abs(step_size) else: step_size = abs(step_size) if not le: return while self.filehandle.tell() >= 2 and (le.datetime is None or le.datetime >= start_dt): self.filehandle.seek(-2, 1) le = self._find_curr_line(prev=True)
Fast-forward file to given start_dt datetime obj using binary search. Only fast for files. Streams need to be forwarded manually, and it will miss the first line that would otherwise match (as it consumes the log line).
385,349
def map_ids(queries,frm=,to=, organism_taxid=9606,test=False): url = params = { :frm, :to, :, :organism_taxid, :.join(queries), } response = requests.get(url, params=params) if test: print(response.url) if response.ok: df=pd.read_table(response.url) df.columns=[frm,to] return df else: print(, response.status_code)
https://www.uniprot.org/help/api_idmapping
385,350
def upload_file(self, metadata, filename, signer=None, sign_password=None, filetype=, pyversion=, keystore=None): self.check_credentials() if not os.path.exists(filename): raise DistlibException( % filename) metadata.validate() d = metadata.todict() sig_file = None if signer: if not self.gpg: logger.warning() else: sig_file = self.sign_file(filename, signer, sign_password, keystore) with open(filename, ) as f: file_data = f.read() md5_digest = hashlib.md5(file_data).hexdigest() sha256_digest = hashlib.sha256(file_data).hexdigest() d.update({ : , : , : filetype, : pyversion, : md5_digest, : sha256_digest, }) files = [(, os.path.basename(filename), file_data)] if sig_file: with open(sig_file, ) as f: sig_data = f.read() files.append((, os.path.basename(sig_file), sig_data)) shutil.rmtree(os.path.dirname(sig_file)) request = self.encode_request(d.items(), files) return self.send_request(request)
Upload a release file to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the file to be uploaded. :param filename: The pathname of the file to be uploaded. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :param filetype: The type of the file being uploaded. This is the distutils command which produced that file, e.g. ``sdist`` or ``bdist_wheel``. :param pyversion: The version of Python which the release relates to. For code compatible with any Python, this would be ``source``, otherwise it would be e.g. ``3.2``. :param keystore: The path to a directory which contains the keys used in signing. If not specified, the instance's ``gpg_home`` attribute is used instead. :return: The HTTP response received from PyPI upon submission of the request.
385,351
def create(cls, csr, duration, package, altnames=None, dcv_method=None): params = {: csr, : package, : duration} if altnames: params[] = altnames if dcv_method: params[] = dcv_method try: result = cls.call(, params) except UsageError: params[] = True msg = .join([ % (err[], err[]) for err in cls.call(, params)]) cls.error(msg) raise if dcv_method in (, ): cls.advice_dcv_method(csr, package, altnames, dcv_method, cert_id=result[].get()) return result
Create a new certificate.
385,352
def create_tablefn_map(fns, pqdb, poolnames): poolmap = {name: pid for (name, pid) in pqdb.get_all_poolnames()} pqdb.store_table_files([(poolmap[pool], os.path.basename(fn)) for fn, pool in zip(fns, poolnames)]) return pqdb.get_tablefn_map()
Stores protein/peptide table names in DB, returns a map with their respective DB IDs
385,353
def drag_sphere(Re, Method=None, AvailableMethods=False): rs solution. * If 0.01 <= Re < 0.1, linearly combine with StokesBaratiStokesBaratiBarati_high def list_methods(): methods = [] for key, (func, Re_min, Re_max) in drag_sphere_correlations.items(): if (Re_min is None or Re > Re_min) and (Re_max is None or Re < Re_max): methods.append(key) return methods if AvailableMethods: return list_methods() if not Method: if Re > 0.1: if Re <= 212963.26847812787: return Barati(Re) elif Re <= 1E6: return Barati_high(Re) else: raise ValueError() elif Re >= 0.01: ratio = (Re - 0.01)/(0.1 - 0.01)
r'''This function handles calculation of drag coefficient on spheres. Twenty methods are available, all requiring only the Reynolds number of the sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will be automatically selected if none is specified. The full list of correlations valid for a given Reynolds number can be obtained with the `AvailableMethods` flag. If no correlation is selected, the following rules are used: * If Re < 0.01, use Stoke's solution. * If 0.01 <= Re < 0.1, linearly combine 'Barati' with Stokes's solution such that at Re = 0.1 the solution is 'Barati', and at Re = 0.01 the solution is 'Stokes'. * If 0.1 <= Re <= ~212963, use the 'Barati' solution. * If ~212963 < Re <= 1E6, use the 'Barati_high' solution. * For Re > 1E6, raises an exception; no valid results have been found. Examples -------- >>> drag_sphere(200) 0.7682237950389874 Parameters ---------- Re : float Particle Reynolds number of the sphere using the surrounding fluid density and viscosity, [-] Returns ------- Cd : float Drag coefficient [-] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate `Cd` with the given `Re` Other Parameters ---------------- Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate `Cd` with the given `Re`
385,354
def WriteHashBlobReferences(self, references_by_hash, cursor): values = [] for hash_id, blob_refs in iteritems(references_by_hash): refs = rdf_objects.BlobReferences(items=blob_refs).SerializeToString() values.append({ "hash_id": hash_id.AsBytes(), "blob_references": refs, }) _Insert(cursor, "hash_blob_references", values)
Writes blob references for a given set of hashes.
385,355
def fit(self, X, y): self._data = X self._classes = np.unique(y) self._labels = y self._is_fitted = True
Fit the model using X as training data and y as target values
385,356
def _variable(lexer): names = _names(lexer) tok = next(lexer) if isinstance(tok, LBRACK): indices = _indices(lexer) _expect_token(lexer, {RBRACK}) else: lexer.unpop_token(tok) indices = tuple() return (, names, indices)
Return a variable expression.
385,357
def splitStis(stisfile, sci_count): newfiles = [] toclose = False if isinstance(stisfile, str): f = fits.open(stisfile) toclose = True else: f = stisfile hdu0 = f[0].copy() stisfilename = stisfile.filename() for count in range(1,sci_count+1): fitsobj = fits.HDUList() fitsobj.append(hdu0) hdu = f[(,count)].copy() fitsobj.append(hdu) rootname = hdu.header[] newfilename = fileutil.buildNewRootname(rootname, extn=) try: if f[(, count)].data is None: raise ValueError if f[(, count)].data is None: raise ValueError hdu = f[(,count)].copy() fitsobj.append(hdu) hdu = f[(,count)].copy() fitsobj.append(hdu) fitsobj[1].header[] = 1 fitsobj[2].header[] = 1 fitsobj[3].header[] = 1 except ValueError: print() print( %(count, stisfile)) print() print() continue if (os.path.exists(newfilename)): os.remove(newfilename) print(" Replacing "+newfilename+"...") fitsobj.writeto(newfilename) fitsobj.close() fitsobj = fits.open(newfilename, mode=) newfiles.append(fitsobj) f.close() sptfilename = fileutil.buildNewRootname(stisfilename, extn=) try: sptfile = fits.open(sptfilename) except IOError: print( % sptfilename) return newfiles if sptfile: hdu0 = sptfile[0].copy() try: for count in range(1,sci_count+1): fitsobj = fits.HDUList() fitsobj.append(hdu0) hdu = sptfile[count].copy() fitsobj.append(hdu) rootname = hdu.header[] newfilename = fileutil.buildNewRootname(rootname, extn=) fitsobj[1].header[] = 1 if (os.path.exists(newfilename)): os.remove(newfilename) print(" Replacing "+newfilename+"...") fitsobj.writeto(newfilename) except: print("Warning: Unable to split spt file %s " % sptfilename) if toclose: sptfile.close() return newfiles
Split a STIS association file into multiple imset MEF files. Split the corresponding spt file if present into single spt files. If an spt file can't be split or is missing a Warning is printed. Returns ------- names: list a list with the names of the new flt files.
385,358
def set_lines( lines, target_level, indent_string=" ", indent_empty_lines=False ): first_non_empty_line_index = _get_first_non_empty_line_index( lines ) first_line_original_level = get_line_level( lines[first_non_empty_line_index], indent_string ) for i in range(first_non_empty_line_index, len(lines)): if not indent_empty_lines and lines[i] == "": continue line_i_unindented = get_line_unindented( lines[i], indent_string ) line_i_level = get_line_level( lines[i], indent_string ) on_second_line_or_later = i > first_non_empty_line_index if on_second_line_or_later: first_line_final_level = get_line_level( lines[first_non_empty_line_index], indent_string ) relative_indent_move = first_line_final_level - first_line_original_level target_level = line_i_level + relative_indent_move if line_i_level == target_level: continue lines[i] = indent_string * target_level + line_i_unindented
Sets indentation for the given set of :lines:.
385,359
def mutualInformation(sp, activeColumnsCurrentEpoch, column_1, column_2): i, j = column_1, column_2 batchSize = activeColumnsCurrentEpoch.shape[0] ci, cj, cij = 0., 0., dict([((0,0),0.), ((1,0),0.), ((0,1),0.), ((1,1),0.)]) for t in range(batchSize): ai = activeColumnsCurrentEpoch[t, i] aj = activeColumnsCurrentEpoch[t, j] cij[(ai, aj)] += 1. ci += ai cj += aj Iij = 0 for a,b in [(0,0), (1,0), (0,1), (1,1)]: pij = cij[(a,b)]/batchSize pi = ci/batchSize if a == 1 else 1. - ci/batchSize pj = cj/batchSize if b == 1 else 1. - cj/batchSize Iij += pij * np.log2(pij/(pi*pj)) if pij > 0 else 0 return Iij
Computes the mutual information of the binary variables that represent the activation probabilities of two columns. The mutual information I(X,Y) of two random variables is given by \[ I (X,Y) = \sum_{x,y} p(x,y) log( p(x,y) / ( p(x) p(y) ) ). \] (https://en.wikipedia.org/wiki/Mutual_information)
385,360
def connect(self, hostname=None, port=None): if hostname is not None: self.host = hostname conn = self._connect_hook(self.host, port) self.os_guesser.protocol_info(self.get_remote_version()) self.auto_driver = driver_map[self.guess_os()] if self.get_banner(): self.os_guesser.data_received(self.get_banner(), False) return conn
Opens the connection to the remote host or IP address. :type hostname: string :param hostname: The remote host or IP address. :type port: int :param port: The remote TCP port number.
385,361
def guess_settings(self, major, minor): version = major, minor if self.vbr_method == 2: if version in ((3, 90), (3, 91), (3, 92)) and self.encoding_flags: if self.bitrate < 255: return u"--alt-preset %d" % self.bitrate else: return u"--alt-preset %d+" % self.bitrate if self.preset_used != 0: return u"--preset %d" % self.preset_used elif self.bitrate < 255: return u"--abr %d" % self.bitrate else: return u"--abr %d+" % self.bitrate elif self.vbr_method == 1: if self.preset_used == 0: if self.bitrate < 255: return u"-b %d" % self.bitrate else: return u"-b 255+" elif self.preset_used == 1003: return u"--preset insane" return u"-b %d" % self.preset_used elif version in ((3, 90), (3, 91), (3, 92)): preset_key = (self.vbr_quality, self.quality, self.vbr_method, self.lowpass_filter, self.ath_type) if preset_key == (1, 2, 4, 19500, 3): return u"--preset r3mix" if preset_key == (2, 2, 3, 19000, 4): return u"--alt-preset standard" if preset_key == (2, 2, 3, 19500, 2): return u"--alt-preset extreme" if self.vbr_method == 3: return u"-V %s" % self.vbr_quality elif self.vbr_method in (4, 5): return u"-V %s --vbr-new" % self.vbr_quality elif version in ((3, 93), (3, 94), (3, 95), (3, 96), (3, 97)): if self.preset_used == 1001: return u"--preset standard" elif self.preset_used == 1002: return u"--preset extreme" elif self.preset_used == 1004: return u"--preset fast standard" elif self.preset_used == 1005: return u"--preset fast extreme" elif self.preset_used == 1006: return u"--preset medium" elif self.preset_used == 1007: return u"--preset fast medium" if self.vbr_method == 3: return u"-V %s" % self.vbr_quality elif self.vbr_method in (4, 5): return u"-V %s --vbr-new" % self.vbr_quality elif version == (3, 98): if self.vbr_method == 3: return u"-V %s --vbr-old" % self.vbr_quality elif self.vbr_method in (4, 5): return u"-V %s" % self.vbr_quality elif version >= (3, 99): if self.vbr_method == 3: return u"-V %s --vbr-old" % self.vbr_quality elif self.vbr_method in (4, 5): p = self.vbr_quality adjust_key = (p, self.bitrate, self.lowpass_filter) p = { (5, 32, 0): 7, (5, 8, 0): 8, (6, 8, 0): 9, }.get(adjust_key, p) return u"-V %s" % p return u""
Gives a guess about the encoder settings used. Returns an empty string if unknown. The guess is mostly correct in case the file was encoded with the default options (-V --preset --alt-preset --abr -b etc) and no other fancy options. Args: major (int) minor (int) Returns: text
385,362
def dump(new_data): *{: } if not isinstance(new_data, dict): if isinstance(ast.literal_eval(new_data), dict): new_data = ast.literal_eval(new_data) else: return False try: datastore_path = os.path.join(__opts__[], ) with salt.utils.files.fopen(datastore_path, ) as fn_: serial = salt.payload.Serial(__opts__) serial.dump(new_data, fn_) return True except (IOError, OSError, NameError): return False
Replace the entire datastore with a passed data structure CLI Example: .. code-block:: bash salt '*' data.dump '{'eggs': 'spam'}'
385,363
def maps_get_default_rules_output_rules_action(self, **kwargs): config = ET.Element("config") maps_get_default_rules = ET.Element("maps_get_default_rules") config = maps_get_default_rules output = ET.SubElement(maps_get_default_rules, "output") rules = ET.SubElement(output, "rules") action = ET.SubElement(rules, "action") action.text = kwargs.pop() callback = kwargs.pop(, self._callback) return callback(config)
Auto Generated Code
385,364
def _work_request(self, worker, md5=None): if not md5 and not self.session.md5: return elif not md5: md5 = self.session.md5 if self.workbench.is_sample_set(md5): return self.workbench.set_work_request(worker, md5) try: return self.workbench.work_request(worker, md5) except zerorpc.exceptions.RemoteError as e: return repr_to_str_decorator.r_to_s(self._data_not_found)(e)
Wrapper for a work_request to workbench
385,365
def set_payload_format(self, payload_format): request = { "command": "payload_format", "format": payload_format } status = self._check_command_response_status(request) self.format = payload_format return status
Set the payload format for messages sent to and from the VI. Returns True if the command was successful.
385,366
def replace(self, photo_file, **kwds): result = self._client.photo.replace(self, photo_file, **kwds) self._replace_fields(result.get_fields())
Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace this photo.
385,367
def pca_to_mapping(pca,**extra_props): from .axes import sampling_axes method = extra_props.pop(,sampling_axes) return dict( axes=pca.axes.tolist(), covariance=method(pca).tolist(), **extra_props)
A helper to return a mapping of a PCA result set suitable for reconstructing a planar error surface in other software packages kwargs: method (defaults to sampling axes)
385,368
def get_subprocess_output(cls, command, ignore_stderr=True, **kwargs): if ignore_stderr is False: kwargs.setdefault(, subprocess.STDOUT) try: return subprocess.check_output(command, **kwargs).decode().strip() except (OSError, subprocess.CalledProcessError) as e: subprocess_output = getattr(e, , ).strip() raise cls.ExecutionError(str(e), subprocess_output)
Get the output of an executed command. :param command: An iterable representing the command to execute (e.g. ['ls', '-al']). :param ignore_stderr: Whether or not to ignore stderr output vs interleave it with stdout. :raises: `ProcessManager.ExecutionError` on `OSError` or `CalledProcessError`. :returns: The output of the command.
385,369
def pack(chunks, r=32): if r < 1: raise ValueError() n = shift = 0 for c in chunks: n += c << shift shift += r return n
Return integer concatenating integer chunks of r > 0 bit-length. >>> pack([0, 1, 0, 1, 0, 1], 1) 42 >>> pack([0, 1], 8) 256 >>> pack([0, 1], 0) Traceback (most recent call last): ... ValueError: pack needs r > 0
385,370
def map_exp_ids(self, exp): names = self.exp_feature_names if self.discretized_feature_names is not None: names = self.discretized_feature_names return [(names[x[0]], x[1]) for x in exp]
Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight)
385,371
def nvmlDeviceGetMemoryInfo(handle): r c_memory = c_nvmlMemory_t() fn = _nvmlGetFunctionPointer("nvmlDeviceGetMemoryInfo") ret = fn(handle, byref(c_memory)) _nvmlCheckReturn(ret) return bytes_to_str(c_memory)
r""" /** * Retrieves the amount of used, free and total memory available on the device, in bytes. * * For all products. * * Enabling ECC reduces the amount of total available memory, due to the extra required parity bits. * Under WDDM most device memory is allocated and managed on startup by Windows. * * Under Linux and Windows TCC, the reported amount of used memory is equal to the sum of memory allocated * by all active channels on the device. * * See \ref nvmlMemory_t for details on available memory info. * * @param device The identifier of the target device * @param memory Reference in which to return the memory information * * @return * - \ref NVML_SUCCESS if \a memory has been populated * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a memory is NULL * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \ref NVML_ERROR_UNKNOWN on any unexpected error */ nvmlReturn_t DECLDIR nvmlDeviceGetMemoryInfo
385,372
def connected_subgraph(self, node): G = self.G subgraph_nodes = set() subgraph_nodes.add(node) subgraph_nodes.update(dag.ancestors(G, node)) subgraph_nodes.update(dag.descendants(G, node)) graph_changed = True while graph_changed: initial_count = len(subgraph_nodes) old_nodes = set(subgraph_nodes) for n in old_nodes: subgraph_nodes.update(dag.ancestors(G, n)) subgraph_nodes.update(dag.descendants(G, n)) current_count = len(subgraph_nodes) graph_changed = current_count > initial_count return G.subgraph(subgraph_nodes)
Returns the subgraph containing the given node, its ancestors, and its descendants. Parameters ---------- node : str We want to create the subgraph containing this node. Returns ------- subgraph : networkx.DiGraph The subgraph containing the specified node.
385,373
def coin_toss(self): doc = self.get_doc() table = doc() giTable = sportsref.utils.parse_info_table(table) if in giTable: pass else: return None
Gets information relating to the opening coin toss. Keys are: * wonToss - contains the ID of the team that won the toss * deferred - bool whether the team that won the toss deferred it :returns: Dictionary of coin toss-related info.
385,374
def ping_directories(self, request, queryset, messages=True): for directory in settings.PING_DIRECTORIES: pinger = DirectoryPinger(directory, queryset) pinger.join() if messages: success = 0 for result in pinger.results: if not result.get(, True): success += 1 else: self.message_user(request, % (directory, result[])) if success: self.message_user( request, _( ) % {: directory, : success})
Ping web directories for selected entries.
385,375
def _read(self): event = self._stick_file.read(self.EVENT_SIZE) (tv_sec, tv_usec, type, code, value) = struct.unpack(self.EVENT_FORMAT, event) if type == self.EV_KEY: return InputEvent( timestamp=tv_sec + (tv_usec / 1000000), direction={ self.KEY_UP: DIRECTION_UP, self.KEY_DOWN: DIRECTION_DOWN, self.KEY_LEFT: DIRECTION_LEFT, self.KEY_RIGHT: DIRECTION_RIGHT, self.KEY_ENTER: DIRECTION_MIDDLE, }[code], action={ self.STATE_PRESS: ACTION_PRESSED, self.STATE_RELEASE: ACTION_RELEASED, self.STATE_HOLD: ACTION_HELD, }[value]) else: return None
Reads a single event from the joystick, blocking until one is available. Returns `None` if a non-key event was read, or an `InputEvent` tuple describing the event otherwise.
385,376
def reload_class_methods(self, class_, verbose=True): if verbose: print( % (self, class_)) self.__class__ = class_ for key in dir(class_): func = getattr(class_, key) if isinstance(func, types.MethodType): inject_func_as_method(self, func, class_=class_, allow_override=True, verbose=verbose)
rebinds all class methods Args: self (object): class instance to reload class_ (type): type to reload as Example: >>> # DISABLE_DOCTEST >>> from utool.util_class import * # NOQA >>> self = '?' >>> class_ = '?' >>> result = reload_class_methods(self, class_) >>> print(result)
385,377
def headers(self): headers = self.conn.issue_command("Headers") res = [] for header in headers.split("\r"): key, value = header.split(": ", 1) for line in value.split("\n"): res.append((_normalize_header(key), line)) return res
Returns a list of the last HTTP response headers. Header keys are normalized to capitalized form, as in `User-Agent`.
385,378
def GC_partial(portion): sequence_count = collections.Counter(portion) gc = ((sum([sequence_count[i] for i in ]) + sum([sequence_count[i] for i in ]) / 3.0 + 2 * sum([sequence_count[i] for i in ]) / 3.0 + sum([sequence_count[i] for i in ]) / 2.0) / len(portion)) return 0 or 100 * gc
Manually compute GC content percentage in a DNA string, taking ambiguous values into account (according to standard IUPAC notation).
385,379
def _par_write(self, dirname): filename = dirname + + with open(filename, ) as parfile: for template in self.templates: for key in template.__dict__.keys(): if key not in [, ]: parfile.write(key + + str(template.__dict__[key]) + ) parfile.write() return self
Internal write function to write a formatted parameter file. :type dirname: str :param dirname: Directory to write the parameter file to.
385,380
def put_intent(name=None, description=None, slots=None, sampleUtterances=None, confirmationPrompt=None, rejectionStatement=None, followUpPrompt=None, conclusionStatement=None, dialogCodeHook=None, fulfillmentActivity=None, parentIntentSignature=None, checksum=None): pass
Creates an intent or replaces an existing intent. To define the interaction between the user and your bot, you use one or more intents. For a pizza ordering bot, for example, you would create an OrderPizza intent. To create an intent or replace an existing intent, you must provide the following: You can specify other optional information in the request, such as: If you specify an existing intent name to update the intent, Amazon Lex replaces the values in the $LATEST version of the slot type with the values in the request. Amazon Lex removes fields that you don't provide in the request. If you don't specify the required fields, Amazon Lex throws an exception. For more information, see how-it-works . This operation requires permissions for the lex:PutIntent action. See also: AWS API Documentation :example: response = client.put_intent( name='string', description='string', slots=[ { 'name': 'string', 'description': 'string', 'slotConstraint': 'Required'|'Optional', 'slotType': 'string', 'slotTypeVersion': 'string', 'valueElicitationPrompt': { 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'maxAttempts': 123, 'responseCard': 'string' }, 'priority': 123, 'sampleUtterances': [ 'string', ], 'responseCard': 'string' }, ], sampleUtterances=[ 'string', ], confirmationPrompt={ 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'maxAttempts': 123, 'responseCard': 'string' }, rejectionStatement={ 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'responseCard': 'string' }, followUpPrompt={ 'prompt': { 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'maxAttempts': 123, 'responseCard': 'string' }, 'rejectionStatement': { 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'responseCard': 'string' } }, conclusionStatement={ 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'responseCard': 'string' }, dialogCodeHook={ 'uri': 'string', 'messageVersion': 'string' }, fulfillmentActivity={ 'type': 'ReturnIntent'|'CodeHook', 'codeHook': { 'uri': 'string', 'messageVersion': 'string' } }, parentIntentSignature='string', checksum='string' ) :type name: string :param name: [REQUIRED] The name of the intent. The name is not case sensitive. The name can't match a built-in intent name, or a built-in intent name with 'AMAZON.' removed. For example, because there is a built-in intent called AMAZON.HelpIntent , you can't create a custom intent called HelpIntent . For a list of built-in intents, see Standard Built-in Intents in the Alexa Skills Kit . :type description: string :param description: A description of the intent. :type slots: list :param slots: An array of intent slots. At runtime, Amazon Lex elicits required slot values from the user using prompts defined in the slots. For more information, see xref linkend='how-it-works'/. (dict) --Identifies the version of a specific slot. name (string) -- [REQUIRED]The name of the slot. description (string) --A description of the slot. slotConstraint (string) -- [REQUIRED]Specifies whether the slot is required or optional. slotType (string) --The type of the slot, either a custom slot type that you defined or one of the built-in slot types. slotTypeVersion (string) --The version of the slot type. valueElicitationPrompt (dict) --The prompt that Amazon Lex uses to elicit the slot value from the user. messages (list) -- [REQUIRED]An array of objects, each of which provides a message string and its type. You can specify the message string in plain text or in Speech Synthesis Markup Language (SSML). (dict) --The message object that provides the message text and its type. contentType (string) -- [REQUIRED]The content type of the message string. content (string) -- [REQUIRED]The text of the message. maxAttempts (integer) -- [REQUIRED]The number of times to prompt the user for information. responseCard (string) --A response card. Amazon Lex uses this prompt at runtime, in the PostText API response. It substitutes session attributes and slot values for placeholders in the response card. For more information, see ex-resp-card . priority (integer) --Directs Lex the order in which to elicit this slot value from the user. For example, if the intent has two slots with priorities 1 and 2, AWS Lex first elicits a value for the slot with priority 1. If multiple slots share the same priority, the order in which Lex elicits values is arbitrary. sampleUtterances (list) --If you know a specific pattern with which users might respond to an Amazon Lex request for a slot value, you can provide those utterances to improve accuracy. This is optional. In most cases, Amazon Lex is capable of understanding user utterances. (string) -- responseCard (string) --A set of possible responses for the slot type used by text-based clients. A user chooses an option from the response card, instead of using text to reply. :type sampleUtterances: list :param sampleUtterances: An array of utterances (strings) that a user might say to signal the intent. For example, 'I want {PizzaSize} pizza', 'Order {Quantity} {PizzaSize} pizzas'. In each utterance, a slot name is enclosed in curly braces. (string) -- :type confirmationPrompt: dict :param confirmationPrompt: Prompts the user to confirm the intent. This question should have a yes or no answer. Amazon Lex uses this prompt to ensure that the user acknowledges that the intent is ready for fulfillment. For example, with the OrderPizza intent, you might want to confirm that the order is correct before placing it. For other intents, such as intents that simply respond to user questions, you might not need to ask the user for confirmation before providing the information. Note You you must provide both the rejectionStatement and the confirmationPrompt , or neither. messages (list) -- [REQUIRED]An array of objects, each of which provides a message string and its type. You can specify the message string in plain text or in Speech Synthesis Markup Language (SSML). (dict) --The message object that provides the message text and its type. contentType (string) -- [REQUIRED]The content type of the message string. content (string) -- [REQUIRED]The text of the message. maxAttempts (integer) -- [REQUIRED]The number of times to prompt the user for information. responseCard (string) --A response card. Amazon Lex uses this prompt at runtime, in the PostText API response. It substitutes session attributes and slot values for placeholders in the response card. For more information, see ex-resp-card . :type rejectionStatement: dict :param rejectionStatement: When the user answers 'no' to the question defined in confirmationPrompt , Amazon Lex responds with this statement to acknowledge that the intent was canceled. Note You must provide both the rejectionStatement and the confirmationPrompt , or neither. messages (list) -- [REQUIRED]A collection of message objects. (dict) --The message object that provides the message text and its type. contentType (string) -- [REQUIRED]The content type of the message string. content (string) -- [REQUIRED]The text of the message. responseCard (string) --At runtime, if the client is using the API, Amazon Lex includes the response card in the response. It substitutes all of the session attributes and slot values for placeholders in the response card. :type followUpPrompt: dict :param followUpPrompt: A user prompt for additional activity after an intent is fulfilled. For example, after the OrderPizza intent is fulfilled (your Lambda function placed an order with a pizzeria), you might prompt the user to find if they want to order a drink (assuming that you have defined an OrderDrink intent in your bot). Note The followUpPrompt and conclusionStatement are mutually exclusive. You can specify only one. For example, your bot may not solicit both the following: Follow up prompt - '$session.FirstName , your pizza order has been placed. Would you like to order a drink or a dessert?' Conclusion statement - '$session.FirstName , your pizza order has been placed.' prompt (dict) -- [REQUIRED]Obtains information from the user. messages (list) -- [REQUIRED]An array of objects, each of which provides a message string and its type. You can specify the message string in plain text or in Speech Synthesis Markup Language (SSML). (dict) --The message object that provides the message text and its type. contentType (string) -- [REQUIRED]The content type of the message string. content (string) -- [REQUIRED]The text of the message. maxAttempts (integer) -- [REQUIRED]The number of times to prompt the user for information. responseCard (string) --A response card. Amazon Lex uses this prompt at runtime, in the PostText API response. It substitutes session attributes and slot values for placeholders in the response card. For more information, see ex-resp-card . rejectionStatement (dict) -- [REQUIRED]If the user answers 'no' to the question defined in confirmationPrompt , Amazon Lex responds with this statement to acknowledge that the intent was canceled. messages (list) -- [REQUIRED]A collection of message objects. (dict) --The message object that provides the message text and its type. contentType (string) -- [REQUIRED]The content type of the message string. content (string) -- [REQUIRED]The text of the message. responseCard (string) --At runtime, if the client is using the API, Amazon Lex includes the response card in the response. It substitutes all of the session attributes and slot values for placeholders in the response card. :type conclusionStatement: dict :param conclusionStatement: The statement that you want Amazon Lex to convey to the user after the intent is successfully fulfilled by the Lambda function. This element is relevant only if you provide a Lambda function in the fulfillmentActivity . If you return the intent to the client application, you can't specify this element. Note The followUpPrompt and conclusionStatement are mutually exclusive. You can specify only one. messages (list) -- [REQUIRED]A collection of message objects. (dict) --The message object that provides the message text and its type. contentType (string) -- [REQUIRED]The content type of the message string. content (string) -- [REQUIRED]The text of the message. responseCard (string) --At runtime, if the client is using the API, Amazon Lex includes the response card in the response. It substitutes all of the session attributes and slot values for placeholders in the response card. :type dialogCodeHook: dict :param dialogCodeHook: Specifies a Lambda function to invoke for each user input. You can invoke this Lambda function to personalize user interaction. For example, suppose your bot determines that the user is John. Your Lambda function might retrieve John's information from a backend database and prepopulate some of the values. For example, if you find that John is gluten intolerant, you might set the corresponding intent slot, GlutenIntolerant , to true. You might find John's phone number and set the corresponding session attribute. uri (string) -- [REQUIRED]The Amazon Resource Name (ARN) of the Lambda function. messageVersion (string) -- [REQUIRED]The version of the request-response that you want Amazon Lex to use to invoke your Lambda function. For more information, see using-lambda . :type fulfillmentActivity: dict :param fulfillmentActivity: Describes how the intent is fulfilled. For example, after a user provides all of the information for a pizza order, fulfillmentActivity defines how the bot places an order with a local pizza store. You might configure Amazon Lex to return all of the intent information to the client application, or direct it to invoke a Lambda function that can process the intent (for example, place an order with a pizzeria). type (string) -- [REQUIRED]How the intent should be fulfilled, either by running a Lambda function or by returning the slot data to the client application. codeHook (dict) --A description of the Lambda function that is run to fulfill the intent. uri (string) -- [REQUIRED]The Amazon Resource Name (ARN) of the Lambda function. messageVersion (string) -- [REQUIRED]The version of the request-response that you want Amazon Lex to use to invoke your Lambda function. For more information, see using-lambda . :type parentIntentSignature: string :param parentIntentSignature: A unique identifier for the built-in intent to base this intent on. To find the signature for an intent, see Standard Built-in Intents in the Alexa Skills Kit . :type checksum: string :param checksum: Identifies a specific revision of the $LATEST version. When you create a new intent, leave the checksum field blank. If you specify a checksum you get a BadRequestException exception. When you want to update a intent, set the checksum field to the checksum of the most recent revision of the $LATEST version. If you don't specify the checksum field, or if the checksum does not match the $LATEST version, you get a PreconditionFailedException exception. :rtype: dict :return: { 'name': 'string', 'description': 'string', 'slots': [ { 'name': 'string', 'description': 'string', 'slotConstraint': 'Required'|'Optional', 'slotType': 'string', 'slotTypeVersion': 'string', 'valueElicitationPrompt': { 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'maxAttempts': 123, 'responseCard': 'string' }, 'priority': 123, 'sampleUtterances': [ 'string', ], 'responseCard': 'string' }, ], 'sampleUtterances': [ 'string', ], 'confirmationPrompt': { 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'maxAttempts': 123, 'responseCard': 'string' }, 'rejectionStatement': { 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'responseCard': 'string' }, 'followUpPrompt': { 'prompt': { 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'maxAttempts': 123, 'responseCard': 'string' }, 'rejectionStatement': { 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'responseCard': 'string' } }, 'conclusionStatement': { 'messages': [ { 'contentType': 'PlainText'|'SSML', 'content': 'string' }, ], 'responseCard': 'string' }, 'dialogCodeHook': { 'uri': 'string', 'messageVersion': 'string' }, 'fulfillmentActivity': { 'type': 'ReturnIntent'|'CodeHook', 'codeHook': { 'uri': 'string', 'messageVersion': 'string' } }, 'parentIntentSignature': 'string', 'lastUpdatedDate': datetime(2015, 1, 1), 'createdDate': datetime(2015, 1, 1), 'version': 'string', 'checksum': 'string' } :returns: A confirmation prompt to ask the user to confirm an intent. For example, "Shall I order your pizza?" A conclusion statement to send to the user after the intent has been fulfilled. For example, "I placed your pizza order." A follow-up prompt that asks the user for additional activity. For example, asking "Do you want to order a drink with your pizza?"
385,381
def create_branch_and_checkout(self, branch_name: str): self.create_branch(branch_name) self.checkout(branch_name)
Creates a new branch if it doesn't exist Args: branch_name: branch name
385,382
def remove(self, address): with self.lock: for connection in self.connections.pop(address, ()): try: connection.close() except IOError: pass
Remove an address from the connection pool, if present, closing all connections to that address.
385,383
def run(cmd, capture=False, shell=True, env=None, exit_on_error=None, never_pretend=False): if context.get(, False) and not never_pretend: cprint(, cmd) return ExecResult( cmd, 0, , , True, False, ) if context.get(, 0) > 2: cprint(, cmd) options = { : 1, : shell } if exit_on_error is None: exit_on_error = not capture if capture: options.update({ : subprocess.PIPE, : subprocess.PIPE, }) if env is not None: options[] = dict(os.environ) options[].update(env) p = subprocess.Popen(cmd, **options) stdout, stderr = p.communicate() try: if stdout is not None: stdout = stdout.decode() if stderr is not None: stderr = stderr.decode() except AttributeError: pass if exit_on_error and p.returncode != 0: sys.exit(p.returncode) return ExecResult( cmd, p.returncode, stdout, stderr, p.returncode == 0, p.returncode != 0 )
Run a shell command. Args: cmd (str): The shell command to execute. shell (bool): Same as in `subprocess.Popen`. capture (bool): If set to True, it will capture the standard input/error instead of just piping it to the caller stdout/stderr. env (dict[str, str]): The subprocess environment variables. exit_on_error (bool): If set to **True**, on failure it will call `sys.exit` with the return code for the executed command. never_pretend (bool): If set to **True** the command will always be executed, even if context.get('pretend') is set to True. If set to **False** or not given, if the `pretend` context value is **True**, this function will only print the command it would execute and then return a fake result. Returns: ExecResult: The execution result containing the return code and output (if capture was set to *True*).
385,384
def clean_email(self): if EMAIL_CONFIRMATION: from .models import EmailAddress condition = EmailAddress.objects.filter( email__iexact=self.cleaned_data["email"], verified=True ).count() == 0 else: condition = User.objects.get( email__iexact=self.cleaned_data["email"], is_active=True ).count() == 0 if condition is True: raise forms.ValidationError( _("Email address not verified for any user account") ) return self.cleaned_data["email"]
ensure email is in the database
385,385
def GetProp(self, prop): if prop == : return self.id elif prop == : return self.status elif prop == : return self.bm elif prop == : return self.graph else: return self.properties[prop]
get attribute
385,386
def selection(self): sel = QtGui.QItemSelection() for index in self.selectedIndexes(): sel.select(index, index) return sel
Returns items in selection as a QItemSelection object
385,387
def search(request, abbr): if not request.GET: return render(request, templatename(), {: abbr}) search_text = unicode(request.GET[]).encode() if re.search(r, search_text): url = % abbr url += urllib.urlencode([(, search_text)]) return redirect(url) else: found_by_id = False kwargs = {} if abbr != : kwargs[] = abbr bill_results = Bill.search(search_text, sort=, **kwargs) show_chamber_column=True, nav_active=None))
Context: - search_text - abbr - metadata - found_by_id - bill_results - more_bills_available - legislators_list - nav_active Tempaltes: - billy/web/public/search_results_no_query.html - billy/web/public/search_results_bills_legislators.html - billy/web/public/bills_list_row_with_abbr_and_session.html
385,388
def predict(self, data, initial_args=None): request_args = self._create_request_args(data, initial_args) response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args) return self._handle_response(response)
Return the inference from the specified endpoint. Args: data (object): Input data for which you want the model to provide inference. If a serializer was specified when creating the RealTimePredictor, the result of the serializer is sent as input data. Otherwise the data must be sequence of bytes, and the predict method then sends the bytes in the request body as is. initial_args (dict[str,str]): Optional. Default arguments for boto3 ``invoke_endpoint`` call. Default is None (no default arguments). Returns: object: Inference for the given input. If a deserializer was specified when creating the RealTimePredictor, the result of the deserializer is returned. Otherwise the response returns the sequence of bytes as is.
385,389
def remove_parenthesis_around_tz(cls, timestr): parenthesis = cls.TIMEZONE_PARENTHESIS.match(timestr) if parenthesis is not None: return parenthesis.group(1)
get rid of parenthesis around timezone: (GMT) => GMT :return: the new string if parenthesis were found, `None` otherwise
385,390
def create(epsilon: typing.Union[Schedule, float]): return GenericFactory(EpsGreedy, arguments={: epsilon})
Vel factory function
385,391
def _divide_and_round(a, b): q, r = divmod(a, b) r *= 2 greater_than_half = r > b if b > 0 else r < b if greater_than_half or r == b and q % 2 == 1: q += 1 return q
divide a by b and round result to the nearest integer When the ratio is exactly half-way between two integers, the even integer is returned.
385,392
def __get_resource_entry_data(self, bundleId, languageId, resourceKey, fallback=False): url = self.__get_base_bundle_url() + + bundleId + \ + languageId + + resourceKey params = {: } if fallback else None response = self.__perform_rest_call(requestURL=url, params=params) if not response: return None resourceEntryData = response.get(self.__RESPONSE_RESOURCE_ENTRY_KEY) return resourceEntryData
``GET /{serviceInstanceId}/v2/bundles/{bundleId}/{languageId} /{resourceKey}`` Gets the resource entry information.
385,393
def check_ellipsis(text): err = "typography.symbols.ellipsis" msg = u" is an approximation, use the ellipsis symbol ." regex = "\.\.\." return existence_check(text, [regex], err, msg, max_errors=3, require_padding=False, offset=0)
Use an ellipsis instead of three dots.
385,394
def __get_merged_api_info(self, services): base_paths = sorted(set(s.api_info.base_path for s in services)) if len(base_paths) != 1: raise api_exceptions.ApiConfigurationError( .format(base_paths)) names_versions = sorted(set( (s.api_info.name, s.api_info.api_version) for s in services)) if len(names_versions) != 1: raise api_exceptions.ApiConfigurationError( .format(names_versions)) return services[0].api_info
Builds a description of an API. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: The _ApiInfo object to use for the API that the given services implement.
385,395
def text_search(self, anchor, byte=False): if isinstance(anchor, six.text_type): if byte: raise GrabMisuseError( ) else: return anchor in self.unicode_body() if not isinstance(anchor, six.text_type): if byte: return anchor in self.body else: raise GrabMisuseError( )
Search the substring in response body. :param anchor: string to search :param byte: if False then `anchor` should be the unicode string, and search will be performed in `response.unicode_body()` else `anchor` should be the byte-string and search will be performed in `response.body` If substring is found return True else False.
385,396
def do_loop_turn(self): self.check_and_del_zombie_modules() if self.watch_for_new_conf(timeout=0.05): logger.info("I got a new configuration...") self.setup_new_conf() _t0 = time.time() self.get_objects_from_from_queues() statsmgr.timer(, time.time() - _t0) _t0 = time.time() self.get_external_commands_from_arbiters() statsmgr.timer(, time.time() - _t0) statsmgr.gauge(, len(self.unprocessed_external_commands)) _t0 = time.time() self.push_external_commands_to_schedulers() statsmgr.timer(, time.time() - _t0)
Receiver daemon main loop :return: None
385,397
def find(self, obj, forced_type=None, cls=anyconfig.models.processor.Processor): return find(obj, self.list(), forced_type=forced_type, cls=cls)
:param obj: a file path, file, file-like object, pathlib.Path object or an 'anyconfig.globals.IOInfo' (namedtuple) object :param forced_type: Forced processor type to find :param cls: A class object to compare with 'ptype' :return: an instance of processor class to process 'obj' :raises: ValueError, UnknownProcessorTypeError, UnknownFileTypeError
385,398
def _prepare_connection(**nxos_api_kwargs): nxos_api_kwargs = clean_kwargs(**nxos_api_kwargs) init_kwargs = {} for karg, warg in six.iteritems(nxos_api_kwargs): if karg in RPC_INIT_KWARGS: init_kwargs[karg] = warg if not in init_kwargs: init_kwargs[] = if not in init_kwargs: init_kwargs[] = if not in init_kwargs: init_kwargs[] = 80 if init_kwargs[] == else 443 verify = init_kwargs.get(, True) if isinstance(verify, bool): init_kwargs[] = verify else: init_kwargs[] = verify if not in init_kwargs: init_kwargs[] = if not in init_kwargs: init_kwargs[] = 60 return init_kwargs
Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init.
385,399
def total_statements(self, filename=None): if filename is not None: statements = self._get_lines_by_filename(filename) return len(statements) total = 0 for filename in self.files(): statements = self._get_lines_by_filename(filename) total += len(statements) return total
Return the total number of statements for the file `filename`. If `filename` is not given, return the total number of statements for all files.