Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
347,500
def is_metric_cls(cls): return ( cls is not DiffParserBase and cls.__dict__.get(, True) and issubclass(cls, DiffParserBase) )
A metric class is defined as follows: - It inherits DiffParserBase - It is not DiffParserBase - It does not have __metric__ = False
347,501
def scan_videopath(videopath, callback, recursive=False): log.debug(.format( videopath=videopath, recursive=recursive)) if not videopath.exists(): log.debug(.format(videopath=videopath)) raise IllegalPathException(path=videopath) if videopath.is_dir(): log.debug(.format(...
Scan the videopath string for video files. :param videopath: Path object :param callback: Instance of ProgressCallback :param recursive: True if the scanning should happen recursive :return: tuple with list of videos and list of subtitles (videos have matched subtitles)
347,502
def get_file_list(self, lstPaths, lstXtn, lstExcluded, VERBOSE = False): if VERBOSE: print("Generating list of Files...") print("Paths = ", lstPaths) print("Xtns = ", lstXtn) print("exclude = ", lstExcluded) numFiles = 0 self.file...
builds a list of files and returns as a list
347,503
def from_attributes(cls, server, dbname, username, dbclass, port=None, query_band=None, initial_sql=None, authentication=): root = ET.Element(, authentication=authentication) xml = cls(root) xml.server = server xml.dbname = dbname xml.username = ...
Creates a new connection that can be added into a Data Source. defaults to `''` which will be treated as 'prompt' by Tableau.
347,504
def update(self, resource, timeout=-1): return self._client.update(resource, timeout=timeout)
Updates the specified data center resource. Args: resource (dict): Object to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. Returns: ...
347,505
def emit(self, signal, *args): if not (self.signalsBlocked() or self.signalBlocked(signal)): super(XViewDispatch, self).emit(SIGNAL(signal), *args)
Emits a signal through the dispatcher. :param signal | <str> *args | additional arguments
347,506
def is_proxy(): import __main__ as main ret = False try: ret = True except AttributeError: pass return ret
Return True if this minion is a proxy minion. Leverages the fact that is_linux() and is_windows both return False for proxies. TODO: Need to extend this for proxies that might run on other Unices
347,507
def chdir(self, path, shutit_pexpect_child=None, timeout=shutit_global.shutit_global_object.default_timeout, note=None, loglevel=logging.DEBUG): shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_child = shutit_pexpect_child or self.get_curren...
How to change directory will depend on whether we are in delivery mode bash or docker. @param path: Path to send file to. @param shutit_pexpect_child: See send() @param timeout: Timeout on response @param note: See send()
347,508
def iter_import_chunks(self): chunk = [] last_line = None for leaf in self.python_file.tree.body: if isinstance(leaf, (ast.Import, ast.ImportFrom)): elif not last_line or last_line and leaf.lineno == last_line[1]: chunk.append(leaf) last_line = self.python_file....
Iterate over space-separated import chunks in a file.
347,509
def top_1_tpu(inputs): inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True) mask = tf.to_int32(tf.equal(inputs_max, inputs)) index = tf.range(tf.shape(inputs)[-1]) * mask return tf.squeeze(inputs_max, -1), tf.reduce_max(index, axis=-1)
find max and argmax over the last dimension. Works well on TPU Args: inputs: A tensor with shape [..., depth] Returns: values: a Tensor with shape [...] indices: a Tensor with shape [...]
347,510
def transform(self, document): if isinstance(document, RDD): return document.map(self.transform) freq = {} for term in document: i = self.indexOf(term) freq[i] = 1.0 if self.binary else freq.get(i, 0) + 1.0 return Vectors.sparse(self.numFeatu...
Transforms the input document (list of terms) to term frequency vectors, or transform the RDD of document to RDD of term frequency vectors.
347,511
def get_contents_sig(self): try: return self.contentsig except AttributeError: pass executor = self.get_executor() result = self.contentsig = SCons.Util.MD5signature(executor.get_contents()) return result
A helper method for get_cachedir_bsig. It computes and returns the signature for this node's contents.
347,512
def set_arc(self, arc): _send_vendor_setup(self.handle, SET_RADIO_ARC, arc, 0, ()) self.arc = arc
Set the ACK retry count for radio communication
347,513
def PorodGuinierPorod(q, a, alpha, Rg, beta): return PorodGuinierMulti(q, a, alpha, Rg, beta)
Empirical Porod-Guinier-Porod scattering Inputs: ------- ``q``: independent variable ``a``: factor of the first power-law branch ``alpha``: exponent of the first power-law branch ``Rg``: radius of gyration ``beta``: exponent of the second power-law branch Formula: ...
347,514
def get_provider_links_metadata(self): metadata = dict(self._mdata[]) metadata.update({: self._my_map[]}) return Metadata(**metadata)
Gets the metadata for the provider chain. return: (osid.Metadata) - metadata for the provider chain *compliance: mandatory -- This method must be implemented.*
347,515
def create_conversation( self, parameters, custom_headers=None, raw=False, **operation_config): url = self.create_conversation.metadata[] query_parameters = {} header_parameters = {} header_parameters[] = header_parameters[] = ...
CreateConversation. Create a new Conversation. POST to this method with a * Bot being the bot creating the conversation * IsGroup set to true if this is not a direct message (default is false) * Array containing the members to include in the conversation The retu...
347,516
def nce(reference_intervals, reference_labels, estimated_intervals, estimated_labels, frame_size=0.1, beta=1.0, marginal=False): validate_structure(reference_intervals, reference_labels, estimated_intervals, estimated_labels) if reference_intervals.size == 0 or estimat...
Frame-clustering segmentation: normalized conditional entropy Computes cross-entropy of cluster assignment, normalized by the max-entropy. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals, ... est_labels) = mir_e...
347,517
def help(cls): print("for named colors use :") for c in sorted(list(cls.colors.items())): print("{:10} {}".format(*c))
prints named colors
347,518
def write_segment(buff, segment, ver, ver_range, eci=False): mode = segment.mode append_bits = buff.append_bits if eci and mode == consts.MODE_BYTE \ and segment.encoding != consts.DEFAULT_BYTE_ENCODING: append_bits(consts.MODE_ECI, 4) append_bits(get_eci_assignment_num...
\ Writes a segment. :param buff: The byte buffer. :param _Segment segment: The segment to serialize. :param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a Micro QR Code is written. :param ver_range: "M1", "M2", "M3", or "M4" if a Micro QR Code is written, ...
347,519
def deterministic_solve(model, shocks=None, start_states=None, T=100, ignore_constraints=False, maxit=100, initial_guess=None, verbose=False, tol=1e-6): n_s = len(model.calibration[]) n_x = len(model.calibration[]) epsilons = ...
Computes a perfect foresight simulation using a stacked-time algorithm. The initial state is specified either by providing a series of exogenous shocks and assuming the model is initially in equilibrium with the first value of the shock, or by specifying an initial value for the states. Parameters ...
347,520
def _match_by_uuid(self, current_venvs, uuid): for venv_str in current_venvs: venv = json.loads(venv_str) env_path = venv.get(, {}).get() _, env_uuid = os.path.split(env_path) if env_uuid == uuid: return venv
Select a venv matching exactly by uuid.
347,521
def _check_attributes(self, attributes, extra=None): extra = extra or () unknown_keys = set(attributes) - set(self._possible_attributes) - set(extra) if unknown_keys: logger.warning( % (self.__class__.__name__, unknown_keys))
Check if attributes given to the constructor can be used to instanciate a valid node.
347,522
def connect_post_namespaced_pod_proxy(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.connect_post_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) else: (data) = self.connect_post_namespaced_pod_proxy_with_http_in...
connect_post_namespaced_pod_proxy # noqa: E501 connect POST requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_post_namespaced_pod_proxy(name, namespac...
347,523
def reserveIdentifierResponse(self, pid, vendorSpecific=None): mmp_dict = {: pid} return self.POST([, pid], fields=mmp_dict, headers=vendorSpecific)
CNCore.getLogRecords(session[, fromDate][, toDate][, event][, start][, count]) → Log https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNCore.getLogRecords Implemented in d1_client.baseclient.py. CNCore.reserveIdentifier(session, pid) → Identifier h...
347,524
def initArgosApplicationSettings(app): assert app, \ "app undefined. Call QtWidgets.QApplication.instance() or QtCor.QApplication.instance() first." logger.debug("Setting Argos QApplication settings.") app.setApplicationName(info.REPO_NAME) app.setApplicationVersion(info.VERSION) app....
Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this.
347,525
def nvmlDeviceSetPersistenceMode(handle, mode): r fn = _nvmlGetFunctionPointer("nvmlDeviceSetPersistenceMode") ret = fn(handle, _nvmlEnableState_t(mode)) _nvmlCheckReturn(ret) return None
r""" /** * Set the persistence mode for the device. * * For all products. * For Linux only. * Requires root/admin permissions. * * The persistence mode determines whether the GPU driver software is torn down after the last client * exits. * * This operation takes ef...
347,526
def merge_pexes(cls, path, pex_info, interpreter, pexes, interpeter_constraints=None): with cls.merged_pex(path, pex_info, interpreter, pexes, interpeter_constraints) as builder: builder.freeze()
Generates a merged pex at path.
347,527
def pull_file(): session_token = request.headers[] repository = request.headers[] current_user = have_authenticated_user(request.environ[], repository, session_token) if current_user is False: return fail(user_auth_fail_msg) data_store = versioned_storage(config[][repository][]...
Get a file from the server
347,528
def load_key(self, key): self._serialize(key) if isinstance(key, ec.EllipticCurvePrivateKey): self.priv_key = key self.pub_key = key.public_key() else: self.pub_key = key return self
Load an Elliptic curve key :param key: An elliptic curve key instance, private or public. :return: Reference to this instance
347,529
def visit_spires_keyword_query(self, node): keyword = node.left.accept(self) value = node.right.accept(self) if isinstance(value, SimpleValueBooleanQuery): return _convert_simple_value_boolean_query_to_and_boolean_queries(value, keyword) return KeywordOp(keyword, v...
Transform a :class:`SpiresKeywordQuery` into a :class:`KeywordOp`. Notes: In case the value being a :class:`SimpleValueBooleanQuery`, the subtree is transformed to chained :class:`AndOp` queries containing :class:`KeywordOp`, whose keyword is the keyword of the current node and ...
347,530
def _generate_union_cstor_signatures(self, union, fields): for field in fields: args = self._cstor_args_from_fields( [field] if not is_void_type(field.data_type) else []) signature = fmt_signature( func=self._cstor_name_from_field(field), ...
Emits union constructor signatures to be used in the union's header file.
347,531
def update(self, old_line, new_line, once=False): nb = 0 for i, line in enumerate(self.lines): if line.match(old_line): self.lines[i] = new_line nb += 1 if once: return nb return nb
Replace all lines matching `old_line` with `new_line`. If ``once`` is set to True, remove only the first instance.
347,532
def from_file_obj(cls, fp): log.debug("Parsing email from file object") try: fp.seek(0) except IOError: pass finally: s = fp.read() return cls.from_string(s)
Init a new object from a file-like object. Not for Outlook msg. Args: fp (file-like object): file-like object of raw email Returns: Instance of MailParser
347,533
def diff_config(ctx, second_host, mode): mp_pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2) for ip in ctx.obj[]: mp_pool.apply_async(wrap.open_connection, args=(ip, ctx.obj[][], ctx.obj[][], wrap.diff_c...
Config comparison between two devices. @param ctx: The click context paramter, for receiving the object dictionary | being manipulated by other previous functions. Needed by any | function with the @click.pass_context decorator. @type ctx: click.Context @param second_host: The I...
347,534
def canPrepare(self, ppReq) -> (bool, str): if self.has_sent_prepare(ppReq): return False, .format(ppReq) return True,
Return whether the batch of requests in the PRE-PREPARE can proceed to the PREPARE step. :param ppReq: any object with identifier and requestId attributes
347,535
def edge_by_target(self): if self._edge_by_target is None: self._edge_by_target = reverse_edge_by_source_dict(self._edge_by_source_id, self._nexson_tree[]) return self._edge_by_target
Returns a reference to the dict of target node id to (edge_id, edge)
347,536
def run(args): raw_arguments = get_arguments(args[1:]) process_arguments(raw_arguments) walk.run() return True
Process command line arguments and walk inputs.
347,537
def initWithArticleUriList(uriList): q = QueryArticles() assert isinstance(uriList, list), "uriList has to be a list of strings that represent article uris" q.queryParams = { "action": "getArticles", "articleUri": uriList } return q
instead of making a query, provide a list of article URIs manually, and then produce the desired results on top of them
347,538
def sendEmail(self, emails, massType=): return SendEmailRequest( self.__serverUrl, self.sessionId, emails, massType ).post(self.__conn)
Send one or more emails from Salesforce. Parameters: emails - a dictionary or list of dictionaries, each representing a single email as described by https://www.salesforce.com/us /developer/docs/api/Content/sforce_api_calls_sendemail.htm massTyp...
347,539
def route(cls, path): if not path.startswith(): raise ValueError() def wrap(fn): setattr(fn, cls.ROUTE_ATTRIBUTE, path) return fn return wrap
A decorator to indicate that a method should be a routable HTTP endpoint. .. code-block:: python from compactor.process import Process class WebProcess(Process): @Process.route('/hello/world') def hello_world(self, handler): return handler.write('<html><title>hello...
347,540
def from_dict(data, ctx): data = data.copy() if data.get() is not None: data[] = ctx.convert_decimal_number( data.get() ) if data.get() is not None: data[] = ctx.convert_decimal_number( data.get() ) ...
Instantiate a new AccountSummary from a dict (generally from loading a JSON response). The data used to instantiate the AccountSummary is a shallow copy of the dict passed in, with any complex child types instantiated appropriately.
347,541
def _charlist(self, data) -> list: char_string = nosub = self.sas.nosub self.sas.nosub = False ll = self.sas.submit(char_string.format(data.libref, data.table + data._dsopts())) self.sas.nosub = nosub l2 = ll[].partition("VARLIST=\n") l...
Private method to return the variables in a SAS Data set that are of type char :param data: SAS Data object to process :return: list of character variables :rtype: list
347,542
def genExamplePlanet(binaryLetter=): planetPar = PlanetParameters() planetPar.addParam(, ) planetPar.addParam(, ) planetPar.addParam(, ) planetPar.addParam(, ) planetPar.addParam(, ) planetPar.addParam(, ) planetPar.addParam(, .format(ac._ExampleSystemCount, binaryLetter)) plan...
Creates a fake planet with some defaults :param `binaryLetter`: host star is part of a binary with letter binaryletter :return:
347,543
def started(name=None, user=None, group=None, chroot=None, caps=None, no_caps=False, pidfile=None, enable_core=False, fd_limit=None, verbose=False, debug=False, trace=False, yy...
Ensures, that syslog-ng is started via the given parameters. Users shouldn't use this function, if the service module is available on their system.
347,544
def mergebed(args): p = OptionParser(mergebed.__doc__) p.add_option("-w", "--weightsfile", default="weights.txt", help="Write weights to file") p.set_outfile("out.bed") opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) maps = args ...
%prog mergebed map1.bed map2.bed map3.bed ... Combine bed maps to bed format, adding the map name.
347,545
def get_camera_info(self, camera_id): response = api.request_camera_info(self.blink, self.network_id, camera_id) try: return response[][0] except (TypeError, KeyError): _LOGGER....
Retrieve camera information.
347,546
def resume(self, landingpad): br = instructions.Branch(self.block, "resume", [landingpad]) self._set_terminator(br) return br
Resume an in-flight exception.
347,547
def add_errors(self, *errors: Union[BaseSchemaError, SchemaErrorCollection]) -> None: for error in errors: self._error_cache.add(error)
Adds errors to the error store for the schema
347,548
def get_symbol_ids(symbol_yml_file, metadata): with open(symbol_yml_file, ) as stream: symbol_cfg = yaml.load(stream) symbol_ids = [] symbol_ids_set = set() for symbol in symbol_cfg: if not in symbol: logging.error("Key not found for a symbol in %s (%s)", ...
Get a list of ids which describe which class they get mapped to. Parameters ---------- symbol_yml_file : string Path to a YAML file. metadata : dict Metainformation of symbols, like the id on write-math.com. Has keys 'symbols', 'tags', 'tags2symbols'. Returns ------- ...
347,549
def lyap_r_len(**kwargs): min_len = (kwargs[] - 1) * kwargs[] + 1 min_len += kwargs[] - 1 min_len += kwargs[] * 2 + 1 return min_len
Helper function that calculates the minimum number of data points required to use lyap_r. Note that none of the required parameters may be set to None. Kwargs: kwargs(dict): arguments used for lyap_r (required: emb_dim, lag, trajectory_len and min_tsep) Returns: minimum number of data poi...
347,550
def _variant_sv(checkpoints): if not checkpoints.get("sv"): return [], [] sv = [s("detect_sv", "batch-single", [["sv_batch_rec"]], [cwlout("sv_rec", "record", fields=[cwlout(["sv", "variantcaller"], ["string", "null"]), cwlout(...
Structural variant workflow.
347,551
def handle(self): while True: try: callable = None callable = self._Q.get(True, 1.0) except Empty: continue try: if callable is self._stopit: break ...
Process queued work until interrupt() is called
347,552
def begin_segment(self, name=None, traceid=None, parent_id=None, sampling=None): seg_name = name or self.service if not seg_name: raise SegmentNameMissingException("Segment name is required.") decision = True ...
Begin a segment on the current thread and return it. The recorder only keeps one segment at a time. Create the second one without closing existing one will overwrite it. :param str name: the name of the segment :param str traceid: trace id of the segment :param int sampling: 0 m...
347,553
def cumulative_statistics(self): if self._cumulative_statistics is None: self._cumulative_statistics = WorkspaceCumulativeStatisticsList( self._version, workspace_sid=self._solution[], ) return self._cumulative_statistics
Access the cumulative_statistics :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsList
347,554
def dropna(self, subset=None): subset = check_and_obtain_subset_columns(subset, self) not_nas = [v.notna() for v in self[subset]._iter()] and_filter = reduce(lambda x, y: x & y, not_nas) return self[and_filter]
Remove missing values according to Baloo's convention. Parameters ---------- subset : list of str, optional Which columns to check for missing values in. Returns ------- DataFrame DataFrame with no null values in columns.
347,555
async def _get_payload(self, user): payload = await utils.call(self.build_payload, user) if ( not isinstance(payload, dict) or self.config.user_id() not in payload ): raise exceptions.InvalidPayload payload = await utils.call(self.add_claims...
Given a user object, create a payload and extend it as configured.
347,556
def write_shortstr(self, s): if isinstance(s, unicode): s = s.encode() self.write_octet(len(s)) self.write(s) return self
Write a string up to 255 bytes long after encoding. If passed a unicode string, encode as UTF-8.
347,557
def node_labels(self): assert list(self.node_indices)[0] == 0 labels = list("m{}".format(i) for i in self.node_indices) return NodeLabels(labels, self.node_indices)
Return the labels for macro nodes.
347,558
def _margins(vars, margins=True): if margins is False: return [] def fn(_vars): "The margin variables for a given row or column" dim_margins = [[]] for i, u in enumerate(_vars): if margins is True or u in margins: lst =...
Figure out margining variables. Given the variables that form the rows and columns, and a set of desired margins, works out which ones are possible. Variables that can't be margined over are dropped silently. Parameters ---------- vars : list variable names for rows and columns ...
347,559
def load(dirname): if not os.path.exists(dirname): raise AttributeError( % dirname) db = Database(dirname, dbmode=) chain_folders = [os.path.join(dirname, c) for c in db.get_chains()] db.chains = len(chain_folders) data = {} for chain, folder in enumerate(chain_folders): f...
Create a Database instance from the data stored in the directory.
347,560
def subcommand(self, description=, arguments={}): def decorator(func): self.register_subparser( func, func.__name__.replace(, ), description=description, arguments=arguments, ) return func return...
Decorator for quickly adding subcommands to the omnic CLI
347,561
def alert_policy_exists(self, policy_name): if next((policy for policy in self.all_alerts if policy[] == policy_name), False): return True
Check to see if an alert policy exists in NewRelic. Return True if so, False if not
347,562
def _setup_stats_plugins(self): self.stats_dict[] = {} for key in self.plugins_dict: plugin_name = self.plugins_dict[key][].__class__.__name__ temp_key = .format(p=plugin_name) self.stats_dict[][plugin_name] = {} for item in self.settings[]: ...
Sets up the plugin stats collectors
347,563
def track_from_url(url, timeout=DEFAULT_ASYNC_TIMEOUT): param_dict = dict(url = url) return _upload(param_dict, timeout, data=None)
Create a track object from a public http URL. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: url: A string giving the URL to read from. This must be on a public machine accessible by HTTP. Example: >>> t = track.track_from_url("htt...
347,564
def toArray(self): arr = np.zeros((self.size,), dtype=np.float64) arr[self.indices] = self.values return arr
Returns a copy of this SparseVector as a 1-dimensional NumPy array.
347,565
def generate_to(self, worksheet, row): super(ItemImage, self).generate_to(worksheet, row) embedded = False fmt = self.generator.formats worksheet.write(row, 3, "image", fmt[]) worksheet.write_url(row, 5, self.data[0], fmt[]) try: if self.data: ...
Generate row report. Generates a row report of the item represented by this instance and inserts it into a given worksheet at a specified row number. :param worksheet: Reference to a worksheet in which to insert row report. :param row: Row number.
347,566
def ARPLimitExceeded_originator_switch_info_switchIpV4Address(self, **kwargs): config = ET.Element("config") ARPLimitExceeded = ET.SubElement(config, "ARPLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ET.SubElement(ARPLimitExceeded, "...
Auto Generated Code
347,567
def bindRoute(self, receiver, routeName=_unspecified): if routeName is _unspecified: routeName = self.createRouteIdentifier() route = Route(self, receiver, routeName) mapping = self._routes if mapping is None: mapping = self._unstarted ...
Create a new route to associate the given route name with the given receiver. @type routeName: C{unicode} or L{NoneType} @param routeName: The identifier for the newly created route. If C{None}, boxes with no route in them will be delivered to this receiver. @r...
347,568
def _tchelper(tc_deps,evals,deps): for e in evals: if e in tc_deps: continue else: if e in deps: tc_deps[e]=deps[e] _tchelper(tc_deps,deps[e],deps) return tc_deps
modifies graph in place
347,569
def save(self, **kwargs): validated_data = [ dict(list(attrs.items()) + list(kwargs.items())) for attrs in self.validated_data ] if "id" in validated_data: ModelClass = self.Meta.model try: self.instance = ModelClass.obje...
Save and return a list of object instances.
347,570
def submitEntry(self): mcclogs, physlogs = self.selectedLogs() success = True if mcclogs != []: if not self.acceptedUser("MCC"): QMessageBox().warning(self, "Invalid User", "Please enter a valid user name!") return ...
Process user inputs and subit logbook entry when user clicks Submit button
347,571
def attrib_to_dict(element, *args, **kwargs): if len(args) > 0: return {key: element.get(key) for key in args} if len(kwargs) > 0: return {new_key: element.get(old_key) for new_key, old_key in viewitems(kwargs)} return element.attrib
For an ElementTree ``element`` extract specified attributes. If an attribute does not exists, its value will be ``None``. attrib_to_dict(element, 'attr_a', 'attr_b') -> {'attr_a': 'value', 'attr_a': 'value'} Mapping between xml attributes and dictionary keys is done with kwargs. attrib_to_dict(element...
347,572
def decode_dict( cls, obj, key_type, item_type, ): if not isinstance(obj, dict): raise Exception("expected a python dict") if key_type == str or isinstance(key_type, BinaryType) \ or (inspect.isclass(key_type) ...
Decodes json into a dictionary, handling conversion of the keys/values (the keys/values may themselves require conversion). Args: obj: the json object to decode key_type: a class object which is the conjure type of the keys in this dict item_type: a c...
347,573
def update(self): if not self._remap: return with self._remap_lock: if not self._remap: return self._rules.sort(key=lambda x: x.match_compare_key()) for rules in itervalues(self._rules_by_endpoint): rules.sort(key...
Called before matching and building to keep the compiled rules in the correct order after things changed.
347,574
def apply_payoff(self): if self._selected_action is None: raise ValueError("The action has not been selected yet.") if self._closed: raise ValueError("The payoff for this match set has already" "been applied.") self._algorithm.distrib...
Apply the payoff that has been accumulated from immediate reward and/or payments from successor match sets. Attempting to call this method before an action has been selected or after it has already been called for the same match set will result in a ValueError. Usage: ...
347,575
def do_if_has_tag(parser, token, negate=False): bits = list(token.split_contents()) if len(bits) < 2: raise TemplateSyntaxError("%r takes at least one arguments" % bits[0]) end_tag = % bits[0] has_tag = all([tag in parser.tags for tag in bits[1:]]) has_tag = (not negate and has_tag) or...
The logic for both ``{% if_has_tag %}`` and ``{% if not_has_tag %}``. Checks if all the given tags exist (or not exist if ``negate`` is ``True``) and then only parses the branch that will not error due to non-existing tags. This means that the following is essentially the same as a ``{% comment %}...
347,576
def update_meta_data_for_name_view(graphical_editor_view, name_v, publish=True): from gaphas.item import NW rel_pos = calc_rel_pos_to_parent(graphical_editor_view.editor.canvas, name_v, name_v.handles()[NW]) state_v = graphical_editor_view.editor.canvas.get_parent(name_v) state_v.model.set_meta_d...
This method updates the meta data of a name view. :param graphical_editor_view: Graphical Editor view the change occurred in :param name_v: The name view which has been changed/moved :param publish: Whether to publish the changes of the meta data
347,577
def gen_retries(start, end, intervals, time=time): for interval in intervals: now = time() if now < end: wait = min(interval, end - now) yield now - start, end - now, wait else: yield now - start, end - now, 0 break
Helper for retrying something, sleeping between attempts. Yields ``(elapsed, remaining, wait)`` tuples, giving times in seconds. The last item, `wait`, is the suggested amount of time to sleep before trying again. This function works in concert with `retries`. It's split out so that `retries` can ...
347,578
def iterrepos(self): for repo, items in self.repo_items_hash.iteritems(): if items: yield (repo, items)
A generator function that yields a (repo, [items]) tuple for each non-empty repo.
347,579
def list_partitions(self, table, retry=DEFAULT_RETRY): table = _table_arg_to_table_ref(table, default_project=self.project) meta_table = self.get_table( TableReference( self.dataset(table.dataset_id, project=table.project), "%s$__PARTITIONS_SUMMARY__"...
List the partitions in a table. Arguments: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \ :class:`~google.cloud.bigquery.table.TableReference`, \ str, \ ]): The table or reference from which to get partition...
347,580
def _try_coerce_args(self, values, other): values = values.view() if isinstance(other, bool): raise TypeError elif is_null_datetimelike(other): other = tslibs.iNaT elif isinstance(other, (datetime, np.datetime64, date)): other = self._box_fu...
Coerce values and other to dtype 'i8'. NaN and NaT convert to the smallest i8, and will correctly round-trip to NaT if converted back in _try_coerce_result. values is always ndarray-like, other may not be Parameters ---------- values : ndarray-like other : ndarra...
347,581
def send_dynamic_message(sender, message): dispatcher.send( signal=DYNAMIC_MESSAGE_SIGNAL, sender=sender, message=message)
Send a dynamic message to the listeners. Dynamic messages represents a progress. Usually it will be appended to the previous messages. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param message: An instance of our rich message class. :type message: safe.messagin...
347,582
def _create_dotdot(self, vd, parent, rock_ridge, relocated, xa, file_mode): dotdotdotdot dotdot = dr.DirectoryRecord() dotdot.new_dotdot(vd, parent, vd.sequence_number(), rock_ridge, vd.logical_block_size(), relocated, xa, file_mode) self._add_child_to_...
An internal method to create a new 'dotdot' Directory Record. Parameters: vd - The volume descriptor to attach the 'dotdot' Directory Record to. parent - The parent Directory Record for new Directory Record. rock_ridge - The Rock Ridge version to use for this entry (if any). ...
347,583
def shared_locations(self): result = {} shared_path = os.path.join(self.path, ) if os.path.isfile(shared_path): with codecs.open(shared_path, , encoding=) as f: lines = f.read().splitlines() for line in lines: key, value = line.spl...
A dictionary of shared locations whose keys are in the set 'prefix', 'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'. The corresponding value is the absolute path of that category for this distribution, and takes into account any paths selected by the user at installat...
347,584
def mulexp_action(self, text, loc, mul): exshared.setpos(loc, text) if DEBUG > 0: print("MUL_EXP:",mul) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return m = list(mul) while len(m) > 1: if not self.symtab....
Code executed after recognising a mulexp expression (something *|/ something)
347,585
def add_plugin(self, plugin_type, plugin_name, args_dict): plugin_modified = False for plugin in self.dock_json[plugin_type]: if plugin[] == plugin_name: plugin[] = args_dict plugin_modified = True if not plugin_modified: self.d...
if config has plugin, override it, else add it
347,586
def vm_action(name, kwargs=None, call=None): release if call != : raise SaltCloudSystemExit( ) if kwargs is None: kwargs = {} action = kwargs.get(, None) if action is None: raise SaltCloudSystemExit( action\ ) server, user, pass...
Submits an action to be performed on a given virtual machine. .. versionadded:: 2016.3.0 name The name of the VM to action. action The action to be performed on the VM. Available options include: - boot - delete - delete-recreate - hold - ...
347,587
def find_ledger_file(ledgerrcpath=None): if ledgerrcpath is None: ledgerrcpath = os.path.abspath(os.path.expanduser("~/.ledgerrc")) if "LEDGER_FILE" in os.environ: return os.path.abspath(os.path.expanduser(os.environ["LEDGER_FILE"])) elif os.path.exists(ledgerrcpath): l...
Returns main ledger file path or raise exception if it cannot be \ found.
347,588
def read_volume_attachment_status(self, name, **kwargs): kwargs[] = True if kwargs.get(): return self.read_volume_attachment_status_with_http_info(name, **kwargs) else: (data) = self.read_volume_attachment_status_with_http_info(name, **kwargs) r...
read_volume_attachment_status # noqa: E501 read status of the specified VolumeAttachment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_volume_attachment_status(name, async_re...
347,589
def parse_pac_file(pacfile): try: with open(pacfile) as f: pac_script = f.read() _pacparser.parse_pac_string(pac_script) except IOError: raise IOError(.format(pacfile))
Reads the pacfile and evaluates it in the Javascript engine created by init().
347,590
def xpath_on_node(self, node, xpath, **kwargs): if isinstance(node, etree._ElementTree): root = self.get_impl_root(node) namespaces_dict = root.nsmap.copy() else: namespaces_dict = node.nsmap.copy() if in kwargs: namespaces_d...
Return result of performing the given XPath query on the given node. All known namespace prefix-to-URI mappings in the document are automatically included in the XPath invocation. If an empty/default namespace (i.e. None) is defined, this is converted to the prefix name '_' so it can b...
347,591
def getWorkingSeatedZeroPoseToRawTrackingPose(self): fn = self.function_table.getWorkingSeatedZeroPoseToRawTrackingPose pmatSeatedZeroPoseToRawTrackingPose = HmdMatrix34_t() result = fn(byref(pmatSeatedZeroPoseToRawTrackingPose)) return result, pmatSeatedZeroPoseToRawTrackingPo...
Returns the preferred seated position from the working copy.
347,592
def detect_gpt(self, filename, offset, fs_guid): self.logger.debug() if fs_guid not in self.__gpt_plugins: return None else: plugins = self.__gpt_plugins.get(fs_guid) for plugin in plugins: if plugin.detect(filename, offset): ...
Used by rawdisk.session.Session to match gpt partitions agains filesystem plugins. Args: filename: device or file that it will read in order to detect the filesystem fs_id: filesystem guid to match (ex. {EBD0A0A2-B9E5-4433-87C0-68B6B72699C7}) ...
347,593
def save(self): check_bind(self) creating = self.id is None if creating and not self.__class__._has_schema_method("create"): raise MethodNotSupported("{} do not support creating.".format(self.__class__.__name__)) if not creating and not self.__class__._has_schema_me...
Either create or persist changes on this object back to the One Codex server.
347,594
def save(self, filething=None): fileobj = filething.fileobj data = _APEv2Data(fileobj) if data.is_at_start: delete_bytes(fileobj, data.end - data.start, data.start) elif data.start is not None: fileobj.seek(data.start) fileobj....
Save changes to a file. If no filename is given, the one most recently loaded is used. Tags are always written at the end of the file, and include a header and a footer.
347,595
def _serve_individual_image(self, request): run = request.args.get() tag = request.args.get() index = int(request.args.get()) sample = int(request.args.get(, 0)) data = self._get_individual_image(run, tag, index, sample) image_type = imghdr.what(None, data) content_type = _IMGHDR_TO_MIM...
Serves an individual image.
347,596
def expand_path(pathname): home_directory = find_home_directory() separators = set([os.sep]) if os.altsep is not None: separators.add(os.altsep) if len(pathname) >= 2 and pathname[0] == and pathname[1] in separators: pathname = os.path.join(home_directory, pathname[2...
Expand the home directory in a pathname based on the effective user id. :param pathname: A pathname that may start with ``~/``, indicating the path should be interpreted as being relative to the home directory of the current (effective) user. :returns: The (modified) p...
347,597
def get_task_results(self): results = self.get_task_results_without_format() if options.tunnel.string_as_binary: return compat.OrderedDict([(k, bytes(result)) for k, result in six.iteritems(results)]) else: return compat.OrderedDict([(k, str(result)) for k, resu...
Get all the task results. :return: a dict which key is task name, and value is the task result as string :rtype: dict
347,598
def map_data(self, cached=False): ret = {: {}} pmap = self.map_providers_parallel(cached=cached) exist = set() defined = set() rendered_map = copy.deepcopy(self.rendered_map) for profile_name, nodes in six.iteritems(rendered_map): if profile_name not ...
Create a data map of what to execute on
347,599
def get_socket(self, sessid=): socket = self.sockets.get(sessid) if sessid and not socket: return None if socket is None: socket = Socket(self, self.config) self.sockets[socket.sessid] = socket else: socket.incr_hits() ...
Return an existing or new client Socket.