Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
370,500
def create_context_store(name=, ttl=settings.CONTEXT_DEFAULT_TTL, store=settings.CONTEXT_STORE) -> : store_class = import_class(store[]) return store_class(name=name, ttl=ttl, **store[])
Create a context store. By default using the default configured context store, but you can use a custom class if you want to using the `store` setting. The time to live of each store (aka there is one per conversation) is defined by the `ttl` value, which is also inferred by default from the config...
370,501
def query_artifacts(job_ids, log): jobs_artifacts = list() for job in job_ids: url = .format(job) log.debug(, job) json_data = query_api(url) for artifact in json_data: jobs_artifacts.append((job, artifact[], artifact[])) return jobs_artifacts
Query API again for artifacts. :param iter job_ids: List of AppVeyor jobIDs. :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: List of tuples: (job ID, artifact file name, artifact file size). :rtype: list
370,502
def file_list(*packages, **kwargs): s rpm database (not generally recommended). root use root as top level directory (default: "/") CLI Examples: .. code-block:: bash salt lowpkg.file_list httpd salt lowpkg.file_list httpd postfix salt lowpkg.file_list rpmr...
List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's rpm database (not generally recommended). root use root as top level directory (default: "/") CLI Examples: .. code-block:: bash salt '*' lowpkg.file_list httpd...
370,503
def make_path_qs(self, items): s url pattern will be inserted into the path. Any remaining items will be appended as query string parameters. All items will be urlencoded. Any items which are not instances of basestring, or int/long will be pickled before being urlencoded. ...
Returns a relative path complete with query string for the given dictionary of items. Any items with keys matching this rule's url pattern will be inserted into the path. Any remaining items will be appended as query string parameters. All items will be urlencoded. Any items wh...
370,504
def set_limits(self, min_=None, max_=None): self._min, self._max = min_, max_
Sets limits for this config value If the resulting integer is outside those limits, an exception will be raised :param min_: minima :param max_: maxima
370,505
def get_relation_count_query_for_self_join(self, query, parent): query.select(QueryExpression()) table_prefix = self._query.get_query().get_connection().get_table_prefix() hash_ = self.get_relation_count_hash() query.from_( % (self._table, table_prefix, hash_)) key = ...
Add the constraints for a relationship count query on the same table. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder
370,506
def is_filter_with_outer_scope_vertex_field_operator(directive): if directive.name.value != : return False op_name, _ = _get_filter_op_name_and_values(directive) return op_name in OUTER_SCOPE_VERTEX_FIELD_OPERATORS
Return True if we have a filter directive whose operator applies to the outer scope.
370,507
def token_from_fragment(self, authorization_response): self._client.parse_request_uri_response( authorization_response, state=self._state ) self.token = self._client.token return self.token
Parse token from the URI fragment, used by MobileApplicationClients. :param authorization_response: The full URL of the redirect back to you :return: A token dict
370,508
def get_location(self, location_id, depth=0): response = self._perform_request( % (location_id, depth)) return response
Retrieves a single location by ID. :param location_id: The unique ID of the location. :type location_id: ``str``
370,509
def delete(self): if self.filename == : return True try: os.remove(self.filename) return True except OSError: return False
Deletes the current session file
370,510
def convertTupleArrayToPoints(self, arrayOfPointTuples): points = "" for tuple in arrayOfPointTuples: points += str(tuple[0]) + "," + str(tuple[1]) + " " return points
Method used to convert an array of tuples (x,y) into a string suitable for createPolygon or createPolyline @type arrayOfPointTuples: An array containing tuples eg.[(x1,y1),(x2,y2] @param arrayOfPointTuples: All points needed to create the shape @return a string in the form "x1,y1 x2,y2...
370,511
def build_dependencies(self): cmd_list = [, , self.pyang_plugins] cmd_list += [, self.dir_yang] cmd_list += [, ] cmd_list += [self.dir_yang + ] logger.info(.format(.join(cmd_list))) p = Popen(.join(cmd_list), shell=True, stdout=PIPE, stderr=PIPE) stdout,...
build_dependencies High-level api: Briefly compile all yang files and find out dependency infomation of all modules. Returns ------- None Nothing returns.
370,512
def dump(self): text = for result in self.objects: if result.is_failure or result.is_error: text += text += .format(.ljust(79, )) status = if result.is_failure else text += .format(status, result.process) ...
Returns the results in string format.
370,513
def items(self): r = [] for key in self._safe_keys(): try: r.append((key, self[key])) except KeyError: pass return r
Return a copy of the dictionary's list of (key, value) pairs.
370,514
def get_tiltplane(self, sequence): sequence = sorted(sequence, key=lambda x: self.virtual_atoms[ x ].z) in_plane = [] for i in range(0, len(sequence)-4): if abs(self.virtual_atoms[ sequence[i] ].z - self.virtual_atoms[ sequence[i+1] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE ...
Extract the main tilting plane basing on Z coordinate
370,515
def fit(self, X, y=None, input_type=): X = self._validate_input(X, input_type) self.fit_geometry(X, input_type) random_state = check_random_state(self.random_state) self.embedding_, self.eigen_vectors_, self.P_ = spectral_clustering(self.geom_, K = self.K, ...
Fit the model from data in X. Parameters ---------- input_type : string, one of: 'similarity', 'distance' or 'data'. The values of input data X. (default = 'data') X : array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of sam...
370,516
def ref(self, orm_classpath, cls_pk=None): orm_module, orm_class = get_objects(orm_classpath) q = orm_class.query if cls_pk: found = False for fn, f in orm_class.schema.fields.items(): cls_ref_s = f...
takes a classpath to allow query-ing from another Orm class the reason why it takes string paths is to avoid infinite recursion import problems because an orm class from module A might have a ref from module B and sometimes it is handy to have module B be able to get the objects from m...
370,517
def blend_rect(self, x0, y0, x1, y1, dx, dy, destination, alpha=0xff): x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) for x in range(x0, x1 + 1): for y in range(y0, y1 + 1): o = self._offset(x, y) rgba = self.canvas[o:o + 4] rgba[3]...
Blend a rectangle onto the image
370,518
def upsert_object_property(self, identifier, properties, ignore_constraints=False): obj = self.get_object(identifier) if not obj is None: for key in properties: value = properties[key] if no...
Manipulate an object's property set. Inserts or updates properties in given dictionary. If a property key does not exist in the object's property set it is created. If the value is None an existing property is deleted. Existing object properties that are not present in the given propert...
370,519
def _generalized_word_starts(self, xs): self.word_starts = [] i = 0 for n in range(len(xs)): self.word_starts.append(i) i += len(xs[n]) + 1
Helper method returns the starting indexes of strings in GST
370,520
def create_site(self, webspace_name, website_name, geo_region, host_names, plan=, compute_mode=, server_farm=None, site_mode=None): VirtualDedicatedPlanSharedDedicatedSharedDedicatedLimitedBasicLimitedBasic xml = _XmlSerializer.create_website_to_xml(webspace_name,...
Create a website. webspace_name: The name of the webspace. website_name: The name of the website. geo_region: The geographical region of the webspace that will be created. host_names: An array of fully qualified domain names for website. O...
370,521
def create_topic(self, topic_name, topic=None, fail_on_exist=False): _validate_not_none(, topic_name) request = HTTPRequest() request.method = request.host = self._get_host() request.path = + _str(topic_name) + request.body = _get_request_body(_convert_topic_t...
Creates a new topic. Once created, this topic resource manifest is immutable. topic_name: Name of the topic to create. topic: Topic object to create. fail_on_exist: Specify whether to throw an exception when the topic exists.
370,522
def length_degrees(self): d_angle = self.sign * (self.to_angle - self.from_angle) if (d_angle > 360): return 360.0 elif (d_angle < 0): return d_angle % 360.0 else: return abs(d_angle)
Computes the length of the arc in degrees. The length computation corresponds to what you would expect if you would draw the arc using matplotlib taking direction into account. >>> Arc((0,0), 1, 0, 0, True).length_degrees() 0.0 >>> Arc((0,0), 2, 0, 0, False).length_degrees() ...
370,523
def as_bulk_queries(queries, bulk_size): stmt_dict = defaultdict(list) for stmt, args in queries: bulk_args = stmt_dict[stmt] bulk_args.append(args) if len(bulk_args) == bulk_size: yield stmt, bulk_args del stmt_dict[stmt] for stmt, bulk_args in stmt_dict...
Group a iterable of (stmt, args) by stmt into (stmt, bulk_args). bulk_args will be a list of the args grouped by stmt. len(bulk_args) will be <= bulk_size
370,524
def json_request(self, registration_ids, data=None, collapse_key=None, delay_while_idle=False, time_to_live=None, retries=5, dry_run=False): if not registration_ids: raise GCMMissingRegistrationException("Missing registration_ids") if len(registration_ids) > 10...
Makes a JSON request to GCM servers :param registration_ids: list of the registration ids :param data: dict mapping of key-value pairs of messages :return dict of response body from Google including multicast_id, success, failure, canonical_ids, etc :raises GCMMissingRegistrationExcepti...
370,525
def update_listener(self, lbaas_listener, body=None): return self.put(self.lbaas_listener_path % (lbaas_listener), body=body)
Updates a lbaas_listener.
370,526
def flavor_extra_set(request, flavor_id, metadata): flavor = _nova.novaclient(request).flavors.get(flavor_id) if (not metadata): return None return flavor.set_keys(metadata)
Set the flavor extra spec keys.
370,527
def sam2fastq(sam, singles = False, force = False): L, R = None, None for line in sam: if line.startswith() is True: continue line = line.strip().split() bit = [True if i == else False \ for i in bin(int(line[1])).split()[1][::-1]] while len(bit)...
convert sam to fastq
370,528
def parse_services(config, services): enabled = 0 for service in services: check_disabled = config.getboolean(service, ) if not check_disabled: enabled += 1 return enabled
Parse configuration to return number of enabled service checks. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. services (list): A list of section names which holds configuration for each service check Returns: A number (i...
370,529
def probe(self): if not self.validate_file_handler(): return [] messages = [] for line in self.fh.readlines(self.max_lines): data = {"path":self.path} msg = self.new_message() parsed = self.proce...
Probe the file for new lines
370,530
def _speak_normal_inherit(self, element): self._visit(element, self._speak_normal) element.normalize()
Speak the content of element and descendants. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement
370,531
def float(self, item, default=None): try: item = self.__getattr__(item) except AttributeError as err: if default is not None: return default raise err return float(item)
Return value of key as a float :param item: key of value to transform :param default: value to return if item does not exist :return: float of value
370,532
def FromArchive(cls, path, actions_dict, resources_dict, temp_dir=None): if not path.endswith(".ship"): raise ArgumentError("Attempted to unpack a recipe archive from a file that did not end in .ship", path=path) name = os.path.basename(path)[:-5] if temp_dir is None: ...
Create a RecipeObject from a .ship archive. This archive should have been generated from a previous call to iotile-ship -a <path to yaml file> or via iotile-build using autobuild_shiparchive(). Args: path (str): The path to the recipe file that we wish to load ...
370,533
def _six_fail_hook(modname): attribute_of = modname != "six.moves" and modname.startswith("six.moves") if modname != "six.moves" and not attribute_of: raise AstroidBuildingError(modname=modname) module = AstroidBuilder(MANAGER).string_build(_IMPORTS) module.name = "six.moves" if attrib...
Fix six.moves imports due to the dynamic nature of this class. Construct a pseudo-module which contains all the necessary imports for six :param modname: Name of failed module :type modname: str :return: An astroid module :rtype: nodes.Module
370,534
def get_release_task_attachments(self, project, release_id, environment_id, attempt_id, plan_id, type): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) if release_id is not None: route_values[] = self._serialize.url(, r...
GetReleaseTaskAttachments. [Preview API] :param str project: Project ID or project name :param int release_id: :param int environment_id: :param int attempt_id: :param str plan_id: :param str type: :rtype: [ReleaseTaskAttachment]
370,535
def validate_event_and_assign_id(event): event_time = event.get(TIMESTAMP_FIELD) if event_time is None: event[TIMESTAMP_FIELD] = event_time = epoch_time_to_kronos_time(time.time()) elif type(event_time) not in (int, long): raise InvalidEventTime(event_time) _id = uuid_from_kronos_time(event_t...
Ensure that the event has a valid time. Assign a random UUID based on the event time.
370,536
def cv(params, train_set, num_boost_round=100, folds=None, nfold=5, stratified=True, shuffle=True, metrics=None, fobj=None, feval=None, init_model=None, feature_name=, categorical_feature=, early_stopping_rounds=None, fpreproc=None, verbose_eval=None, show_stdv=True, seed=0, ca...
Perform the cross-validation with given paramaters. Parameters ---------- params : dict Parameters for Booster. train_set : Dataset Data to be trained on. num_boost_round : int, optional (default=100) Number of boosting iterations. folds : generator or iterator of (train...
370,537
def to_text(value): if value < 0 or value > 65535: raise ValueError("class must be between >= 0 and <= 65535") text = _by_value.get(value) if text is None: text = + repr(value) return text
Convert a DNS rdata class to text. @param value: the rdata class value @type value: int @rtype: string @raises ValueError: the rdata class value is not >= 0 and <= 65535
370,538
def show_vertex(self, node_id, show_ce_ratio=True): from matplotlib import pyplot as plt fig = plt.figure() ax = fig.gca() plt.axis("equal") edge_gids = numpy.where((self.edges["nodes"] == node_id).any(axis=1))[0] for node_ids in self...
Plot the vicinity of a node and its ce_ratio. :param node_id: Node ID of the node to be shown. :type node_id: int :param show_ce_ratio: If true, shows the ce_ratio of the node, too. :type show_ce_ratio: bool, optional
370,539
def _set_ovsdb_server(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("name",ovsdb_server.ovsdb_server, yang_name="ovsdb-server", rest_name="ovsdb-server", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yan...
Setter method for ovsdb_server, mapped from YANG variable /ovsdb_server (list) If this variable is read-only (config: false) in the source YANG file, then _set_ovsdb_server is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ovsdb_server() ...
370,540
def priority_compare(self, other): pc = cmp(self.simplified, other.simplified) if pc is 0: if self.is_registered != other.is_registered: pc = -1 if self.is_registered else 1 elif self.platform != other.platform: ...
Compares the MIME::Type based on how reliable it is before doing a normal <=> comparison. Used by MIME::Types#[] to sort types. The comparisons involved are: 1. self.simplified <=> other.simplified (ensures that we don't try to compare different types) 2. IANA-registered defin...
370,541
def flash(self, partition, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK): return self._simple_command(, arg=partition, info_cb=info_cb, timeout_ms=timeout_ms)
Flashes the last downloaded file to the given partition. Args: partition: Partition to flash. timeout_ms: Optional timeout in milliseconds to wait for it to finish. info_cb: See Download. Usually no messages. Returns: Response to a download request, normally nothing.
370,542
def _error_repr(error): error_repr = repr(error) if len(error_repr) > 200: error_repr = hash(type(error)) return error_repr
A compact unique representation of an error.
370,543
def flush_buffers(self): while True: try: self.read(FLUSH_READ_SIZE, timeout_ms=10) except usb_exceptions.LibusbWrappingError as exception: if exception.is_timeout(): break raise
Default implementation, calls Read() until it blocks.
370,544
def get_wsgi_server( self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False ): return wsgi.Server( sock, sock.getsockname(), wsgi_app, protocol=protocol, debug=debug, log=getLogger(__name__) )
Get the WSGI server used to process requests.
370,545
def c_ideal_gas(T, k, MW): rs Chemical Engineers Rspecific = R*1000./MW return (k*Rspecific*T)**0.5
r'''Calculates speed of sound `c` in an ideal gas at temperature T. .. math:: c = \sqrt{kR_{specific}T} Parameters ---------- T : float Temperature of fluid, [K] k : float Isentropic exponent of fluid, [-] MW : float Molecular weight of fluid, [g/mol] Retur...
370,546
def _anova(self, dv=None, between=None, detailed=False, export_filename=None): aov = anova(data=self, dv=dv, between=between, detailed=detailed, export_filename=export_filename) return aov
Return one-way and two-way ANOVA.
370,547
def _safemembers(members): base = _resolved(".") for finfo in members: if _badpath(finfo.name, base): print(finfo.name, "is blocked (illegal path)") elif finfo.issym() and _badlink(finfo, base): print(finfo.name, "is blocked: Hard link to", finfo.linkname) e...
Check members of a tar archive for safety. Ensure that they do not contain paths or links outside of where we need them - this would only happen if the archive wasn't made by eqcorrscan. :type members: :class:`tarfile.TarFile` :param members: an open tarfile.
370,548
def wcs_pix_transform(ct, i, format=0): z1 = float(ct.z1) z2 = float(ct.z2) i = float(i) yscale = 128.0 / (z2 - z1) if (format == or format == ): format = 1 if (i == 0): t = 0. else: if (ct.zt == W_LINEAR): t = ((i - 1) * (z2 - z1) / 199.0) + z1 ...
Computes the WCS corrected pixel value given a coordinate transformation and the raw pixel value. Input: ct coordinate transformation. instance of coord_tran. i raw pixel intensity. format format string (optional). Returns: WCS corrected pixel value
370,549
def serializer(self, create=False, many=False): if create and many: raise Exception() def wrapper(cls): cls.__kind__ = (create and or many and or ) return cls return wrapper
Decorator to mark a :class:`Serializer` subclass for a specific purpose, ie, to be used during object creation **or** for serializing lists of objects. :param create: Whether or not this serializer is for object creation. :param many: Whether or not this serializer is for lists of objects.
370,550
def check_payment_v2(state_engine, state_op_type, nameop, fee_block_id, token_address, burn_address, name_fee, block_id): assert name_fee is not None assert isinstance(name_fee, (int,long)) epoch_features = get_epoch_features(block_id) name = nameop[] namespace_id = get_namespace_fr...
Verify that for a version-2 namespace (burn-to-creator), the nameop paid the right amount of BTC or Stacks. It can pay either through a preorder (for registers), or directly (for renewals) Return {'status': True, 'tokens_paid': ..., 'token_units': ...} if so Return {'status': False} if not.
370,551
def ext_pillar(minion_id, pillar, command): try: command = command.replace(, minion_id) output = __salt__[](command, python_shell=True) return salt.utils.yaml.safe_load(output) except Exception: log.critical( %s\, com...
Execute a command and read the output as YAML
370,552
def partial_update(self, index, doc_type, id, doc=None, script=None, params=None, upsert=None, querystring_args=None): if querystring_args is None: querystring_args = {} if doc is None and script is None: raise InvalidQuery("script or doc can not ...
Partially update a document with a script
370,553
def import_simple_cookie(cls, simple_cookie): cookie_jar = WHTTPCookieJar() for cookie_name in simple_cookie.keys(): cookie_attrs = {} for attr_name in WHTTPCookie.cookie_attr_value_compliance.keys(): attr_value = simple_cookie[cookie_name][attr_name] if attr_value != : cookie_attrs[attr_name]...
Create cookie jar from SimpleCookie object :param simple_cookie: cookies to import :return: WHTTPCookieJar
370,554
def __get_view_tmpl(tag_key): the_view_file_4 = .format( KIND_DICS[ + tag_key.split()[-1]], tag_key.split()[1] ) the_view_file_2 = .format( KIND_DICS[ + tag_key.split()[-1]], tag_key.split()[1][:2] ) if os.path.exists(the_view_file_4): the_view_sig_str = ...
根据分类uid的4位编码来找模板。如果4位的存在,则使用4位的;不然找其父类;再不然则使用通用模板 只有View需要,edit, list使用通用模板 :return String.
370,555
def transition(self, duration, is_on=None, **kwargs): self._cancel_active_transition() dest_state = self._prepare_transition(is_on, **kwargs) total_steps = self._transition_steps(**dest_state) state_stages = [self._transition_stage(step, total_steps, **dest_state) ...
Transition to the specified state of the led. If another transition is already running, it is aborted. :param duration: The duration of the transition. :param is_on: The on-off state to transition to. :param kwargs: The state to transition to.
370,556
def pad(data, blocksize=16): padlen = blocksize - len(data) % blocksize return bytes(data + bytearray(range(1, padlen)) + bytearray((padlen - 1,)))
Pads data to blocksize according to RFC 4303. Pad length field is included in output.
370,557
def get_unique_gene_psms(self, genetable, fields, firstjoin): lastgene = None gpsms_out, gp_ids = [], [] for gpsm in self.get_proteins_psms(genetable, fields, firstjoin): if gpsm[0] != lastgene: for outpsm in gpsms_out: yield outpsm ...
Uniques the results from get_proteins_psms so each PSM as defined by gene ID / setname / psm_id will only occur once
370,558
def prepare_output(d): outDir = os.path.join(d, ) if not os.path.exists(outDir): os.mkdir(outDir) for f in os.listdir(outDir): f = os.path.join(outDir, f) if os.path.islink(f): os.remove(f) return outDir
Clean pre-existing links in output directory.
370,559
def remove_reader(self, fd): " Stop watching the file descriptor for read availability. " h = msvcrt.get_osfhandle(fd) if h in self._read_fds: del self._read_fds[h]
Stop watching the file descriptor for read availability.
370,560
def get_slab_regions(slab, blength=3.5): fcoords, indices, all_indices = [], [], [] for site in slab: neighbors = slab.get_neighbors(site, blength, include_index=True, include_image=True) for nn in neighbors: if nn[0].frac_coords[...
Function to get the ranges of the slab regions. Useful for discerning where the slab ends and vacuum begins if the slab is not fully within the cell Args: slab (Structure): Structure object modelling the surface blength (float, Ang): The bondlength between atoms. You generally want t...
370,561
def get_older_backup(self, encrypted=None, compressed=None, content_type=None, database=None, servername=None): files = self.list_backups(encrypted=encrypted, compressed=compressed, content_type=content_type, database=database, ...
Return the older backup's file name. :param encrypted: Filter by encrypted or not :type encrypted: ``bool`` or ``None`` :param compressed: Filter by compressed or not :type compressed: ``bool`` or ``None`` :param content_type: Filter by media or database backup, must be ...
370,562
def parse(cls, string): match = re.match(r + + , string) try: groups = match.groupdict() return Metric(groups[], groups[], float(g...
Parse a string and create a metric
370,563
def make_command(self, ctx, name, info): @self.command() @click.option("--debug/--no-debug", default=False, help="Show debug information") @doc(info.get("description")) def func(*args, **kwargs): if "debug" in kwargs: del kwargs["debug"] ...
make click sub-command from command info gotten from xbahn engineer
370,564
def create_connection(self, alias=, **kwargs): kwargs.setdefault(, serializer) conn = self._conns[alias] = Elasticsearch(**kwargs) return conn
Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias.
370,565
def authenticated_users(func): is_object_permission = "has_object" in func.__name__ @wraps(func) def func_wrapper(*args, **kwargs): request = args[0] if is_object_permission: request = args[1] if not(request.user and request.user.is_authenticated): ...
This decorator is used to abstract common authentication checking functionality out of permission checks. It determines which parameter is the request based on name.
370,566
def version(self) -> str: output, _ = self._execute() return output.splitlines()[0].split()[-1]
Show the version number of Android Debug Bridge.
370,567
def get_orientation(width, height): if width > height: return Orientation.LANDSCAPE elif width < height: return Orientation.PORTRAIT else: return Orientation.EQUAL
Get viewport orientation from given width and height. :type width: int :type height: int :return: viewport orientation enum :rtype: Orientation
370,568
def _Rforce(self,R,phi=0.,t=0.): return -R*(1.+R*numpy.sin(3.*phi))
NAME: _Rforce PURPOSE: evaluate the radial force for this potential INPUT: R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT: the radial force HISTORY: 2017-10-16 - Written - Bovy (UofT)
370,569
def _forbidden_attributes(obj): for key in list(obj.data.keys()): if key in list(obj.reserved_keys.keys()): obj.data.pop(key) return obj
Return the object without the forbidden attributes.
370,570
def hms2frame(hms, fps): import time t = time.strptime(hms, "%H:%M:%S") return (t.tm_hour * 60 * 60 + t.tm_min * 60 + t.tm_sec) * fps
:param hms: a string, e.g. "01:23:15" for one hour, 23 minutes 15 seconds :param fps: framerate :return: frame number
370,571
def _hash_pair(first: bytes, second: bytes) -> bytes: if first is None: return second if second is None: return first if first > second: return keccak(second + first) else: return keccak(first + second)
Computes the hash of the items in lexicographic order
370,572
def is_classvar(tp): if NEW_TYPING: return (tp is ClassVar or isinstance(tp, _GenericAlias) and tp.__origin__ is ClassVar) try: from typing import _ClassVar return type(tp) is _ClassVar except: return False
Test if the type represents a class variable. Examples:: is_classvar(int) == False is_classvar(ClassVar) == True is_classvar(ClassVar[int]) == True is_classvar(ClassVar[List[T]]) == True
370,573
def min_row_dist_sum_idx(dists): row_sums = np.apply_along_axis(arr=dists, axis=0, func1d=np.sum) return row_sums.argmin()
Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row with min dist row sum
370,574
def generate_batch(cls, strategy, size, **kwargs): assert strategy in (enums.STUB_STRATEGY, enums.BUILD_STRATEGY, enums.CREATE_STRATEGY) batch_action = getattr(cls, % strategy) return batch_action(size, **kwargs)
Generate a batch of instances. The instances will be created with the given strategy (one of BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY). Args: strategy (str): the strategy to use for generating the instance. size (int): the number of instances to generate ...
370,575
def evaluate(self, path): result = False cause = None for f in self.filters: cause, result = f.evaluate(path) if not result: break return cause, result
This method evaluates attributes of the path. Returns the cause and result of matching. Both cause and result are returned from filters that this object contains. ``path`` specifies the path.
370,576
def replace_video(api_key, api_secret, local_video_path, video_key, **kwargs): filename = os.path.basename(local_video_path) jwplatform_client = jwplatform.Client(api_key, api_secret) logging.info("Updating Video") try: response = jwplatform_client.videos.update( video_key...
Function which allows to replace the content of an EXISTING video object. :param api_key: <string> JWPlatform api-key :param api_secret: <string> JWPlatform shared-secret :param local_video_path: <string> Path to media on local machine. :param video_key: <string> Video's object ID. Can be found within ...
370,577
def _message_to_entity(msg, modelclass): ent = modelclass() for prop_name, prop in modelclass._properties.iteritems(): if prop._code_name == : continue value = getattr(msg, prop_name) if value is not None and isinstance(prop, model.StructuredProperty): if prop._repeated: value...
Recursive helper for _to_base_type() to convert a message to an entity. Args: msg: A Message instance. modelclass: A Model subclass. Returns: An instance of modelclass.
370,578
def ReleaseClick(cls): element = cls._element() action = ActionChains(Web.driver) action.release(element) action.perform()
释放按压操作
370,579
def hard_reset(self): if self.seq is not None and self.shuffle: random.shuffle(self.seq) if self.imgrec is not None: self.imgrec.reset() self.cur = 0 self._allow_read = True self._cache_data = None self._cache_label = None self._ca...
Resets the iterator and ignore roll over data
370,580
def resolveFilenameConflicts(self, dialog=True): resolved = self.wdplv.resolveFilenameConflicts() if resolved and dialog: QMessageBox.warning(self, "Filename conflicts", , QMessageBox.Ok, 0) return resolved
Goes through list of DPs to make sure that their destination names do not clash. Applies new names. Returns True if some conflicts were resolved. If dialog is True, shows confirrmation dialog.
370,581
def filehandles(path, openers_list=openers, pattern=, verbose=False): if not verbose: logging.disable(logging.VERBOSE) for opener in openers_list: try: for filehandle in opener(path=path, pattern=pattern, verbose=verbose): with closing(filehandle): ...
Main function that iterates over list of openers and decides which opener to use. :param str path: Path. :param list openers_list: List of openers. :param str pattern: Regular expression pattern. :param verbose: Print additional information. :type verbose: :py:obj:`True` or :py:obj:`False` :ret...
370,582
def resize_img(fname, targ, path, new_path, fn=None): if fn is None: fn = resize_fn(targ) dest = os.path.join(path_for(path, new_path, targ), fname) if os.path.exists(dest): return im = Image.open(os.path.join(path, fname)).convert() os.makedirs(os.path.split(dest)[0], exist_ok=True) ...
Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ.
370,583
def write_long(self, n, pack=Struct().pack): if 0 <= n <= 0xFFFFFFFF: self._output_buffer.extend(pack(n)) else: raise ValueError(, n) return self
Write an integer as an unsigned 32-bit value.
370,584
def get_file_to_text( self, share_name, directory_name, file_name, encoding=, start_range=None, end_range=None, range_get_content_md5=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): _validate_not_none(, share_name) _...
Downloads a file as unicode text, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties, metadata, and content. :param str share_name: Name of existing share. :param str directory_name: The path to the directory....
370,585
def _get_prediction_feature_weights(lgb, X, n_targets): if n_targets == 2: n_targets = 1 dump = lgb.booster_.dump_model() tree_info = dump[] _compute_node_values(tree_info) pred_leafs = lgb.booster_.predict(X, pred_leaf=True).reshape(-1, n_targets) tree_info = np.array(tree_info).re...
Return a list of {feat_id: value} dicts with feature weights, following ideas from http://blog.datadive.net/interpreting-random-forests/
370,586
def json_dumps(self, data): return json.dumps( data, separators=(, ), sort_keys=True, cls=self.json_encoder, ensure_ascii=False ).encode()
Standardized json.dumps function with separators and sorted keys set Args: data (dict or list): data to be dumped Returns: string: json
370,587
def encode(cls, line): if not line.encoded: encoding = getattr(line, , None) if encoding and encoding.upper() == cls.base64string: line.value = b64encode(line.value).decode() else: line.value = backslashEscape(str_(line.value)) ...
Backslash escape line.value.
370,588
def utf8(value): if isinstance(value, _UTF8_TYPES): return value elif isinstance(value, unicode_type): return value.encode("utf-8") else: return str(value)
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
370,589
def save(self, fp=None): self.storage.settings[] = self.get_settings_json() self.storage.save(fp)
Save to file. Parameters ---------- fp : `file`, optional Output file.
370,590
def get_overs_summary(self, match_key): overs_summary_url = self.api_path + "match/" + match_key + "/overs_summary/" response = self.get_response(overs_summary_url) return response
Calling Overs Summary API Arg: match_key: key of the match Return: json data
370,591
def create_pull(self, *args, **kwds): if len(args) + len(kwds) >= 4: return self.__create_pull_1(*args, **kwds) else: return self.__create_pull_2(*args, **kwds)
:calls: `POST /repos/:owner/:repo/pulls <http://developer.github.com/v3/pulls>`_ :param title: string :param body: string :param issue: :class:`github.Issue.Issue` :param base: string :param head: string :param maintainer_can_modify: bool :rtype: :class:`github.Pu...
370,592
def match(self, other, psd=None, low_frequency_cutoff=None, high_frequency_cutoff=None): return self.to_frequencyseries().match(other, psd=psd, low_frequency_cutoff=low_frequency_cutoff, high_frequency_cutoff=high_frequency_cutoff)
Return the match between the two TimeSeries or FrequencySeries. Return the match between two waveforms. This is equivelant to the overlap maximized over time and phase. By default, the other vector will be resized to match self. This may remove high frequency content or the end of the v...
370,593
def render(self): value = self.value if value is None: value = [] fmt = [Int.fmt] data = [len(value)] for item_value in value: if issubclass(self.item_class, Primitive): item = self.item_class(item_value) else: ...
Creates a composite ``struct`` format and the data to render with it. The format and data are prefixed with a 32-bit integer denoting the number of elements, after which each of the items in the array value are ``render()``-ed and added to the format and data as well.
370,594
def bellman_segmentation(self, x, states): peaks, prominences = get_signal_peaks_and_prominences(x) bellman_idx = BellmanKSegment(prominences, states) return peaks, prominences, bellman_idx
Divide a univariate time-series, data_frame, into states contiguous segments, using Bellman k-segmentation algorithm on the peak prominences of the data. :param x: The time series to assess freeze of gait on. This could be x, y, z or mag_sum_acc. :type x: pandas.Series :para...
370,595
def _stats(arr, percentiles=(2, 98), **kwargs): sample, edges = np.histogram(arr[~arr.mask], **kwargs) return { "pc": np.percentile(arr[~arr.mask], percentiles).astype(arr.dtype).tolist(), "min": arr.min().item(), "max": arr.max().item(), "std": arr.std().item(), "hi...
Calculate array statistics. Attributes ---------- arr: numpy ndarray Input array data to get the stats from. percentiles: tuple, optional Tuple of Min/Max percentiles to compute. kwargs: dict, optional These will be passed to the numpy.histogram function. Returns --...
370,596
def set_writer_position(self, name, timestamp): execute = self.cursor.execute execute(, (name,)) execute( , (name, timestamp,))
Insert a timestamp to keep track of the current writer position
370,597
def load_dataloader(self): input_transform = transforms.Compose([transforms.ToTensor(), \ transforms.Normalize((0.7136, 0.4906, 0.3283), \ (0.1138, 0.1078, 0.0917))]) training_dataset...
Description : Setup the dataloader
370,598
def add_rectangle(self, north=None, west=None, south=None, east=None, **kwargs): kwargs.setdefault(, {}) if north: kwargs[][] = north if west: kwargs[][...
Adds a rectangle dict to the Map.rectangles attribute The Google Maps API describes a rectangle using the LatLngBounds object, which defines the bounds to be drawn. The bounds use the concept of 2 delimiting points, a northwest and a southeast points, were each coordinate is defined by ...
370,599
def get_messages(self, statuses=DEFAULT_MESSAGE_STATUSES, order="sent_at desc", offset=None, count=None, content=False): req_data = [ { "status": statuses }, order, fmt_paging(offset, count) ] service = "query:Message.stats" i...
Returns a list of messages your account sent. Messages are sorted by ``order``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items (in sorted order). Returned data includes various statistics about each message, e.g., ``total_opens``, ``open_rate``,...