Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
357,500
def visit(self, node): if node in self._visited: return None self._visited[node] = 1 methods = self.get_callbacks(node) if methods[0] is not None: methods[0](node) if hasattr(node, "locals"): for local_node in node.values(): ...
launch the visit starting from the given node
357,501
def mark_variables(variables, gradients, grad_reqs=): if isinstance(variables, NDArray): assert isinstance(gradients, NDArray) variables = [variables] gradients = [gradients] if isinstance(grad_reqs, string_types): grad_reqs = [_GRAD_REQ_MAP[grad_reqs]]*len(variables) e...
Mark NDArrays as variables to compute gradient for autograd. Parameters ---------- variables: NDArray or list of NDArray gradients: NDArray or list of NDArray grad_reqs: str or list of str
357,502
def convert_aws_args(aws_args): if not isinstance(aws_args, dict): raise errors.InvalidConfiguration( ) old_session_kwargs = dict( region="region_name", access_id="aws_access_key_id", secret_key="aws_secret_access_key", ) new_kwargs = {} for ...
Convert old style options into arguments to boto3.session.Session.
357,503
def get_row_failures(df, value_cols, type_cols, verbose=False, outfile=None): df["num"] = list(range(len(df))) names = value_cols.union(type_cols) value_problems = df[names.union(["num"])] failing_items = value_problems.dropna(how="all", subset=names) if not len(failing_item...
Input: already validated DataFrame, value & type column names, and output options. Get details on each detected issue, row by row. Output: DataFrame with type & value validation columns, plus an "issues" column with a dictionary of every problem for that row.
357,504
def enable_rights(self): if self.rights is None: handler_instance = RightsHandler(self) self.handlers.insert(len(self.default_handlers), handler_instance)
Enables rights management provided by :class:`fatbotslim.handlers.RightsHandler`.
357,505
def build(self, words): words = [self._normalize(tokens) for tokens in words] self._dawg = dawg.CompletionDAWG(words) self._loaded_model = True
Construct dictionary DAWG from tokenized words.
357,506
def add_task( self, title, tags=None): self.refresh task = title.strip() if task[:2] != "- ": task = "- " + task if tags: if isinstance(tags, list): if "@" not in tags[0]: tagString ...
*Add a task to this taskpaper object* **Key Arguments:** - ``title`` -- the title for the task. - ``tags`` -- tag string (*'@one @two(data)'*) or list of tags (*['one', 'two(data)']*) **Return:** - ``task`` -- the new taskpaper task object **Usage:** ...
357,507
def validate_parsed_json(obj_json, options=None): validating_list = isinstance(obj_json, list) if not options: options = ValidationOptions() if not options.no_cache: init_requests_cache(options.refresh_cache) results = None if validating_list: results = [] fo...
Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance or list which includes one of these instances, is returned...
357,508
def deliver_hook(self, instance, payload_override=None): payload = payload_override or self.serialize_hook(instance) if getattr(settings, , None): deliverer = get_module(settings.HOOK_DELIVERER) deliverer(self.target, payload, instance=instance, hook=self) else: ...
Deliver the payload to the target URL. By default it serializes to JSON and POSTs.
357,509
def get_matching_process_ids(cmd_pattern, user_pattern): import psutil import re process_list = list(psutil.process_iter()) def matches_pattern(proc, user_pattern, cmd_pattern): matches_user = True if user_pattern is None else re.match(user_pattern, proc.username()) cmdline_str = .j...
CommandLine: export PID=30196 export PID=$(python -c "import utool as ut; print(ut.get_matching_process_ids('jonc', 'python2.7'))") export PID=$(python -c "import utool as ut; print(ut.get_matching_process_ids('jonc', 'matlab'))") sudo -H echo $PID ps -o pid,comm,nice -p $PID ...
357,510
def fetch(self, order_id, data={}, **kwargs): return super(Order, self).fetch(order_id, data, **kwargs)
Fetch Order for given Id Args: order_id : Id for which order object has to be retrieved Returns: Order dict for given order Id
357,511
def disconnect(self): try: os.kill(-self.pid, signal.SIGKILL) except OSError: pass self.read_buffer = b self.write_buffer = b self.set_enabled(False) if self.read_in_state_not_started: self.print_lines(self.read_in...
We are no more interested in this remote process
357,512
def blockgen(bytes, block_size=16): for i in range(0, len(bytes), block_size): block = bytes[i:i + block_size] block_len = len(block) if block_len > 0: yield block if block_len < block_size: break
a block generator for pprp
357,513
def report(hp, rhr): if len(hp.hosts) > 1: return make_fail("TOO_MANY_HOSTS", num=len(hp.hosts)) return make_pass("TOO_MANY_HOSTS", num=len(hp.hosts))
Rule reports a response if there is more than 1 host entry defined in the /etc/hosts file. Arguments: hp (HostParser): Parser object for the custom parser in this module. rhr (RedhatRelease): Parser object for the /etc/redhat-release file.
357,514
def authorize_redirect(self, redirect_uri=None, client_id=None, client_secret=None, extra_params=None ): args = { "redirect_uri": redirect_uri, "client_id": client_id } if extra_params: args.update(extra_params) self.redirect( ...
Redirects the user to obtain OAuth authorization for this service. Some providers require that you register a Callback URL with your application. You should call this method to log the user in, and then call get_authenticated_user() in the handler you registered as your Callback URL to ...
357,515
def StoreResults(self, responses): client_id = responses.request.client_id if responses.success: logging.info("Client %s has a file %s.", client_id, self.args.filename) else: logging.info("Client %s has no file %s.", client_id, self.args.filename) self.MarkClientDone(client_id)
Stores the responses.
357,516
def evaluate(self, dataset, metric=, output_type=, iou_threshold=None, confidence_threshold=None, verbose=True): if iou_threshold is None: iou_threshold = self.non_maximum_suppression_threshold if confidence_threshold is None: confidence_threshold = 0.001 AP = ...
Evaluate the model by making predictions and comparing these to ground truth bounding box annotations. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same names as the annotations and feature used for model train...
357,517
def htmlNodeDumpFormatOutput(self, doc, cur, encoding, format): if doc is None: doc__o = None else: doc__o = doc._o if cur is None: cur__o = None else: cur__o = cur._o libxml2mod.htmlNodeDumpFormatOutput(self._o, doc__o, cur__o, encoding, format)
Dump an HTML node, recursive behaviour,children are printed too.
357,518
def _postprocess(self, x, out=None): if out is None: if self.range.field == ComplexNumbers(): out = self._tmp_r if self._tmp_r is not None else self._tmp_f elif self.range.field == RealNumbers() and not self.halfcomplex: out = self._tmp_f ...
Return the post-processed version of ``x``. C2C: use ``tmp_r`` or ``tmp_f`` (C2C operation) R2C: use ``tmp_f`` (C2C operation) HALFC: use ``tmp_r`` (R2R operation) The result is stored in ``out`` if given, otherwise in a temporary or a new array.
357,519
def list_dataset_uris(cls, base_uri, config_path): storage_account_name = generous_parse_uri(base_uri).netloc blobservice = get_blob_service(storage_account_name, config_path) containers = blobservice.list_containers(include_metadata=True) uri_list = [] for c in contai...
Return list containing URIs with base URI.
357,520
def write(self, output_file): for message_level, message_text in self: output_file.write( % (message_level, message_text)) output_file.write()
Writes this MessageHeader to an output stream. Messages are written as a sequence of *<message_text-message_level>***=** *<message_text-text>* pairs separated by '\r\n'. The sequence is terminated by a pair of '\r\n' sequences.
357,521
def make_item_ref(app, env, fromdocname, item_info): id = item_info[][] if item_info[] != : caption = + item_info[] else: caption = para = nodes.paragraph() newnode = nodes.reference(, ) innernode = nodes.emphasis(id + caption, id + caption) newnode[] = item_info[] ...
Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists.
357,522
def _set_lsp_frr_bandwidth(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=lsp_frr_bandwidth.lsp_frr_bandwidth, is_container=, presence=False, yang_name="lsp-frr-bandwidth", rest_name="bandwidth", parent=self, path_helper=self._path_helper, extmethods...
Setter method for lsp_frr_bandwidth, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/lsp_frr/lsp_frr_bandwidth (container) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_frr_bandwidth is considered as a private method. Backends looking to populat...
357,523
def _organizerPluginName(plugin): name = getattr(plugin, , None) if name is not None: return name warn( "IOrganizerPlugin now has the attribute" " and %s does not define it" % (plugin.__class__,), category=PendingDeprecationWarning) return _objectToName(plugin).deco...
Get a name for C{plugin}, taking into account the fact that it might not have defined L{IOrganizerPlugin.name}. @type plugin: L{IOrganizerPlugin} provider. @rtype: C{unicode}
357,524
def get_available_facets(self): result = [] for k, v in list(self.properties.items()): if isinstance(v, DateField): if not v.tokenize: result.append((k, "date")) elif isinstance(v, NumericFieldAbstract): result.append((...
Returns Available facets for the document
357,525
def add_event(self, key, event): assert isinstance(key, str) assert isinstance(event, bytes) self.conn.execute(, (key, event.decode()))
Add an event and its corresponding key to the store.
357,526
def increment_download_count(self, id, attachmentID, doc_type=): body = self.es.get(index=self.index_name, id=id, doc_type=, _source_include=)[] for attachment in body[]: if attachment[] == attachmentID: attachment[] += 1 self.es.update(index=self.in...
Increment the download counter of a specific file
357,527
def ip_address_2_json(self): LOGGER.debug("IPAddress.ip_address_2_json") json_obj = { : self.id, : self.ip_address, : self.fqdn, : self.ipa_os_instance_id, : self.ipa_subnet_id, } return json.dumps(json_obj)
transform ariane_clip3 OS Instance object to Ariane server JSON obj :return: Ariane JSON obj
357,528
def is_bytes(string): if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)): return True elif six.PY2 and isinstance(string, (buffer, bytearray)): return True return False
Check if a string is a bytes instance :param Union[str, bytes] string: A string that may be string or bytes like :return: Whether the provided string is a bytes type or not :rtype: bool
357,529
def min(self, expr, extra_constraints=(), solver=None, model_callback=None): if self._solver_required and solver is None: raise BackendError("%s requires a solver for evaluation" % self.__class__.__name__) return self._min(self.convert(expr), extra_constraints=self.convert_list(ext...
Return the minimum value of `expr`. :param expr: expression (an AST) to evaluate :param solver: a solver object, native to the backend, to assist in the evaluation (for example, a z3.Solver) :param extra_constraints: extra constraints (as ASTs) to add to the solver for th...
357,530
def typeset(table, field): s = set() for v in values(table, field): try: s.add(type(v).__name__) except IndexError: pass return s
Return a set containing all Python types found for values in the given field. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar', 'baz'], ... ['A', 1, '2'], ... ['B', u'2', '3.4'], ... [u'B', u'3', '7.8', True], ... ['D', u'x...
357,531
def create_task(function, *args, **kwargs): name = "{}".format(uuid4()) handler = None deps = set() if in kwargs: name = kwargs[] del kwargs[] elif function is not None: name = "{}-{}".format(function.__name__, name) if in kwargs: handler = kwargs[] ...
Create a task object name: The name of the task. function: The actual task function. It should take no arguments, and return a False-y value if it fails. dependencies: (optional, ()) Any dependencies that this task relies on.
357,532
def find_eq_stress(strains, stresses, tol=1e-10): stress_array = np.array(stresses) strain_array = np.array(strains) eq_stress = stress_array[np.all(abs(strain_array)<tol, axis=(1,2))] if eq_stress.size != 0: all_same = (abs(eq_stress - eq_stress[0]) < 1e-8).all() if len(eq_stress)...
Finds stress corresponding to zero strain state in stress-strain list Args: strains (Nx3x3 array-like): array corresponding to strains stresses (Nx3x3 array-like): array corresponding to stresses tol (float): tolerance to find zero strain state
357,533
def kl(samples1, samples2, pdf1=False, pdf2=False, bins=30, hist_min=None, hist_max=None): hist_range = (hist_min, hist_max) if not pdf1: samples1, _ = numpy.histogram(samples1, bins=bins, range=hist_range, normed=True) if not pdf2: samples2,...
Computes the Kullback-Leibler divergence for a single parameter from two distributions. Parameters ---------- samples1 : numpy.array Samples or probability density function (must also set `pdf1=True`). samples2 : numpy.array Samples or probability density function (must also set `pd...
357,534
def pop(self, key=__marker, default=__marker): heap = self._heap position = self._position if key is self.__marker: if not heap: raise KeyError() key = heap[0].key del self[key] return key try: ...
If ``key`` is in the pqdict, remove it and return its priority value, else return ``default``. If ``default`` is not provided and ``key`` is not in the pqdict, raise a ``KeyError``. If ``key`` is not provided, remove the top item and return its key, or raise ``KeyError`` if the pqdict i...
357,535
def call_gui_callback(callback, *args, **kwargs): from future.utils import raise_ from threading import Condition import sys from rafcon.utils import log global exception_info, result from gi.repository import GLib condition = Condition() exception_info = None @log.log_exceptio...
Wrapper method for GLib.idle_add This method is intended as replacement for idle_add. It wraps the method with a callback option. The advantage is that this way, the call is blocking. The method return, when the callback method has been called and executed. :param callback: The callback method, e.g. on_op...
357,536
def _collect_arrays(self): self.data_arrays = [[(self.slices[i], e.arg_dict[name]) for i, e in enumerate(self.execs)] for name, _ in self.data_shapes] self.state_arrays = [[e.arg_dict[name] for e in self.execs] for name in self....
Collect internal arrays from executors.
357,537
def bind(self, database): super(TransactionPingingPool, self).bind(database) self.begin_pending_transactions()
Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed.
357,538
def extract_text(input_file, pageno=1): if pageno is not None: pages = [ % pageno, % pageno] else: pages = [] args_gs = ( [ , , , , , , , ] + pages + [, , fspath(input_...
Use the txtwrite device to get text layout information out For details on options of -dTextFormat see https://www.ghostscript.com/doc/current/VectorDevices.htm#TXT Format is like <page> <line> <span bbox="left top right bottom" font="..." size="..."> <char bbox="...." c="X"/> :param p...
357,539
def validlocations(configuration=None): if Locations._validlocations is None: if configuration is None: configuration = Configuration.read() Locations._validlocations = configuration.call_remoteckan(, {: True}) return Locations._validlocations
Read valid locations from HDX Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. Returns: List[Dict]: A list of valid locations
357,540
def compute(self): fields = self.fields t = self.t pars = self.parameters self._started_timestamp = pendulum.now() self.stream.emit(self) try: while True: t, fields, pars = self._compute_one_step(t, fields, pars) self...
Generator which yield the actual state of the system every dt. Yields ------ tuple : t, fields Actual time and updated fields container.
357,541
def get_stats(package): grand_total = 0 if in package: package, version = package.split() try: package = normalize(package) version = None except ValueError: raise RuntimeError( % package) total, releases = count_downloads( package, json=...
Fetch raw statistics of a package, no corrections are made to this data. You should use get_corrected_stats().
357,542
def absorb(self, trits, offset=0, length=None): pad = ((len(trits) % TRIT_HASH_LENGTH) or TRIT_HASH_LENGTH) trits += [0] * (TRIT_HASH_LENGTH - pad) if length is None: length = len(trits) if length < 1: raise ...
Absorb trits into the sponge from a buffer. :param trits: Buffer that contains the trits to absorb. :param offset: Starting offset in ``trits``. :param length: Number of trits to absorb. Defaults to ``len(trits)``.
357,543
def load(self, modelfile, layer=None): self.param_file = modelfile self._load(layer) self._update(layer)
Load or update a model or layers in a model. :param modelfile: The name of the json file to load. :type modelfile: str :param layer: Optionally load only specified layer. :type layer: str
357,544
def __handle_rate_limit_exception(self, rate_limit_exception): retry_after = int( rate_limit_exception.response.headers.get(, 60)) self.log.info( "Hit Zendesk API rate limit. Pausing for %s seconds", retry_after ) time.sleep(retry_after)
Sleep for the time specified in the exception. If not specified, wait for 60 seconds.
357,545
def vary_name(name: Text): snake = re.match(r, name) if not snake: fail() camel = [x[0].upper() + x[1:] for x in name.split()] return { : name, : .join(camel), : .join(camel), }
Validates the name and creates variations
357,546
def nearest_int(x): if x == 0: return np.int64(0) elif x > 0: return np.int64(x + 0.5) else: return np.int64(x - 0.5)
Return nearest long integer to x
357,547
def _set_logical_chassis(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=logical_chassis.logical_chassis, is_container=, presence=False, yang_name="logical-chassis", rest_name="logical-chassis", parent=self, path_helper=self._path_helper, extmethods=s...
Setter method for logical_chassis, mapped from YANG variable /rbridge_id/logical_chassis (container) If this variable is read-only (config: false) in the source YANG file, then _set_logical_chassis is considered as a private method. Backends looking to populate this variable should do so via calling thi...
357,548
def get_arca_base(self, pull=True): name = self.get_arca_base_name() tag = arca.__version__ pyenv_installer = "https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer" dockerfile = f self.get_or_build_image(name, tag, dockerfile, pull=pull) ...
Returns the name and tag of image that has the basic build dependencies installed with just pyenv installed, with no python installed. (Builds or pulls the image if it doesn't exist locally.)
357,549
def write(connection, skip, directory, force): os.makedirs(directory, exist_ok=True) from .manager.bel_manager import BELManagerMixin import pybel for idx, name, manager in _iterate_managers(connection, skip): if not isinstance(manager, BELManagerMixin): continue click.s...
Write all as BEL.
357,550
def create(self, data, update=False, **kwargs): data = unjson(data) if update is True: obj = get_obj_by_request_data(self.session, self.table, data) else: obj = None return self._add(obj, data, **kwargs)
Creates a new object pretreated input data. .. code-block:: python DBSession.sacrud(Users).create({'name': 'Vasya', 'sex': 1}) Support JSON: .. code-block:: python DBSession.sacrud(Users).create('{"name": "Vasya", "sex": 1}') For adding multiple data for m2m...
357,551
def remote(): logger.info("Fetching latest data from PyPI.") results = defaultdict(list) packages = PackageVersion.objects.exclude(is_editable=True) for pv in packages: pv.update_from_pypi() results[pv.diff_status].append(pv) logger.debug("Updated package from PyPI: %r", pv)...
Update package info from PyPI.
357,552
def p_prj_name_art_1(self, p): try: if six.PY2: value = p[2].decode(encoding=) else: value = p[2] self.builder.set_file_atrificat_of_project(self.document, , value) except OrderError: self.order_error(, , p.lineno(1...
prj_name_art : ART_PRJ_NAME LINE
357,553
def find_in_coord_list(coord_list, coord, atol=1e-8): if len(coord_list) == 0: return [] diff = np.array(coord_list) - np.array(coord)[None, :] return np.where(np.all(np.abs(diff) < atol, axis=1))[0]
Find the indices of matches of a particular coord in a coord_list. Args: coord_list: List of coords to test coord: Specific coordinates atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and array. Returns: Indices of matches, e.g., [0, 1, 2, 3]. Empty ...
357,554
def next(self): try: return next(self._execution_context) except HTTPFailure as e: if self._is_partitioned_execution_info(e): query_execution_info = self._get_partitioned_execution_info(e) self._execution_context = self._create_pip...
Returns the next query result. :return: The next query result. :rtype: dict :raises StopIteration: If no more result is left.
357,555
def downsample(f1, f2, data, N, quick=False): if quick: rand_records = range(N) else: records = sum(1 for _ in open(f1)) / 4 N = records if N > records else N rand_records = sorted(random.sample(xrange(records), N)) fh1 = open_possible_gzip(f1) fh2 = open_possible_g...
get N random headers from a fastq file without reading the whole thing into memory modified from: http://www.biostars.org/p/6544/ quick=True will just grab the first N reads rather than do a true downsampling
357,556
def get_clan(self, *tags: crtag, **params: keys): url = self.api.CLAN + + .join(tags) return self._get_model(url, FullClan, **params)
Get a clan information Parameters ---------- \*tags: str Valid clan tags. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*keys: Optional[list] = None Filter which keys should be included in the response \*\*exclude: Optional...
357,557
def get_http_headers(user_agent=None, referer=None, accept_language=None): if user_agent is None: user_agent = settings.default_user_agent if referer is None: referer = settings.default_referer if accept_language is None: accept_language = settings.default_accept_language ...
Update the default requests HTTP headers with OSMnx info. Parameters ---------- user_agent : str the user agent string, if None will set with OSMnx default referer : str the referer string, if None will set with OSMnx default accept_language : str make accept-language explic...
357,558
def evaluate_conditionals_in_context (properties, context): if __debug__: from .property_set import PropertySet assert is_iterable_typed(properties, Property) assert isinstance(context, PropertySet) base = [] conditional = [] for p in properties: if p.condition: ...
Removes all conditional properties which conditions are not met For those with met conditions, removes the condition. Properies in conditions are looked up in 'context'
357,559
def get_verse(self, v=1): verse_count = len(self.verses) if v - 1 < verse_count: return self.verses[v - 1]
Get a specific verse.
357,560
def validate(self, method, *args, **kwargs): validate(method, self.auth, *args, **kwargs)
Validate authentication and values passed to the specified method. Raises a PyCronofyValidationError on error. :param string method: Method name to check. :param *args: Arguments for "Method". :param **kwargs: Keyword arguments for "Method".
357,561
def get_keystone_session(self, keystone_ip, username, password, api_version=False, admin_port=False, user_domain_name=None, domain_name=None, project_domain_name=None, project_name=None): ep = self.get_keystone_endpo...
Return a keystone session object
357,562
async def send_file(self, file_type, method, file, payload) -> Union[Dict, base.Boolean]: if file is None: files = {} elif isinstance(file, str): payload[file_type] = file files = None else: files = {file_type: file} ...
Send file https://core.telegram.org/bots/api#inputfile :param file_type: field name :param method: API method :param file: String or io.IOBase :param payload: request payload :return: response
357,563
def _choose_scheme(self): if self.style_cols[self.color] in (, , ): self.scheme = antique(10) elif self.style_cols[self.color] in (, ): self.scheme = mint(5) elif self.style_cols[self.color] in (, , ): raise ValueError( ...
Choose color scheme
357,564
def filter_slow_requests(slowness): def filter_func(log_line): slowness_int = int(slowness) return slowness_int <= log_line.time_wait_response return filter_func
Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that filters by the server response time. :...
357,565
def get_mol_filename(chebi_id): mol = get_mol(chebi_id) if mol is None: return None file_descriptor, mol_filename = tempfile.mkstemp(str(chebi_id) + , ) mol_file = open(mol_filename, ) mol_file.write(mol.get_structure()) mol_fil...
Returns mol file
357,566
def closed(self, block_identifier: BlockSpecification) -> bool: return self.token_network.channel_is_closed( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, ...
Returns if the channel is closed.
357,567
def delete_element_when_value_none(data_structure): if isinstance(data_structure, list): for element in data_structure: delete_element_when_value_none(element) elif isinstance(data_structure, dict): for element in data_structure.keys(): if data_structure[element] is ...
This method remove all entries in a Python dict when its value is None. :param data_structure: Python dict (lists are supported). e.i: [{"element1": "e1", "element2": {"element2.1": "e2", "element2.2": None}, "element3": "e3"}, {"elementA":...
357,568
def add_cmd(self, name, help=None, func=None): if self.subparsers is None: self.subparsers = self.add_subparsers( title="sub-commands", help=help or , ) parser = self.subparsers.add_parser( name, help=help, ...
If func is None, this is regarded as a sub-parser which can contains sub-command. Else, this is a leaf node in cmd tree which can not add sub-command. :rtype: AParser
357,569
def get(self, *args, **kwargs): url_arr = self.parse_url(args[0]) if len(url_arr) == 2: if url_arr[0] == : self.remove_redis_keyword(url_arr[1]) else: self.list(url_arr[0], url_arr[1]) elif len(url_arr) == 3: self.list...
/label/s/view
357,570
def p_conditional_expr(self, p): if len(p) == 2: p[0] = p[1] else: p[0] = self.asttypes.Conditional( predicate=p[1], consequent=p[3], alternative=p[5]) p[0].setpos(p, 2)
conditional_expr \ : logical_or_expr | logical_or_expr CONDOP assignment_expr COLON assignment_expr
357,571
def create_user(self, user_name, initial_password): res = self._make_ocs_request( , self.OCS_SERVICE_CLOUD, , data={: initial_password, : user_name} ) if res.status_code == 200: tree = ET.fromstring(res.content) ...
Create a new user with an initial password via provisioning API. It is not an error, if the user already existed before. If you get back an error 999, then the provisioning API is not enabled. :param user_name: name of user to be created :param initial_password: password for user bein...
357,572
def command(state, args): if len(args) > 1: print(f) return db = state.db _refresh_incomplete_anime(db) _fix_cached_completed(db)
Fix cache issues caused by schema pre-v4.
357,573
def edge_iterator(edges=[], edges_fn=None): for edge in itertools.chain(edges, files.read_edges(edges_fn)): subj = copy.deepcopy(edge["edge"]["subject"]) subj_id = str(utils._create_hash_from_doc(subj)) subj["_key"] = subj_id obj = copy.deepcopy(edge["edge"]["object"]) ...
Yield documents from edge for loading into ArangoDB
357,574
def fetch_profile_data_from_file(): with open(SEARCH_PROFILE_DATA_FILE, ) as fin: profiles = json.load(fin) counter = 0 log.debug("-" * 5) log.debug("Fetching profile data from file") for entry in profiles: new_entry = {} new_entry[] = entry[] new_entry[] = en...
takes profile data from file and saves in the profile_data DB
357,575
def _set_ta_limit(self, limit_name, value): try: self.limits[limit_name]._set_ta_limit(value) logger.debug( "Setting %s limit %s TA limit to %d", self.service_name, limit_name, value, ) except Ke...
Set the value for the limit as reported by Trusted Advisor, for the specified limit. This method should only be called by :py:class:`~.TrustedAdvisor`. :param limit_name: the name of the limit to override the value for :type limit_name: str :param value: the Trusted Advisor lim...
357,576
def get_signature_data(fileobj, filesize): fileobj.seek(0) marfile = mar.parse_stream(fileobj) if not marfile.signatures: raise IOError("Can't generate signature data for file without signature blocks") fileobj.seek(0) block = fileobj.read(8) yield block ...
Read data from MAR file that is required for MAR signatures. Args: fileboj (file-like object): file-like object to read the MAR data from filesize (int): the total size of the file Yields: blocks of bytes representing the data required to generate or validate signatures.
357,577
def submit_curation(hash_val, tag, curator, text=None, source=, ev_hash=None, is_test=False): data = {: tag, : text, : curator, : source, : ev_hash} url = % hash_val if is_test: qstr = else: qstr = return make_db_rest_request(, url, qstr, data=...
Submit a curation for the given statement at the relevant level. Parameters ---------- hash_val : int The hash corresponding to the statement. tag : str A very short phrase categorizing the error or type of curation, e.g. "grounding" for a grounding error, or "correct" if you ar...
357,578
def GetArtifactKnowledgeBase(client_obj, allow_uninitialized=False): client_schema = client_obj.Schema kb = client_obj.Get(client_schema.KNOWLEDGE_BASE) if not allow_uninitialized: if not kb: raise artifact_utils.KnowledgeBaseUninitializedError( "KnowledgeBase empty for %s." % client_obj.ur...
This generates an artifact knowledge base from a GRR client. Args: client_obj: A GRRClient object which is opened for reading. allow_uninitialized: If True we accept an uninitialized knowledge_base. Returns: A KnowledgeBase semantic value. Raises: ArtifactProcessingError: If called when the kno...
357,579
def matches_ip(self, ip): if self.cache is not None: matches_ip = self.cache.get(ip) if matches_ip is not None: return matches_ip matches_ip = IPNetwork.matches_ip( ip, read_preference=self.read_preference) ...
Return True if the given IP is blacklisted, False otherwise.
357,580
def update_ngram(self, ngram, count): query = "UPDATE _{0}_gram SET count = {1}".format(len(ngram), count) query += self._build_where_clause(ngram) query += ";" self.execute_sql(query)
Updates a given ngram in the database. The ngram has to be in the database, otherwise this method will stop with an error. Parameters ---------- ngram : iterable of str A list, set or tuple of strings. count : int The count for the given n-gram.
357,581
def safe_get(data, key_list): for key in key_list: data = data.get(key, {}) return data if data else
Safely access dictionary keys when plugin may have failed
357,582
def coord_to_tilepath(self, lat, lon, zoom): tile = self.coord_to_tile(lat, lon, zoom) return self.tile_to_path(tile)
return the tile ID that covers a latitude/longitude at a specified zoom level
357,583
def set_state(profile, state, store=): if profile.lower() not in (, , ): raise ValueError(.format(profile)) if state.lower() not in (, , ): raise ValueError(.format(state)) command = .format(profile, state) results = _netsh_command(command=command, store=store) ...
Configure the firewall state. Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private state (str): The firewall state. Valid options are: - on - off - n...
357,584
def read_criteria_file(self, criteria_file_name=None): acceptance_criteria = pmag.initialize_acceptance_criteria() if self.data_model == 3: if criteria_file_name == None: criteria_file_name = "criteria.txt" contribution = cb.Contribution(self.WD, read_ta...
reads 2.5 or 3.0 formatted PmagPy criteria file and returns a set of nested dictionary 2.5 formated criteria data that can be passed into pmag.grade to filter data. Parameters ---------- criteria_file : name of criteria file to read in Returns ------- ne...
357,585
def clone_wire(old_wire, name=None): if isinstance(old_wire, Const): return Const(old_wire.val, old_wire.bitwidth) else: if name is None: return old_wire.__class__(old_wire.bitwidth, name=old_wire.name) return old_wire.__class__(old_wire.bitwidth, name=name)
Makes a copy of any existing wire :param old_wire: The wire to clone :param name: a name fo rhte new wire Note that this function is mainly intended to be used when the two wires are from different blocks. Making two wires with the same name in the same block is not allowed
357,586
def verify(self, byts, sign): try: chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize() self.publ.verify(sign, digest, ...
Verify the signature for the given bytes using the ECC public key. Args: byts (bytes): The data bytes. sign (bytes): The signature bytes. Returns: bool: True if the data was verified, False otherwise.
357,587
def _process_response(response): if response.status_code == 404: raise Trovebox404Error("HTTP Error %d: %s" % (response.status_code, response.reason)) try: json_response = response.json() code = json_response["code"] ...
Decodes the JSON response, returning a dict. Raises an exception if an invalid response code is received.
357,588
def _convert_trigger(self, trigger_def, parent): if trigger_def.explicit_stream is None: stream = parent.resolve_identifier(trigger_def.named_event, DataStream) trigger = TrueTrigger() else: stream = trigger_def.explicit_stream trigger = trigger_...
Convert a TriggerDefinition into a stream, trigger pair.
357,589
def _get_image_infos(config,image): client = _get_client(config) infos = None try: infos = _set_id(client.inspect_image(image)) except Exception as e: pass return infos
Verify that the image exists We will try to resolve either by: - name - image_id - tag image Image Name / Image Id / Image Tag Returns dict
357,590
def push(self, metric_type, metric_id, value, timestamp=None): if type(timestamp) is datetime: timestamp = datetime_to_time_millis(timestamp) item = create_metric(metric_type, metric_id, create_datapoint(value, timestamp)) self.put(item)
Pushes a single metric_id, datapoint combination to the server. This method is an assistant method for the put method by removing the need to create data structures first. :param metric_type: MetricType to be matched (required) :param metric_id: Exact string matching metric id ...
357,591
def type_assert_dict( d, kcls=None, vcls=None, allow_none=False, cast_from=None, cast_to=None, dynamic=None, objcls=None, ctor=None, ): _check_dstruct(d, objcls) if ( d is None and dynamic is not None ): d = dynamic t = type(d) ...
Checks that every key/value in @d is an instance of @kcls: @vcls Will also unmarshal JSON objects to Python objects if the value is an instance of dict and @vcls is a class type Args: d: The dict to type assert kcls: The class to type assert for keys. ...
357,592
def reload(self, hooks=None): args = None if os.environ.get(): compline = os.environ.get() args = self.parser.parse_known_args(compline.split()[1:])[0] else: args = self.parse...
This method will reload the configuration using input argument from the command line interface. 1. pasing arguments 2. applying hooks 3. addding help argument 4. reloading configuration using cli argument like a configuration file name.
357,593
def add(self, operator, *args): if isinstance(operator, str): op = getattr(proxops, operator)(*args) elif isinstance(operator, proxops.ProximalOperatorBaseClass): op = operator else: raise ValueError("operator must be a string or a subclass of Proxim...
Adds a proximal operator to the list of operators
357,594
def doppler_width(transition, Temperature): r atom = Atom(transition.e1.element, transition.e1.isotope) m = atom.mass omega = transition.omega return omega*np.log(8*np.sqrt(2))*np.sqrt(k_B*Temperature/m/c**2)
r"""Return the Doppler width of a transition at a given temperature (in angular frequency). The usual Doppler FWHM of the rubidium D2 line (in MHz). >>> g = State("Rb", 87, 5, 0, 1/Integer(2), 2) >>> e = State("Rb", 87, 5, 1, 3/Integer(2)) >>> t = Transition(e, g) >>> omega = doppler_width(t, ...
357,595
def get_route_to(self, destination="", protocol=""): longer_pref = "" vrf = "" ip_version = None try: ip_version = IPNetwork(destination).version except AddrFormatError: return "Please specify a valid destination!" if ip_version == 4: ...
Only IPv4 supported, vrf aware, longer_prefixes parameter ready
357,596
def nsx_controller_name(self, **kwargs): name = kwargs.pop() name_args = dict(name=name) method_name = method_class = self._brocade_tunnels nsxcontroller_attr = getattr(method_class, method_name) config = nsxcontroller_attr(**name_args) if kwargs.pop(, ...
Get/Set nsx controller name Args: name: (str) : Name of the nsx controller get (bool) : Get nsx controller config(True,False) callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. ...
357,597
def compress_and_upload(data, compressed_file, s3_path, multipart_chunk_size_mb=500, method=, delete=False, access_key=None, secret_key=None): /path/to/data/path/to/compressed.tar.gzs3://my_bucket/path/to/gzbz2gz logger = log.get_logger() if all([access_key, secret_key]): configure(access_key=ac...
Compresses data and uploads to S3. S3 upload uses ``s3cmd``, so you must either: 1) Manually configure ``s3cmd`` prior to use (typically using ``s3cmd --configure``). 2) Configure ``s3cmd`` using ``s3.configure()``. 3) Pass your access key and secret key to ``compress_and_upload``, which...
357,598
def resolve_colors(n_colors=None, colormap=None, colors=None): if colormap is not None and colors is None: if isinstance(colormap, str): try: colormap = cm.get_cmap(colormap) except ValueError as e: raise YellowbrickValueError(e) n...
Generates a list of colors based on common color arguments, for example the name of a colormap or palette or another iterable of colors. The list is then truncated (or multiplied) to the specific number of requested colors. Parameters ---------- n_colors : int, default: None Specify the...
357,599
def make_item_class_for_custom_generator_class(cls): clsname = cls.__tohu_items_name__ attr_names = cls.field_gens.keys() return make_item_class(clsname, attr_names)
cls: The custom generator class for which to create an item-class