Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
500
def get_python_shell(): env = os.environ shell = "shell" program = os.path.basename(env["_"]) if "jupyter-notebook" in program: shell = "jupyter-notebook" elif "JPY_PARENT_PID" in env or "ipython" in program: shell = "ipython" if "JPY_PARENT_PID" in env: sh...
Determine python shell get_python_shell() returns 'shell' (started python on command line using "python") 'ipython' (started ipython on command line using "ipython") 'ipython-notebook' (e.g., running in Spyder or started with "ipython qtconsole") 'jupyter-notebook' (running in a Jupyter notebook) ...
501
def snakescan(xi, yi, xf, yf): dx = 1 if xf >= xi else -1 dy = 1 if yf >= yi else -1 x, xa, xb = xi, xi, xf for y in range(yi, yf + dy, dy): for x in range(xa, xb + dx, dx): yield x, y if x == xa or x == xb: dx *= -1 xa,...
Scan pixels in a snake pattern along the x-coordinate then y-coordinate :param xi: Initial x-coordinate :type xi: int :param yi: Initial y-coordinate :type yi: int :param xf: Final x-coordinate :type xf: int :param yf: Final y-coordinate :type yf: int :returns: Coordinate generator ...
502
def _rectify_countdown_or_bool(count_or_bool): if count_or_bool is True or count_or_bool is False: count_or_bool_ = count_or_bool elif isinstance(count_or_bool, int): if count_or_bool == 0: return 0 elif count_or_bool > 0: count_or_bool_ = count_or_bool - 1 ...
used by recursive functions to specify which level to turn a bool on in counting down yields True, True, ..., False counting up yields False, False, False, ... True Args: count_or_bool (bool or int): if positive and an integer, it will count down, otherwise it will remain the same. ...
503
def _verify(self, valid_subscriptions, fix): if self.subscription not in valid_subscriptions: if fix: logger.debug("RosterItem.from_xml: got unknown :" " {0!r}, changing to None".format(self.subscription)) self.subscription = None ...
Check if `self` is valid roster item. Valid item must have proper `subscription` and valid value for 'ask'. :Parameters: - `valid_subscriptions`: sequence of valid subscription values - `fix`: if `True` than replace invalid 'subscription' and 'ask' values with the...
504
def open(self): if self._is_open: raise HIDException("Failed to open device: HIDDevice already open") path = self.path.encode() dev = hidapi.hid_open_path(path) if dev: self._is_open = True self._device = dev else: raise ...
Open the HID device for reading and writing.
505
def _build_str_from_chinese(chinese_items): year, month, day = chinese_items year = reduce(lambda a, b: a*10+b, map(CHINESE_NUMS.find, year)) return % (year, _parse_chinese_field(month), _parse_chinese_field(day))
根据解析出的中文时间字符串的关键字返回对应的标准格式字符串
506
def delete_workspace_config(namespace, workspace, cnamespace, config): uri = "workspaces/{0}/{1}/method_configs/{2}/{3}".format(namespace, workspace, cnamespace, config) return __delete(uri)
Delete method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name mnamespace (str): Method namespace method (str): Method name Swagger: https://api.firecloud.org/#!/Method_Configurations/deleteWorkspaceMe...
507
def print_row(self, **kwargs): meta_string = for key in self.column_names: float_specifier = if isinstance(kwargs[key], float): float_specifier = meta_string += " {%s:<{width}%s}|" % (key, float_specifier) kwargs[] = self.column_wid...
keys of kwargs must be the names passed to __init__(...) as `column_names`
508
def spcol(x,knots,spline_order): colmat = np.nan*np.ones((len(x),len(knots) - spline_order-1)) for i in range(0,len(knots) - spline_order -1): colmat[:,i] = spline(x,knots,spline_order,i) return colmat
Computes the spline colocation matrix for knots in x. The spline collocation matrix contains all m-p-1 bases defined by knots. Specifically it contains the ith basis in the ith column. Input: x: vector to evaluate the bases on knots: vector of knots spline_order: orde...
509
def _rebuild_all_command_chains(self): self._commands_by_name = {} for command in self._commands: self._build_command_chain(command)
Rebuilds execution chain for all registered commands. This method is typically called when intercepters are changed. Because of that it is more efficient to register intercepters before registering commands (typically it will be done in abstract classes). However, that performance penalt...
510
def to_html(ds: Any) -> str: rm = min(10, ds.shape[0]) cm = min(10, ds.shape[1]) html = "<p>" if ds.attrs.__contains__("title"): html += "<strong>" + ds.attrs["title"] + "</strong> " html += f"{ds.shape[0]} rows, {ds.shape[1]} columns, {len(ds.layers)} layer{ if len(ds.layers) > 1 else }<br/>(showing up to 10x...
Return an HTML representation of the loom file or view, showing the upper-left 10x10 corner.
511
def _clopper_pearson_confidence_interval(samples, error_rate): if optimize is None or stats is None: raise ValueError( "Scipy is required for computing Clopper-Pearson confidence intervals") if len(samples.shape) != 1: raise ValueError("Batch semantics not implemented")...
Computes a confidence interval for the mean of the given 1-D distribution. Assumes (and checks) that the given distribution is Bernoulli, i.e., takes only two values. This licenses using the CDF of the binomial distribution for the confidence, which is tighter (for extreme probabilities) than the DKWM inequal...
512
def get_version_path(self, version=None): archa1vera20.0.00.0.1a1latestNoneTypemanager version = _process_version(self, version) if self.versioned: return fs.path.join(self.archive_path, str(version)) else: return self.archive_path
Returns a storage path for the archive and version If the archive is versioned, the version number is used as the file path and the archive path is the directory. If not, the archive path is used as the file path. Parameters ---------- version : str or object ...
513
def results(self, use_cache=True, dialect=None, billing_tier=None): if not use_cache or (self._results is None): self.execute(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier) return self._results.results
Retrieves table of results for the query. May block if the query must be executed first. Args: use_cache: whether to use cached results or not. Ignored if append is specified. dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard'...
514
def identify(self, req, resp, resource, uri_kwargs): header = req.get_header("Authorization", False) auth = header.split(" ") if header else None if auth is None or auth[0].lower() != : return None if len(auth) != 2: raise HTTPBadRequest( ...
Identify user using Authenticate header with Basic auth.
515
def update(self, fields=None, **kwargs): kwargs = kwargs.copy() kwargs.update(self._server_config.get_client_kwargs()) headers = kwargs.pop(, {}) headers[] = kwargs[] = headers return client.put( self.path(), fields, ...
Update the current entity. Make an HTTP PUT call to ``self.path('base')``. Return the response. :param fields: An iterable of field names. Only the fields named in this iterable will be updated. No fields are updated if an empty iterable is passed in. All fields are updated if ...
516
def lowdata_fmt(): if cherrypy.request.method.upper() != : return data = cherrypy.request.unserialized_data if data and isinstance(data, collections.Mapping): if in data and not isinstance(data[], list): data[] = [data[]] cherryp...
Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run.
517
def read_secret_version(self, path, version=None, mount_point=DEFAULT_MOUNT_POINT): params = {} if version is not None: params[] = version api_path = .format(mount_point=mount_point, path=path) response = self._adapter.get( url=api_path, param...
Retrieve the secret at the specified location. Supported methods: GET: /{mount_point}/data/{path}. Produces: 200 application/json :param path: Specifies the path of the secret to read. This is specified as part of the URL. :type path: str | unicode :param version: Specifie...
518
def get_segment_definer_comments(xml_file, include_version=True): from glue.ligolw.ligolw import LIGOLWContentHandler as h lsctables.use_in(h) xmldoc, _ = ligolw_utils.load_fileobj(xml_file, gz=xml_file.name.endswith(".gz"), ...
Returns a dict with the comment column as the value for each segment
519
def create_token(self, user): h = crypto.pbkdf2( self.get_revocation_key(user), self.salt, self.iterations, digest=self.digest, ) return self.sign(self.packer.pack_pk(user.pk) + h)
Create a signed token from a user.
520
def __within2(value, within=None, errmsg=None, dtype=None): valid, _value = False, value if dtype: try: _value = dtype(value) valid = _value in within except ValueError: pass else: valid = _value in within if errmsg is None: if d...
validate that a value is in ``within`` and optionally a ``dtype``
521
def all_selected_options(self): ret = [] for opt in self.options: if opt.is_selected(): ret.append(opt) return ret
Returns a list of all selected options belonging to this select tag
522
def pull_session(session_id=None, url=, io_loop=None, arguments=None): t plan to modify ``session.document`` you probably dons document into your process first. Itt need to. In a production scenario, the ``session_id`` should be unique for each browser tab, which keeps users from stomping on ea...
Create a session by loading the current server-side document. ``session.document`` will be a fresh document loaded from the server. While the connection to the server is open, changes made on the server side will be applied to this document, and changes made on the client side will be synced to the...
523
def configure(self, options, conf): self.conf = conf if hasattr(options, self.enable_opt): self.enabled = getattr(options, self.enable_opt)
Configure the plugin and system, based on selected options. The base plugin class sets the plugin to enabled if the enable option for the plugin (self.enable_opt) is true.
524
def make_tz_aware(dt, tz=, is_dst=None): dt = make_datetime(dt) if not isinstance(dt, (list, datetime.datetime, datetime.date, datetime.time, pd.Timestamp)): return dt try: tz = dt.tzinfo or tz except (ValueError, AttributeError, TypeError): pass try: t...
Add timezone information to a datetime object, only if it is naive. >>> make_tz_aware(datetime.datetime(2001, 9, 8, 7, 6)) datetime.datetime(2001, 9, 8, 7, 6, tzinfo=<UTC>) >>> make_tz_aware(['2010-01-01'], 'PST') [datetime.datetime(2010, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 S...
525
def _domain_event_pmsuspend_cb(conn, domain, reason, opaque): _salt_send_domain_event(opaque, conn, domain, opaque[], { : })
Domain suspend events handler
526
def _get_subject_public_key(cert): public_key = cert.get_pubkey() cryptographic_key = public_key.to_cryptography_key() subject_public_key = cryptographic_key.public_bytes(Encoding.DER, PublicFormat.PKCS1) return subject...
Returns the SubjectPublicKey asn.1 field of the SubjectPublicKeyInfo field of the server's certificate. This is used in the server verification steps to thwart MitM attacks. :param cert: X509 certificate from pyOpenSSL .get_peer_certificate() :return: byte string of the asn.1 DER encode...
527
def nunique(expr): output_type = types.int64 if isinstance(expr, SequenceExpr): return NUnique(_value_type=output_type, _inputs=[expr]) elif isinstance(expr, SequenceGroupBy): return GroupedNUnique(_data_type=output_type, _inputs=[expr.to_column()], _grouped=expr.input) elif isinst...
The distinct count. :param expr: :return:
528
def get_child(self, streamId, childId, options={}): return self.get( + streamId + + childId, options)
Get the child of a stream.
529
def get_top_n_meanings(strings, n): scored_strings = [(s, score_meaning(s)) for s in strings] scored_strings.sort(key=lambda tup: -tup[1]) return scored_strings[:n]
Returns (text, score) for top n strings
530
def get_resource_metadata(self, resource=None): result = self._make_metadata_request(meta_id=0, metadata_type=) if resource: result = next((item for item in result if item[] == resource), None) return result
Get resource metadata :param resource: The name of the resource to get metadata for :return: list
531
def screener(molecules, ensemble, sort_order): modified_molecules = [] for index in range(len(molecules)): modified_molecules.append(molecules[index]) scores = [] for query in ensemble: scores.append( (molecules[index].GetProp(query), query)) if sort...
Uses the virtual screening scores for the receptors, or queries, specified in ensemble to sort the molecules in molecules in the direction specified by sort_order. :param molecules: a list of molecule objects (/classification/molecules.Molecules()) :param ensemble: a tuple with receptors, or a query, that s...
532
def get_ssh_key(): path = os.environ.get("TUNE_CLUSTER_SSH_KEY", os.path.expanduser("~/ray_bootstrap_key.pem")) if os.path.exists(path): return path return None
Returns ssh key to connecting to cluster workers. If the env var TUNE_CLUSTER_SSH_KEY is provided, then this key will be used for syncing across different nodes.
533
def dump_privatekey(type, pkey, cipher=None, passphrase=None): bio = _new_mem_buf() if not isinstance(pkey, PKey): raise TypeError("pkey must be a PKey") if cipher is not None: if passphrase is None: raise TypeError( "if a value is given for cipher " ...
Dump the private key *pkey* into a buffer string encoded with the type *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it using *cipher* and *passphrase*. :param type: The file type (one of :const:`FILETYPE_PEM`, :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`) :param PKey...
534
def token_middleware(ctx, get_response): async def middleware(request): params = request.setdefault(, {}) if params.get("token") is None: params[] = ctx.token return await get_response(request) return middleware
Reinject token and consistency into requests.
535
def get_items(self) -> Iterator[StoryItem]: yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node[]))
Retrieve all items from a story.
536
def crawl(self, urls, name=, api=, **kwargs): if isinstance(urls, list): urls = .join(urls) url = self.endpoint() process_url = self.endpoint(api) params = { : self._token, : urls, : name, : process_url, ...
Crawlbot API. Returns a diffbot.Job object to check and retrieve crawl status.
537
def check_uniqueness(self, *args): self.get_unique_index().check_uniqueness(*self.prepare_args(args, transform=False))
For a unique index, check if the given args are not used twice For the parameters, seen BaseIndex.check_uniqueness
538
def refresh(self): pipe = self.redis.pipeline() pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "metadata") pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices") pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice") results = pipe.execute(...
Re-pulls the data from redis
539
def perform_word_selection(self, event=None): self.editor.setTextCursor( TextHelper(self.editor).word_under_cursor(True)) if event: event.accept()
Performs word selection :param event: QMouseEvent
540
def _strip_metadata(self, my_dict): new_dict = copy.deepcopy(my_dict) if const.START in new_dict: del new_dict[const.START] if const.END in new_dict: del new_dict[const.END] if const.WHITELIST in new_dict: del new_dict[const.WHITELIST] ...
Create a copy of dict and remove not needed data
541
def retrieve(self, request, project, pk=None): try: serializer = JobNoteSerializer(JobNote.objects.get(id=pk)) return Response(serializer.data) except JobNote.DoesNotExist: return Response("No note with id: {0}".format(pk), status=HTTP_404_NOT_FOUND)
GET method implementation for a note detail
542
def subsc_search(self, article_code, **kwargs): request = TOPRequest() request[] = article_code for k, v in kwargs.iteritems(): if k not in (, , , , , , , ,) and v==None: continue request[k] = v self.create(self.execute(request), fields=[,], models={:Arti...
taobao.vas.subsc.search 订购记录导出 用于ISV查询自己名下的应用及收费项目的订购记录
543
def raw_pitch_accuracy(ref_voicing, ref_cent, est_voicing, est_cent, cent_tolerance=50): validate_voicing(ref_voicing, est_voicing) validate(ref_voicing, ref_cent, est_voicing, est_cent) ref_voicing = ref_voicing.astype(bool) est_voicing = est_voicing.astype(bool) i...
Compute the raw pitch accuracy given two pitch (frequency) sequences in cents and matching voicing indicator sequences. The first pitch and voicing arrays are treated as the reference (truth), and the second two as the estimate (prediction). All 4 sequences must be of the same length. Examples ---...
544
def assign(self, **kwargs): r data = self.copy() if PY36: for k, v in kwargs.items(): data[k] = com.apply_if_callable(v, data) else: results = OrderedDict() for k, v in kwargs.items(): results[k] =...
r""" Assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. Parameters ---------- **kwargs : dict of {str: callable or Series} The column names are...
545
def endpoint(self, endpoint): def decorator(f): def register_endpoint(state): state.app.view_functions[endpoint] = f self.record_once(register_endpoint) return f return decorator
Like :meth:`Flask.endpoint` but for a blueprint. This does not prefix the endpoint with the blueprint name, this has to be done explicitly by the user of this method. If the endpoint is prefixed with a `.` it will be registered to the current blueprint, otherwise it's an application in...
546
def parse_ipv6_literal_host(entity, default_port): if entity.find() == -1: raise ValueError("an IPv6 address literal must be " "enclosed in and according " "to RFC 2732.") i = entity.find() if i == -1: return entity[1:-1], default_port...
Validates an IPv6 literal host:port string. Returns a 2-tuple of IPv6 literal followed by port where port is default_port if it wasn't specified in entity. :Parameters: - `entity`: A string that represents an IPv6 literal enclosed in braces (e.g. '[::1]' or '[::1]:27017'). ...
547
def delete(self, obj): obj = self.api.get_object(getattr(obj, , obj)) obj.delete() self.remove(obj.id)
Delete an object in CDSTAR and remove it from the catalog. :param obj: An object ID or an Object instance.
548
def _get_request_type(self): value = self.document.tag.lower() if value in allowed_request_types[self.params[]]: self.params["request"] = value else: raise OWSInvalidParameterValue("Request type %s is not supported" % value, value="request") return self.p...
Find requested request type in POST request.
549
def repr_args(args): res = [] for x in args: if isinstance(x, tuple) and len(x) == 2: key, value = x res += ["%s=%s" % (key, repr_arg(value))] else: res += [repr_arg(x)] return .join(res)
formats a list of function arguments prettily but as working code (kwargs are tuples (argname, argvalue)
550
def all(cls, klass, db_session=None): db_session = get_db_session(db_session) return db_session.query(klass)
returns all objects of specific type - will work correctly with sqlalchemy inheritance models, you should normally use models base_query() instead of this function its for bw. compat purposes :param klass: :param db_session: :return:
551
def check_enable_mode(self, check_string=""): self.write_channel(self.RETURN) output = self.read_until_prompt() return check_string in output
Check if in enable mode. Return boolean. :param check_string: Identification of privilege mode from device :type check_string: str
552
def jobs(request): Actionget_configMachineIdConfigSecretUUIDSubmissionFileIdMessageErrorCodeActionSecretUUIDSecretUUIDSubmissionFileIdTimeoutActionPostRunValidation try: if request.method == : secret = request.GET[] uuid = request.GET[] elif request.method == : ...
This is the view used by the executor.py scripts for getting / putting the test results. Fetching some file for testing is changing the database, so using GET here is not really RESTish. Whatever. A visible shared secret in the request is no problem, since the executors come from trusted network...
553
def get_correlation(self, t1, t2): t_min = min(t1, t2) t_max = max(t1, t2) c1 = 1.0 c1 -= np.cos(np.pi / 2.0 - np.log(t_max / max(t_min, 0.109)) * 0.366) if t_max < 0.2: c2 = 0.105 * (1.0 - 1.0 / (1.0 + np.exp(100.0 * t_max - 5.0))) c2 = 1.0 - ...
Computes the correlation coefficient for the specified periods. :param float t1: First period of interest. :param float t2: Second period of interest. :return float rho: The predicted correlation coefficient.
554
def update_devices(self, devices): for qspacket in devices: try: qsid = qspacket[QS_ID] except KeyError: _LOGGER.debug("Device without ID: %s", qspacket) continue if qsid not in self: self[qsid] = QSDev...
Update values from response of URL_DEVICES, callback if changed.
555
def ud_grade_ipix(ipix, nside_in, nside_out, nest=False): if nside_in == nside_out: return ipix elif nside_in < nside_out: return u_grade_ipix(ipix, nside_in, nside_out, nest) elif nside_in > nside_out: return d_grade_ipix(ipix, nside_in, nside_out, nest)
Upgrade or degrade resolution of a pixel list. Parameters: ----------- ipix:array-like the input pixel(s) nside_in:int the nside of the input pixel(s) nside_out:int the desired nside of the output pixel(s) order:str pixel ordering of input and output ("RING" or "NESTED") ...
556
def reconnect(self): self._converters.clear() self._gateway = None self._xsltFactory = None try: self._gateway = JavaGateway(GatewayClient(port=self._gwPort)) self._xsltFactory = self._gateway.jvm.org.pyjxslt.XSLTTransformerFactory() ...
(Re)establish the gateway connection @return: True if connection was established
557
def requires(self, extras=()): dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra( "%s has no such ext...
List of Requirements needed for this distro if `extras` are used
558
def _do_search(conf): connargs = {} for name in [, , , , , ]: connargs[name] = _config(name, conf) if connargs[] and connargs[]: connargs[] = False try: _filter = conf[] except KeyError: raise SaltInvocationError() _dn = _config(, conf) scope = ...
Builds connection and search arguments, performs the LDAP search and formats the results as a dictionary appropriate for pillar use.
559
def yellow(cls): "Make the text foreground color yellow." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_YELLOW cls._set_text_attributes(wAttributes)
Make the text foreground color yellow.
560
def _started_channels(self): super(IPythonWidget, self)._started_channels() self._load_guiref_magic() self.kernel_manager.shell_channel.history(hist_access_type=, n=1000)
Reimplemented to make a history request and load %guiref.
561
def _add_study_provenance( self, phenotyping_center, colony, project_fullname, pipeline_name, pipeline_stable_id, procedure_stable_id, procedure_name, parameter_stable_id, parameter_name, ...
:param phenotyping_center: str, from self.files['all'] :param colony: str, from self.files['all'] :param project_fullname: str, from self.files['all'] :param pipeline_name: str, from self.files['all'] :param pipeline_stable_id: str, from self.files['all'] :param procedure_stable_...
562
def get_agents(self): collection = JSONClientValidated(, collection=, runtime=self._runtime) result = collection.find(self._view_filter()).sort(, DESCENDING) return objects.Agent...
Gets all ``Agents``. In plenary mode, the returned list contains all known agents or an error results. Otherwise, the returned list may contain only those agents that are accessible through this session. return: (osid.authentication.AgentList) - a list of ``Agents`` raise: Ope...
563
def astype(self, dtype): if dtype is None: raise ValueError() dtype = np.dtype(dtype) if dtype == self.dtype: return self if is_numeric_dtype(self.dtype): if dtype == self.__real_dtype: if self.__rea...
Return a copy of this space with new ``dtype``. Parameters ---------- dtype : Scalar data type of the returned space. Can be provided in any way the `numpy.dtype` constructor understands, e.g. as built-in type or as a string. Data types with non-trivial ...
564
def _set_src_vtep_ip(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={: u}), is_leaf=True, yang_name="src-vtep-ip", rest_name="src-vtep-ip-host", parent=self, choice=(u, u), path_helper=self._pat...
Setter method for src_vtep_ip, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/src_vtep_ip (inet:ipv4-address) If this variable is read-only (config: false) in the source YANG file, then _set_src_vtep_ip is considered as a private method. Backends looking to populate this variable sho...
565
def _authenticate(self): self.cleanup_headers() url = LOGIN_ENDPOINT data = self.query( url, method=, extra_params={ : self.__username, : self.__password }) if isinstance(data, dict) and data.get():...
Authenticate user and generate token.
566
def check_subscriber_key_length(app_configs=None, **kwargs): from . import settings as djstripe_settings messages = [] key = djstripe_settings.SUBSCRIBER_CUSTOMER_KEY key_size = len(str(key)) if key and key_size > 40: messages.append( checks.Error( "DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY must be no more tha...
Check that DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY fits in metadata. Docs: https://stripe.com/docs/api#metadata
567
def pandasdfsummarytojson(df, ndigits=3): df = df.transpose() return {k: _pandassummarytojson(v, ndigits) for k, v in df.iterrows()}
Convert the result of a Parameters ---------- df : The result of a Pandas describe operation. ndigits : int, optional - The number of significant digits to round to. Returns ------- A json object which captures the describe. Keys are field names and values are dictionaries with all of...
568
def all(cls, sort=None, limit=None): return cls.where(sort=sort, limit=limit)
Returns all objects of this type. Alias for where() (without filter arguments). See `where` for documentation on the `sort` and `limit` parameters.
569
def parse_config(data: dict) -> dict: return { : data.get(), : data[], : [{ : sample_id, : analysis_type, } for sample_id, analysis_type in data[].items()], : data[], : True if in data else False, : data[], : data[], ...
Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data
570
def get_tasks(self): tasks = self._get_tasks() tasks.extend(self._streams.get_tasks(self)) return tasks
Get the tasks attached to the instance Returns ------- list List of tasks (:class:`asyncio.Task`)
571
def diffuser_conical(Di1, Di2, l=None, angle=None, fd=None, Re=None, roughness=0.0, method=): rRennelsRennelsCraneMillerSwameeIdelchik beta = Di1/Di2 beta2 = beta*beta if angle is not None: angle_rad = radians(angle) l = (Di2 - Di1)/(2.0*tan(0.5*angle_rad)) elif ...
r'''Returns the loss coefficient for any conical pipe diffuser. This calculation has four methods available. The 'Rennels' [1]_ formulas are as follows (three different formulas are used, depending on the angle and the ratio of diameters): For 0 to 20 degrees, all aspect ratios: .. math:: ...
572
def print_err(*args, **kwargs): if kwargs.get(, None) is None: kwargs[] = sys.stderr color = dict_pop_or(kwargs, , True) if color and kwargs[].isatty(): msg = kwargs.get(, ).join( str(a) if isinstance(a, C) else str(C(a, )) for a in args ) ...
A wrapper for print() that uses stderr by default.
573
def get_as(self, cls: Type[MaybeBytesT]) -> Sequence[MaybeBytesT]: _ = cls return cast(Sequence[MaybeBytesT], self.items)
Return the list of parsed objects.
574
def optionally_with_args(phase, **kwargs): if isinstance(phase, PhaseGroup): return phase.with_args(**kwargs) if isinstance(phase, collections.Iterable): return [optionally_with_args(p, **kwargs) for p in phase] if not isinstance(phase, phase_descriptor.PhaseDescriptor): phase = phase_descriptor.P...
Apply only the args that the phase knows. If the phase has a **kwargs-style argument, it counts as knowing all args. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase group (or iterable) to apply with_args to. **kwargs: argume...
575
def fix(csvfile): header(, csvfile.name) bads = [] reader = csv.reader(csvfile) reader.next() for id, _, sources, dests in reader: advice = Advice.objects.get(id=id) sources = [s.strip() for s in sources.split() if s.strip()] dests = [d.strip() for d in dests.split() i...
Apply a fix (ie. remove plain names)
576
def outgoing_caller_ids(self): if self._outgoing_caller_ids is None: self._outgoing_caller_ids = OutgoingCallerIdList(self._version, account_sid=self._solution[], ) return self._outgoing_caller_ids
Access the outgoing_caller_ids :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList
577
def get_autoscaling_group_properties(asg_client, env, service): try: response = asg_client.describe_auto_scaling_groups(AutoScalingGroupNames=["{}-{}".format(env, service)]) if len(response["AutoScalingGroups"]) == 0: response = asg_client.describe_tags(Filters=[{ "Name": "Key", "Values":...
Gets the autoscaling group properties based on the service name that is provided. This function will attempt the find the autoscaling group base on the following logic: 1. If the service name provided matches the autoscaling group name 2. If the service name provided matches the Name tag of the autoscaling gr...
578
def mode_number(self, rows: List[Row], column: NumberColumn) -> Number: most_frequent_list = self._get_most_frequent_values(rows, column) if not most_frequent_list: return 0.0 most_frequent_value = most_frequent_list[0] if not isinstance(most_frequent_value, Number...
Takes a list of rows and a column and returns the most frequent value under that column in those rows.
579
def _conflicted_data_points(L): m = sparse.diags(np.ravel(L.max(axis=1).todense())) return np.ravel(np.max(m @ (L != 0) != L, axis=1).astype(int).todense())
Returns an indicator vector where ith element = 1 if x_i is labeled by at least two LFs that give it disagreeing labels.
580
def check_schema_coverage(doc, schema): name error_list = [] to_delete = [] for entry in doc.list_tuples(): (name, value, index, seq) = entry temp_schema = schema_match_up(doc, schema) if not name in temp_schema.list_values("name"): error_list.append( ("[error]", "doc...
FORWARD CHECK OF DOCUMENT This routine looks at each element in the doc, and makes sure there is a matching 'name' in the schema at that level.
581
def _write_passphrase(stream, passphrase, encoding): passphrase = % passphrase passphrase = passphrase.encode(encoding) stream.write(passphrase) log.debug("Wrote passphrase on stdin.")
Write the passphrase from memory to the GnuPG process' stdin. :type stream: file, :class:`~io.BytesIO`, or :class:`~io.StringIO` :param stream: The input file descriptor to write the password to. :param str passphrase: The passphrase for the secret key material. :param str encoding: The data encoding e...
582
def autoprefixer(input, **kw): cmd = % (current_app.config.get(), current_app.config.get(), input) subprocess.call(cmd, shell=True)
Run autoprefixer
583
def _parse_nicknameinuse(client, command, actor, args): nick, _, _ = args.rpartition(" ") client.dispatch_event("NICKNAMEINUSE", nick)
Parse a NICKNAMEINUSE message and dispatch an event. The parameter passed along with the event is the nickname which is already in use.
584
def assign_objective_requisite(self, objective_id, requisite_objective_id): requisite_type = Type(**Relationship().get_type_data()) ras = self._get_provider_manager( ).get_relationship_admin_session_for_family( self.get_objective_bank_id(), proxy=self._proxy) rf...
Creates a requirement dependency between two ``Objectives``. arg: objective_id (osid.id.Id): the ``Id`` of the dependent ``Objective`` arg: requisite_objective_id (osid.id.Id): the ``Id`` of the required ``Objective`` raise: AlreadyExists - ``objective_id`...
585
def write_byte(self, address, value): LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address)) return self.driver.write_byte(address, value)
Writes the byte to unaddressed register in a device.
586
def restore_state(self, state): super(ReferenceController, self).restore_state(state) state_name = state.get() state_version = state.get() if state_name != self.STATE_NAME or state_version != self.STATE_VERSION: raise ArgumentError("Invalid emulated device state n...
Restore the current state of this emulated object. Args: state (dict): A previously dumped state produced by dump_state.
587
def parse(self, data): if self._initialized: raise pycdlibexception.PyCdlibInternalError() (self.prior_num_direct_entries, self.strategy_type, self.strategy_param, self.max_num_entries, reserved, self.file_type, self.parent_icb_log_block_num, self.parent_...
Parse the passed in data into a UDF ICB Tag. Parameters: data - The data to parse. Returns: Nothing.
588
def handle_cf_error(error_pointer): if is_null(error_pointer): return error = unwrap(error_pointer) if is_null(error): return cf_string_domain = CoreFoundation.CFErrorGetDomain(error) domain = CFHelpers.cf_string_to_unicode(cf_string_domain) CoreFoundation.CFRelease(cf_st...
Checks a CFErrorRef and throws an exception if there is an error to report :param error_pointer: A CFErrorRef :raises: OSError - when the CFErrorRef contains an error
589
def list_models(self, limit=-1, offset=-1): return self.registry.list_models(limit=limit, offset=offset)
Get a list of models in the registry. Parameters ---------- limit : int Limit number of items in the result set offset : int Set offset in list (order as defined by object store) Returns ------- list(ModelHandle)
590
def disconnect(self, signal=None, slot=None, transform=None, condition=None): if slot: self.connections[signal][condition].pop(slot, None) elif condition is not None: self.connections[signal].pop(condition, None) elif signal: self.connections.pop(sign...
Removes connection(s) between this objects signal and connected slot(s) signal: the signal this class will emit, to cause the slot method to be called receiver: the object containing the slot method to be called slot: the slot method or function to call transform: an optiona...
591
def attach_bytes(key, the_bytes): tf_v1.add_to_collection( _ATTACHMENT_COLLECTION_INTERNAL, module_attachment_pb2.ModuleAttachment(key=key, value=the_bytes))
Adds a ModuleAttachment to the current graph. Args: key: A string with the unique key of the attachment. the_bytes: A bytes object with the serialized attachment.
592
def setCustomColorRamp(self, colors=[], interpolatedPoints=10): self._colorRamp = ColorRampGenerator.generateCustomColorRamp(colors, interpolatedPoints)
Accepts a list of RGB tuples and interpolates between them to create a custom color ramp. Returns the color ramp as a list of RGB tuples.
593
def from_utf8(buf, errors=): if isinstance(buf, unicode): return buf else: return unicode(buf, , errors)
Decodes a UTF-8 compatible, ASCII string into a unicode object. `buf` string or unicode string to convert. Returns unicode` string. * Raises a ``UnicodeDecodeError`` exception if encoding failed and `errors` isn't set to 'replace'.
594
def pause(self, instance_id, keep_provisioned=True): try: if self._paused: log.debug("node %s is already paused", instance_id) return self._paused = True post_shutdown_action = if keep_provisioned else \ r...
shuts down the instance without destroying it. The AbstractCloudProvider class uses 'stop' to refer to destroying a VM, so use 'pause' to mean powering it down while leaving it allocated. :param str instance_id: instance identifier :return: None
595
def xmlrpc_provision(self, app_id, path_to_cert_or_cert, environment, timeout=15): if environment not in (, ): raise xmlrpc.Fault(401, % ( environment,)) if not app_id in self.app_ids: self.app_ids[app_id] = APNSService(p...
Starts an APNSService for the this app_id and keeps it running Arguments: app_id the app_id to provision for APNS path_to_cert_or_cert absolute path to the APNS SSL cert or a string containing the .pem file environment ...
596
def read_json(self, params=None): response = self.read_raw(params=params) response.raise_for_status() return response.json()
Get information about the current entity. Call :meth:`read_raw`. Check the response status code, decode JSON and return the decoded JSON as a dict. :return: A dict. The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` if the response has an HTTP ...
597
def asyncPipeRegex(context=None, _INPUT=None, conf=None, **kwargs): splits = yield asyncGetSplits(_INPUT, conf[], **cdicts(opts, kwargs)) asyncConvert = partial(maybeDeferred, convert_func) asyncFuncs = get_async_dispatch_funcs(, asyncConvert) parsed = yield asyncDispatch(splits, *asyncFuncs) _...
An operator that asynchronously replaces text in items using regexes. Each has the general format: "In [field] replace [match] with [replace]". Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT : asyncPipe like object (twisted Deferred iterable of items) conf : { ...
598
def handle_sketch_version(msg): if not msg.gateway.is_sensor(msg.node_id): return None msg.gateway.sensors[msg.node_id].sketch_version = msg.payload msg.gateway.alert(msg) return None
Process an internal sketch version message.
599
def read_config(config_fname=None): if not config_fname: config_fname = DEFAULT_CONFIG_FNAME try: with open(config_fname, ) as config_file: config = yaml.load(config_file) except IOError as exc: if exc.errno == errno.ENOENT: print( .fo...
Parse input configuration file and return a config dict.