Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
356,600
def get_category_activities(self, category_id = None): category_id = category_id or -1 return self._to_dict((, , , ), self.conn.GetCategoryActivities(category_id))
Return activities for category. If category is not specified, will return activities that have no category
356,601
def linear_copy(self, deep=False): lgrid = self.copy(deep) vtk_cell_type = numpy_to_vtk(self.GetCellTypesArray(), deep=True) celltype = vtk_to_numpy(vtk_cell_type) celltype[celltype == VTK_QUADRATIC_TETRA] = VTK_TETRA celltype[celltype == VTK_QUADRATIC_PYRAMID]...
Returns a copy of the input unstructured grid containing only linear cells. Converts the following cell types to their linear equivalents. - VTK_QUADRATIC_TETRA --> VTK_TETRA - VTK_QUADRATIC_PYRAMID --> VTK_PYRAMID - VTK_QUADRATIC_WEDGE --> VTK_WEDGE - VTK_...
356,602
def list(self): return self._post( request=ApiActions.LIST.value, uri=ApiUri.HOOKS.value, ).get()
Get all current hooks :return: All hooks :rtype: list of dict :raises: This will raise a :class:`ServerException<logentries_api.exceptions.ServerException>` if there is an error from Logentries
356,603
def on_snapshot(self, callback): return Watch.for_query( self, callback, document.DocumentSnapshot, document.DocumentReference )
Monitor the documents in this collection that match this query. This starts a watch on this query using a background thread. The provided callback is run on the snapshot of the documents. Args: callback(~.firestore.query.QuerySnapshot): a callback to run when a chan...
356,604
def deployment_allocation_health(self, id, healthy_allocations=list(), unhealthy_allocations=list()): allocations = {"HealthyAllocationIDs": healthy_allocations, "UnHealthyAllocationIDs": unhealthy_allocations, "DeploymentID": id} return self.reques...
This endpoint is used to set the health of an allocation that is in the deployment manually. In some use cases, automatic detection of allocation health may not be desired. As such those task groups can be marked with an upgrade policy that uses health_check = "manual". Those allocations must ha...
356,605
def remove_user(uid): try: acl_url = urljoin(_acl_url(), .format(uid)) r = http.delete(acl_url) assert r.status_code == 204 except DCOSHTTPException as e: if e.response.status_code != 400: raise
Removes a user from the DCOS Enterprise. :param uid: user id :type uid: str
356,606
def loadinfofont(self): if self.infofont == None: self.infofont = imft.load_path(os.path.join(fontsdir, "courR10.pil"))
Auxiliary method to load font if not yet done.
356,607
def gtr(self, value): if not (isinstance(value, GTR) or isinstance(value, GTR_site_specific)): raise TypeError(" GTR instance expected") self._gtr = value
Set a new GTR object Parameters ----------- value : GTR the new GTR object
356,608
def answer_approval(self, issue_id_or_key, approval_id, decision): url = .format(issue_id_or_key, approval_id) data = {: decision} return self.post(url, headers=self.experimental_headers, data=data)
Answer a pending approval :param issue_id_or_key: str :param approval_id: str :param decision: str :return:
356,609
def __scripts(self, filestem): script_construct = open( % (self.tmpdir, RSD.CONSTRUCT), ) script_save = open( % (self.tmpdir, RSD.SAVE), ) script_subgroups = open( % (self.tmpdir, RSD.SUBGROUPS), ) for fn in RSD.SCRIPTS: os.chmod( % (self.tmpdir, fn), S_IRE...
Generates the required scripts.
356,610
def resource_absent(resource, identifier_fields, profile=, subdomain=None, api_key=None, **kwargs): ret = {: kwargs[], : {}, : None, : } for k, v in kwargs.items(): if k not in identifier_fields: continue result = delete_resource(resource, ...
Generic resource.absent state method. Pagerduty state modules should be a thin wrapper over this method, with a custom diff function. This method calls delete_resource() and formats the result as a salt state return value. example: resource_absent("users", ["id","name","email"])
356,611
def visit_comprehension(self, node, parent): newnode = nodes.Comprehension(parent) newnode.postinit( self.visit(node.target, newnode), self.visit(node.iter, newnode), [self.visit(child, newnode) for child in node.ifs], getattr(node, "is_async", No...
visit a Comprehension node by returning a fresh instance of it
356,612
def _repaint(self, drawing_context): canvas_width = self.canvas_size[1] canvas_height = self.canvas_size[0] if self.background_color: with drawing_context.saver(): drawing_context.begin_path() drawing_context.move_to(0,0) ...
Repaint the canvas item. This will occur on a thread.
356,613
def deep_copy(numpy_dict): out = {} for key in numpy_dict: out[key] = numpy_dict[key].copy() return out
Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them.
356,614
def _transform(self, Y, scan_onsets, beta, beta0, rho_e, sigma_e, rho_X, sigma2_X, rho_X0, sigma2_X0): logger.info() n_C = beta.shape[0] n_T = Y.shape[0] weight = np.concatenate((beta, beta0), axis=0) T_X = np.diag(np.concat...
Given the data Y and the response amplitudes beta and beta0 estimated in the fit step, estimate the corresponding X and X0. It is done by a forward-backward algorithm. We assume X and X0 both are vector autoregressive (VAR) processes, to capture temporal smoothness. Their...
356,615
def add_job_set(self, job_list): assert not self._closed results = Results(loop=self._loop) js = JobSet(job_list, results, self, loop=self._loop) if not js.is_done(): if self._active_js is None: self._active_js = js logger.debug("act...
Adds a job set to the manager's queue. If there is no job set running, it is activated immediately. A new job set handle is returned.
356,616
def export_hcurves_csv(ekey, dstore): oq = dstore[] info = get_info(dstore) rlzs_assoc = dstore[].get_rlzs_assoc() R = len(rlzs_assoc.realizations) sitecol = dstore[] sitemesh = get_mesh(sitecol) key, kind, fmt = get_kkf(ekey) fnames = [] checksum = dstore.get_attr(, ) hmap_...
Exports the hazard curves into several .csv files :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
356,617
def save(filename=None, family=): ** if _conf() and not filename: filename = _conf(family) log.debug(, filename) parent_dir = os.path.dirname(filename) if not os.path.isdir(parent_dir): os.makedirs(parent_dir) cmd = .format(_iptables_cmd(family)) ipt = __salt__[](cmd) ...
Save the current in-memory rules to disk CLI Example: .. code-block:: bash salt '*' iptables.save /etc/sysconfig/iptables IPv6: salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
356,618
def delete_view(self, query_criteria=None, uid=): .path.to.numbermin_value.path.to.stringdiscrete_valuespondlakestreambrook title = % self.__class__.__name__ input_fields = { : uid } for key, value in input_fields.items(): ...
a method to delete a view associated with a user design doc :param query_criteria: [optional] dictionary with valid jsonmodel query criteria :param uid: [optional] string with uid of design document to update :return: integer with status of operation an example ...
356,619
def data_available(dataset_name=None): dr = data_resources[dataset_name] if in dr: for dirs, files in zip(dr[], dr[]): for dir, file in zip(dirs, files): if not os.path.exists(os.path.join(data_path, dataset_name, dir, file)): return False else: ...
Check if the data set is available on the local machine already.
356,620
def parse_extra_model_fields(extra_model_fields): fields = defaultdict(list) for entry in extra_model_fields: model_key, field_name = parse_field_path(entry[0]) field_class = import_field(entry[1]) field_args, field_kwargs = entry[2:] try: field = field_class(*fi...
Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model and instantiating the extra fields. Returns a sequence of tuples of the form (model_key, fields) where model_key is a pair of app_label, model_name and fields is a list of (field_name, field_instance) pairs.
356,621
def get_parameters(self): parenthesis = self.tokens[-1] for token in parenthesis.tokens: if isinstance(token, IdentifierList): return token.get_identifiers() elif imt(token, i=(Function, Identifier), t=T.Literal): return [token, ] ...
Return a list of parameters.
356,622
def addDataDocuments(self, scidata_pid_list, scimeta_pid=None): mpids = self.getAggregatedScienceMetadataPids() if scimeta_pid is None: if len(mpids) > 1: raise ValueError( "No metadata PID specified and more than one choice available." ...
Add Science Data object(s) Args: scidata_pid_list : list of str List of one or more PIDs of Science Data objects scimeta_pid: str PID of a Science Metadata object that documents the Science Data objects.
356,623
def folderitem(self, obj, item, index): item["OrderNumber"] = obj.getOrderNumber() item["OrderDate"] = self.ulocalized_time(obj.getOrderDate()) item["DateDispatched"] = self.ulocalized_time(obj.getDateDispatched()) item["replace"]["OrderNumber"] = get_link( api.get_u...
Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current ind...
356,624
def read_pipette_id(self, mount) -> Optional[str]: s ID The ID is unique to this pipette, and is a string of unknown length :param mount: string with value or :return id string, or None 1234567890READ_INSTRUMENT_ID'], mount) except UnicodeDecodeError: ...
Reads in an attached pipette's ID The ID is unique to this pipette, and is a string of unknown length :param mount: string with value 'left' or 'right' :return id string, or None
356,625
def get_count(self, query=None): query = query or Query() return self.get_db().alerts.find(query.where).count()
Return total number of alerts that meet the query filter.
356,626
def get_related(self): self.related = False try: for interface in self.interfaces: if relation_ids(interface): self.related = True return self.related except AttributeError as e: log("{} {}" ...
Check if any of the context interfaces have relation ids. Set self.related and return True if one of the interfaces has relation ids.
356,627
def import_attribute(self, path): module = .join(path.split()[:-1]) function = path.split()[-1] module = importlib.import_module(module) return getattr(module, function)
Import an attribute from a module.
356,628
def ReadUntilClose(self): while True: cmd, data = self.ReadUntil(b, b) if cmd == b: self._Send(b, arg0=self.local_id, arg1=self.remote_id) break if cmd != b: if cmd == b: raise usb_exceptions.AdbComm...
Yield packets until a Close packet is received.
356,629
def lookup_color(color): if color is None: return color = color.lower() if color in COLOR_MAP: return COLOR_MAP[color] return color
Returns the hex color for any valid css color name >>> lookup_color('aliceblue') 'F0F8FF'
356,630
def savepoint(cr): if hasattr(cr, ): with cr.savepoint(): yield else: name = uuid.uuid1().hex cr.execute( % name) try: yield cr.execute( % name) except: cr.execute( % name)
return a context manager wrapping postgres savepoints
356,631
def threshold_gradients_pctile(self, thresh_pctile, min_mag=0.0): data = np.copy(self._data) gx, gy = self.gradients() gradients = np.zeros([gx.shape[0], gx.shape[1], 2]) gradients[:, :, 0] = gx gradients[:, :, 1] = gy gradient_mags = np.linalg.norm(gradients, ax...
Creates a new DepthImage by zeroing out all depths where the magnitude of the gradient at that point is greater than some percentile of all gradients. Parameters ---------- thresh_pctile : float percentile to threshold all gradients above min_mag : float ...
356,632
def prototype_adjacency(self, n_block_features, alpha=None): return -np.ones((n_block_features, n_block_features)) * 0.5 + self.prng.uniform( low=self.low, high=self.high, size=(n_block_features, n_block_features) )
Build a new graph. Doc for ".create(n_features, alpha)" Parameters ----------- n_features : int [alpha] : float (0,1) Unused. Each graph will have a minimum of (n_blocks * n_block_features**2 - n_blocks) / 2 edges and exactly this amo...
356,633
def _update(dict1,dict2,**kwargs): abcduvwxy if( in kwargs): deepcopy = kwargs[] else: deepcopy = 1 if(deepcopy == 1): dict1 = copy.deepcopy(dict1) else: pass dict1 = _extend(dict1,dict2,overwrite=True,deepcopy=deepcopy) return(dict1)
dict1 = {1:'a',2:'b',3:'c',4:'d'} dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'} _update(dict1,dict2) pobj(dict1) pobj(dict2)
356,634
def to_json(self): return { : self.name, : self.day_type, : self.location.to_json(), : self.dry_bulb_condition.to_json(), : self.humidity_condition.to_json(), : self.wind_condition.to_json(), : self.sky_condition.to_jso...
Convert the Design Day to a dictionary.
356,635
def prepare(self): self.src_folder = self.get_src_folder() st = os.stat( % self.path) os.chmod( % self.path, st.st_mode | stat.S_IEXEC)
Prepares the android project to the build process. Checks if the project uses either gradle or ant and executes the necessary steps.
356,636
def read(text, name=None): doc = docutils.utils.new_document(name, SceneScript.settings) parser = docutils.parsers.rst.Parser() parser.parse(text, doc) return doc
Read a block of text as a docutils document. :param str text: Scene script text. :param str name: An optional name for the document. :return: A document object.
356,637
def init(cls, name): clsdict = {subcls.name: subcls for subcls in cls.__subclasses__() if hasattr(subcls, )} return clsdict.get(name, cls)(name)
Return an instance of this class or an appropriate subclass
356,638
def task(*args, **kwargs): if args and hasattr(args[0], ): return _taskify(args[0]) else: def wrapper(func): global DEFAULT, SETUP, TEARDOWN func = _taskify(func) if in args: DEFAULT = func if in args: SETUP = func if in args: TEARDOWN = func if in args: TASKS.rem...
Register a function as a task, as well as applying any attributes.
356,639
def transaction_id(self): if not self._transaction_id: self._transaction_id = random.randint(0, 10000000000 - 1) return self._transaction_id
Transaction ID for Transbank, a secure random int between 0 and 999999999.
356,640
def delete_invitation(self, invitation_id, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_invitation_with_http_info(invitation_id, **kwargs) else: (data) = self.delete_invitation_with_http_info(invitation_id, **kwargs) return dat...
Delete a user invitation. # noqa: E501 An endpoint for deleting an active user invitation which has been sent for a new or an existing user to join the account. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/user-invitations/{invitation-id} -H 'Authorization: Bearer API_KEY'` # n...
356,641
def _LoadArtifactsFromFiles(self, file_paths, overwrite_if_exists=True): loaded_files = [] loaded_artifacts = [] for file_path in file_paths: try: with io.open(file_path, mode="r", encoding="utf-8") as fh: logging.debug("Loading artifacts from %s", file_path) for artif...
Load artifacts from file paths as json or yaml.
356,642
def parse_value_object(self, tup_tree): self.check_node(tup_tree, ) child = self.one_child(tup_tree, (, )) return (name(tup_tree), attrs(tup_tree), child)
:: <!ELEMENT VALUE.OBJECT (CLASS | INSTANCE)>
356,643
def set_url(self, url): self.url = url self.host, self.path = urllib.parse.urlparse(url)[1:3]
Sets the URL referring to a robots.txt file.
356,644
def set_prev_sonorus(self): prev = self.get_prev_letter() if not prev: return if not (self.is_consonant() and prev.is_consonant()): return if self.is_sonorus() and self.is_paired_consonant(): if self._get_sound(False) != : prev...
Выставляет параметры звонкости/глухости, для предыдущих согласных.
356,645
def edit_profile(session, uidentity, **kwargs): def to_none_if_empty(x): return None if not x else x profile = uidentity.profile if in kwargs: profile.name = to_none_if_empty(kwargs[]) if in kwargs: profile.email = to_none_if_empty(kwargs[]) if in kwargs: i...
Edit unique identity profile. This function allows to edit or update the profile information of the given unique identity. The values to update are given as keyword arguments. The allowed keys are listed below (other keywords will be ignored): - `name`: name of the unique identity - `ema...
356,646
def create_from_json(cls, json_data): msa = Msa() msa.msa = json_data["msa_info"]["msa"] msa.meta = json_data["meta"] if "meta" in json_data else None msa.component_results = _create_component_results(json_data, "msa_info") return msa
Deserialize msa json data into a Msa object Args: json_data (dict): The json data for this msa Returns: Msa object
356,647
def _iparam_classname(classname, arg_name): if isinstance(classname, CIMClassName): classname = classname.copy() classname.host = None classname.namespace = None elif isinstance(classname, six.string_types): classname = CIMClassName(classname) ...
Convert a class name specified in an operation method into a CIM object that can be passed to imethodcall().
356,648
def writeByte(self, byte): self.data.write(pack("B" if not self.signed else "b", byte))
Writes a byte into the L{WriteData} stream object. @type byte: int @param byte: Byte value to write into the stream.
356,649
def detach_subnets(self, subnets): if isinstance(subnets, str) or isinstance(subnets, unicode): subnets = [subnets] new_subnets = self.connection.detach_lb_to_subnets(self.name, subnets) self.subnets = new_subnets
Detaches load balancer from one or more subnets. :type subnets: string or List of strings :param subnets: The name of the subnet(s) to detach.
356,650
def masked_log_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor: if mask is not None: mask = mask.float() while mask.dim() < vector.dim(): mask = mask.unsqueeze(1) vector = vector + (mask + 1e-45).l...
``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing ``None`` in for the mask is also acceptable; you'll just get a regular log_softmax. ``vector`` can have an arbitrar...
356,651
def get_versions(self): response = self.ebs.describe_application_versions(application_name=self.app_name) return response[][][]
Returns the versions available
356,652
def download_dxfile(dxid, filename, chunksize=dxfile.DEFAULT_BUFFER_SIZE, append=False, show_progress=False, project=None, describe_output=None, **kwargs): part_retry_counter = defaultdict(lambda: 3) success = False while not success: success = _download_dxfile(dxid, ...
:param dxid: DNAnexus file ID or DXFile (file handler) object :type dxid: string or DXFile :param filename: Local filename :type filename: string :param append: If True, appends to the local file (default is to truncate local file if it exists) :type append: boolean :param project: project to us...
356,653
def write_to(self, group): items_group = group[self.name] nitems = items_group.shape[0] items_group.resize((nitems + len(self.data),)) items_group[nitems:] = self.data
Write stored items to the given HDF5 group. We assume that self.create() has been called.
356,654
def append_fallback(model, fields): fields = set(fields) trans = set() from modeltranslation.translator import translator opts = translator.get_options_for_model(model) for key, _ in opts.fields.items(): if key in fields: langs = resolution_order(get_language(), getattr(mode...
If translated field is encountered, add also all its fallback fields. Returns tuple: (set_of_new_fields_to_use, set_of_translated_field_names)
356,655
def _ed1(token): insertion = {letter.join([token[:i], token[i:]]) for letter in string.ascii_lowercase for i in range(1, len(token) + 1)} deletion = {.join([token[:i], token[i+1:]]) for i in range(1, len(token) + 1)} substitution = {letter.join([token[:i], token[i+1:]]) for letter in string.ascii_lower...
Return tokens the edit distance of which is one from the given token
356,656
def _call_middlewares(self): for middleware in self.middlewares: if self._check_condition(middleware[]): self._call_one_middleware(middleware)
Execute the middleware stack
356,657
def parse_options(): parser = argparse.ArgumentParser(description=, prog=) urls_group = parser.add_mutually_exclusive_group(required=True) urls_group.add_argument(, type=str, metavar=, ...
Parse command line arguments. Returns: options, args
356,658
def matchingPositions(self, tokenArray): s analyses; ' assert isinstance(tokenArray, list), "tokenArray should be list "+str(tokenArray) matchingPos = [] for i in range( len(tokenArray) ): token = tokenArray[i] if self.matches(token): ...
Returns a list of positions (indexes) in the tokenArray where this WordTemplate matches (the method self.matches(token) returns True). Returns an empty list if no matching tokens appear in the input list. Parameters ---------- tokenArray: list of word tokens...
356,659
def from_node(index, name, session, data): if data.startswith(): conn_url, api_url = parse_connection_string(data) data = {: conn_url, : api_url} else: try: data = json.loads(data) except (TypeError, ValueError): da...
>>> Member.from_node(-1, '', '', '{"conn_url": "postgres://foo@bar/postgres"}') is not None True >>> Member.from_node(-1, '', '', '{') Member(index=-1, name='', session='', data={})
356,660
def create_view(self, query_criteria=None, uid=): .path.to.numbermin_value.path.to.stringdiscrete_valuespondlakestreambrook title = % self.__class__.__name__ input_fields = { : uid } for key, value in input_fields.items(...
a method to add a view to a design document of a uid :param query_criteria: dictionary with valid jsonmodel query criteria :param uid: [optional] string with uid of design document to update :return: integer with status of operation an example of how to construct the quer...
356,661
def union_conforms(element: Union, etype, namespace: Dict[str, Any], conforms: Callable) -> bool: union_vals = etype.__union_params__ if sys.version_info < (3, 6) else etype.__args__ return any(conforms(element, t, namespace) for t in union_vals)
Determine whether element conforms to at least one of the types in etype :param element: element to test :param etype: type to test against :param namespace: Namespace to use for resolving forward references :param conforms: conformance test function :return: True if element conforms to at least on...
356,662
def events(self, **kwargs): events_result = self.service.events().list(**kwargs).execute() return [Event(event) for event in events_result.get("items", [])]
Fetch events meeting specified criteria
356,663
def define_new(cls, name, members, is_abstract=False): m = OrderedDict(cls._members) if set(m.keys()) & set(members.keys()): raise ValueError(" contains keys that overlap with parent") m.update(members) dct = { : m, : is_abstract,...
Define a new struct type derived from the current type. Parameters ---------- name: str Name of the struct type members: {member_name : type} Dictionary of struct member types. is_abstract: bool If set, marks the struct as abstract.
356,664
def superuser_required(view_func): @wraps(view_func) def _checklogin(request, *args, **kwargs): if request.user.is_active and request.user.is_superuser: return view_func(request, *args, **kwargs) assert hasattr(request, ), "The Django admin requires session middlew...
Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary.
356,665
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_transmitted(self, **kwargs): config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail output = ET.SubElement(get_lldp_neighbor_detail, "outp...
Auto Generated Code
356,666
def get_access_tokens(self, oauth_verifier): qb_service = OAuth1Service( consumer_key=self.consumer_key, consumer_secret=self.consumer_secret, request_token_url=self.request_token_url, access_token_url=self.access_token_url, authorize_url=self...
Wrapper around get_auth_session, returns session, and sets access_token and access_token_secret on the QB Object. :param oauth_verifier: the oauth_verifier as specified by OAuth 1.0a
356,667
def example_exc_handler(tries_remaining, exception, delay): print >> sys.stderr, "Caught , %d tries remaining, sleeping for %s seconds" % ( exception, tries_remaining, delay)
Example exception handler; prints a warning to stderr. tries_remaining: The number of tries remaining. exception: The exception instance which was raised.
356,668
def Nu_cylinder_Whitaker(Re, Pr, mu=None, muw=None): r Nu = (0.4*Re**0.5 + 0.06*Re**(2/3.))*Pr**0.3 if mu and muw: Nu *= (mu/muw)**0.25 return Nu
r'''Calculates Nusselt number for crossflow across a single tube as shown in [1]_ at a specified `Re` and `Pr`, both evaluated at the free stream temperature. Recommends a viscosity exponent correction of 0.25, which is applied only if provided. Also shown in [2]_. .. math:: Nu_D = (0.4 Re_D^{0...
356,669
def on_btn_orientation(self, event): wait = wx.BusyInfo() wx.SafeYield() size = wx.DisplaySize() size = (size[0]-0.1 * size[0], size[1]-0.1 * size[1]) if self.data_model_num == 3: frame = pmag_gui_dialogs.OrientFrameGrid3(self, -1, , ...
Create and fill wxPython grid for entering orientation data.
356,670
def delete_record(self, bucket_name, record_key, record_version=): title = % self.__class__.__name__ input_fields = { : bucket_name, : record_key, : record_version } for key, value in input_fields.items(): if value...
a method for deleting an object record in s3 :param bucket_name: string with name of bucket :param record_key: string with key value of record :param record_version: [optional] string with aws id of version of record :return: dictionary with status of delete request
356,671
def videogrep(inputfile, outputfile, search, searchtype, maxclips=0, padding=0, test=False, randomize=False, sync=0, use_transcript=False, use_vtt=False, export_clips=False): padding = padding / 1000.0 sync = sync / 1000.0 composition = [] foundSearchTerm = False if use_transcript: co...
Search through and find all instances of the search term in an srt or transcript, create a supercut around that instance, and output a new video file comprised of those supercuts.
356,672
def one_to_one(graph, nodes): edges = itertools.chain.from_iterable(graph.values()) return len(graph) == len(nodes) and len(set(edges)) == len(nodes)
Return True if graph contains only one to one mappings. The directed graph should be represented as a dictionary mapping of edges for each node. Nodes should be passed a simple list.
356,673
def main(data, utype, ctype): copula = CopulaModel(data, utype, ctype) print(copula.sampling(1, plot=True)) print(copula.model.vine_model[-1].tree_data)
Create a Vine from the data, utype and ctype
356,674
def optimizeTransform(transform): if len(transform) == 1 and transform[0][0] == : matrix = A1, B1, A2, B2, A3, B3 = transform[0][1] if matrix == [1, 0, 0, 1, 0, 0]: del transform[0] ...
Optimises a series of transformations parsed from a single transform="" attribute. The transformation list is modified in-place.
356,675
def export_svg(self): d = "" if len(self._points) > 0: d += "M "+str(self._points[0].x)+" "+str(self._points[0].y)+" " for pt in self._points: if pt.cmd == MOVETO: d += "M "+str(pt.x)+" "+str(pt.y)+" " ...
Exports the path as SVG. Uses the filename given when creating this object. The file is automatically updated to reflect changes to the path.
356,676
def _splpy_all_ports_ready(callable_): if hasattr(type(callable_), ): try: return callable_.all_ports_ready() except: ei = sys.exc_info() if streamsx._streams._runtime._call_exit(callable_, ei): return None raise e1[1] return N...
Call all_ports_ready for a primitive operator.
356,677
def _get_hanging_wall_term(self, C, rup, dists): return (C["c10"] * self._get_hanging_wall_coeffs_rx(C, rup, dists.rx) * self._get_hanging_wall_coeffs_rrup(dists) * self._get_hanging_wall_coeffs_mag(C, rup.mag) * self._get_hanging_wall_coe...
Returns the hanging wall scaling term defined in equations 7 to 16
356,678
def forever(klass, *args, **kws): with klass(*args, **kws): _log.info("Running server") try: while True: time.sleep(100) except KeyboardInterrupt: pass finally: _log.info("Stopping server...
Create a server and block the calling thread until KeyboardInterrupt. Shorthand for: :: with Server(*args, **kws): try; time.sleep(99999999) except KeyboardInterrupt: pass
356,679
def register(self, function=None, *, singleton=False, threadlocal=False, name=None): def decorator(function=None): self._set(name, function, singleton, threadlocal) return function if function: return decorator(function) return decorator
Add an object to the injector's registry. Can be used as a decorator like so: >>> @injector.register ... def my_dependency(): ... or a plain function call by passing in a callable injector.register(my_dependency) :param function: The function or callable to ad...
356,680
def groupselectmin(table, key, value, presorted=False, buffersize=None, tempdir=None, cache=True): return groupselectfirst(sort(table, value, reverse=False), key, presorted=presorted, buffersize=buffersize, tempdir=tempdir, cache=cache...
Group by the `key` field then return the row with the minimum of the `value` field within each group. N.B., will only return one row for each group, even if multiple rows have the same (minimum) value.
356,681
def _check_permission(self, name, obj=None): def redirect_or_exception(ex): if not self.request.user or not self.request.user.is_authenticated: if self.auto_login_redirect: redirect_to_login(self.request.get_full_path()) else: ...
If customer is not authorized he should not get information that object is exists. Therefore 403 is returned if object was not found or is redirected to the login page. If custmer is authorized and object was not found is returned 404. If object was found and user is not authorized is returned 4...
356,682
def Address(self): if self._address is None: self._address = Crypto.ToAddress(self.ScriptHash) return self._address
Get the wallet address associated with the token. Returns: str: base58 encoded string representing the wallet address.
356,683
def split_line(line: str) -> typing.Tuple[str, str]: index = line.find() if index == -1: return line.lower(), return line[:index].lower(), line[index:].strip()
Separates the raw line string into two strings: (1) the command and (2) the argument(s) string :param line: :return:
356,684
def create_uniq_field_dis_func(*classes): if len(classes) < 2: raise ValueError("At least two classes required.") cls_and_attrs = [(cl, set(at.name for at in fields(cl))) for cl in classes] if len([attrs for _, attrs in cls_and_attrs if len(attrs) == 0]) > 1: raise ValueError("At l...
Given attr classes, generate a disambiguation function. The function is based on unique fields.
356,685
def json_error_formatter(body, status, title, environ): body = webob.exc.strip_tags(body) status_code = int(status.split(None, 1)[0]) error_dict = { : status_code, : title, : body } return {: [error_dict]}
A json_formatter for webob exceptions.
356,686
def parse_lines(stream, separator=None): separator = None if separator is None else unicode(separator) for line in stream: line = line.rstrip(u) row = [interpret_segment(i) for i in line.split(separator)] yield line, row
Takes each line of a stream, creating a generator that yields tuples of line, row - where row is the line split by separator (or by whitespace if separator is None. :param stream: :param separator: (optional) :return: generator
356,687
def get_filedata(self, condition=None, page_size=1000): condition = validate_type(condition, type(None), Expression, *six.string_types) page_size = validate_type(page_size, *six.integer_types) if condition is None: condition = (fd_path == "~/") params = {"embed":...
Return a generator over all results matching the provided condition :param condition: An :class:`.Expression` which defines the condition which must be matched on the filedata that will be retrieved from file data store. If a condition is unspecified, the following condition ...
356,688
def error(self, message): self.print_usage(_sys.stderr) self.exit(2, _() % (self.prog, message))
error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception.
356,689
def framesig(sig, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,)), stride_trick=True): slen = len(sig) frame_len = int(round_half_up(frame_len)) frame_step = int(round_half_up(frame_step)) if slen <= frame_len: numframes = 1 else: numframes = 1 + int(math.ceil((1.0 * s...
Frame a signal into overlapping frames. :param sig: the audio signal to frame. :param frame_len: length of each frame measured in samples. :param frame_step: number of samples after the start of the previous frame that the next frame should begin. :param winfunc: the analysis window to apply to each fr...
356,690
def jump( self ): potential_jumps = self.potential_jumps() if not potential_jumps: raise BlockedLatticeError() all_transitions = transitions.Transitions( self.potential_jumps() ) random_jump = all_transitions.random() delta_t = all_transitions.time_to_jump() ...
Select a jump at random from all potential jumps, then update the lattice state. Args: None Returns: None
356,691
def prepare_tree(self): self.tree.root.branch_length = 0.001 self.tree.root.mutation_length = self.tree.root.branch_length self.tree.root.mutations = [] self.tree.ladderize() self._prepare_nodes() self._leaves_lookup = {node.name:node for node in self.tree.get_te...
Set link to parent and calculate distance to root for all tree nodes. Should be run once the tree is read and after every rerooting, topology change or branch length optimizations.
356,692
def bbox_to_poly(north, south, east, west): return Polygon([(west, south), (east, south), (east, north), (west, north)])
Convenience function to parse bbox -> poly
356,693
def has(self, querypart_name, value=None): querypart = self._queryparts.get(querypart_name) if not querypart: return False if not querypart.is_set: return False if value: return querypart.has(value) return True
Returns True if `querypart_name` with `value` is set. For example you can check if you already used condition by `sql.has('where')`. If you want to check for more information, for example if that condition also contain ID, you can do this by `sql.has('where', 'id')`.
356,694
def mapper_from_grid_stack_and_border(self, grid_stack, border): if border is not None: relocated_grid_stack = border.relocated_grid_stack_from_grid_stack(grid_stack) else: relocated_grid_stack = grid_stack geometry = self.geometry_from_grid(grid=relocated_grid...
Setup a rectangular mapper from a rectangular pixelization, as follows: 1) If a border is supplied, relocate all of the grid-stack's regular and sub grid pixels beyond the border. 2) Determine the rectangular pixelization's geometry, by laying the pixelization over the sub-grid. 3) Setup the re...
356,695
def link_sources(self): "Returns potential Link or Stream sources." if isinstance(self, GenericOverlayPlot): zorders = [] elif self.batched: zorders = list(range(self.zorder, self.zorder+len(self.hmap.last))) else: zorders = [self.zorder] if i...
Returns potential Link or Stream sources.
356,696
def pack_weights(self, args): args = args.copy() if not self._gate_names: return args for group_name in [, ]: weight = [] bias = [] for gate in self._gate_names: wname = %(self._prefix, group_name, gate) wei...
Pack separate weight matrices into a single packed weight. Parameters ---------- args : dict of str -> NDArray Dictionary containing unpacked weights. Returns ------- args : dict of str -> NDArray Dictionary with packed weights associated...
356,697
def add_task_bt(self, filename, select=False): filename = eval_path(filename) u = self.upload(filename, self.torrents_directory) t = self._load_torrent(u) if select: return t return t.submit()
Add a new BT task :param str filename: path to torrent file to upload :param bool select: whether to select files in the torrent. * True: it returns the opened torrent (:class:`.Torrent`) and can then iterate files in :attr:`.Torrent.files` and select/unsele...
356,698
def count_calls_with_dims(**dims): def counter_wrapper(fn): @functools.wraps(fn) def fn_wrapper(*args, **kwargs): counter("%s_calls" % pyformance.registry.get_qualname(fn), **dims).inc() return fn(*args, **kwargs) return fn_wrapper return ...
Decorator to track the number of times a function is called with with dimensions.
356,699
def generate_scan_parameter_description(scan_parameters): scan_parametersPlsrDACscan_parameters table_description = np.dtype([(key, tb.Int32Col(pos=idx)) for idx, key in enumerate(scan_parameters)]) return table_description
Generate scan parameter dictionary. This is the only way to dynamically create table with dictionary, cannot be done with tables.IsDescription Parameters ---------- scan_parameters : list, tuple List of scan parameters names (strings). Returns ------- table_description : dict T...