Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
17,800
def get_container_instance_logs(access_token, subscription_id, resource_group, container_group_name, container_name=None): if container_name is None: container_name = container_group_name endpoint = .join([get_rm_endpoint(), , subscription_id,...
Get the container logs for containers in a container group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. container_group_name (str): Name of container instance group. ...
17,801
def construct_ingest_query(self, static_path, columns): num_shards = self.num_shards target_partition_size = self.target_partition_size if self.target_partition_size == -1: if self.num_shards == -1: target_partition_size = DEFAULT_...
Builds an ingest query for an HDFS TSV load. :param static_path: The path on hdfs where the data is :type static_path: str :param columns: List of all the columns that are available :type columns: list
17,802
def pstdev(data): n = len(data) if n < 2: raise ValueError() ss = _ss(data) pvar = ss/n return pvar**0.5
Calculates the population standard deviation.
17,803
def start(self): t **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. userThe Proxy Minion is starting upProxy Minion could not connect to MasterProxy Minion StoppingExiting on Ctrl-c') self.shutdown() ...
Start the actual proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`.
17,804
def _sync(self): if (self._opcount > self.checkpoint_operations or datetime.now() > self._last_sync + self.checkpoint_timeout): self.log.debug("Synchronizing queue metadata.") self.queue_metadata.sync() self._last_sync = datetime.now() sel...
Synchronize the cached data with the underlyind database. Uses an internal transaction counter and compares to the checkpoint_operations and checkpoint_timeout paramters to determine whether to persist the memory store. In this implementation, this method wraps calls to C{shelve.Shelf#sync}.
17,805
def memory_objects_for_hash(self, n): return set([self[i] for i in self.addrs_for_hash(n)])
Returns a set of :class:`SimMemoryObjects` that contain expressions that contain a variable with the hash `h`.
17,806
def readme(filename, encoding=): with io.open(filename, encoding=encoding) as source: return source.read()
Read the contents of a file
17,807
def get_content(self, obj): election_day = ElectionDay.objects.get( date=self.context[]) division = obj if obj.level.name == DivisionLevel.DISTRICT: division = obj.parent special = True if self.context.get() else False return P...
All content for a state's page on an election day.
17,808
def convert_avgpool(params, w_name, scope_name, inputs, layers, weights, names): print() if names == : tf_name = + random_string(7) elif names == : tf_name = w_name else: tf_name = w_name + str(random.random()) if in params: height, width = params[] else:...
Convert Average pooling. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for k...
17,809
def simBirth(self,which_agents): AggShockConsumerType.simBirth(self,which_agents) if hasattr(self,): self.pLvlErrNow[which_agents] = 1.0 else: self.pLvlErrNow = np.ones(self.AgentCount)
Makes new consumers for the given indices. Slightly extends base method by also setting pLvlErrNow = 1.0 for new agents, indicating that they correctly perceive their productivity. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount ind...
17,810
def _request(self, request_method, endpoint=, url=, data=None, params=None, use_api_key=False, omit_api_version=False): if not data: data = {} if not params: params = {} if endpoint and omit_api_version and not url: url = % (self.base_url, endpoint) ...
Perform a http request via the specified method to an API endpoint. :param string request_method: Request method. :param string endpoint: Target endpoint. (Optional). :param string url: Override the endpoint and provide the full url (eg for pagination). (Optional). :param dict params: P...
17,811
def update(self, filter_, document, multi=False, **kwargs): self._valide_update_document(document) if multi: return self.__collect.update_many(filter_, document, **kwargs) else: return self.__collect.update_one(filter_, document, **kwargs)
update method
17,812
def add(self, key): if key not in self.map: self.map[key] = len(self.items) self.items.append(key) return self.map[key]
Add `key` as an item to this OrderedSet, then return its index. If `key` is already in the OrderedSet, return the index it already had.
17,813
def overplot_lines(ax, catlines_all_wave, list_valid_islitlets, rectwv_coeff, global_integer_offset_x_pix, global_integer_offset_y_pix, ds9_file, debugplot): for islitlet in list_valid_islitlets: crval1_line...
Overplot lines (arc/OH). Parameters ---------- ax : matplotlib axes Current plot axes. catlines_all_wave : numpy array Array with wavelengths of the lines to be overplotted. list_valid_islitlets : list of integers List with numbers of valid slitlets. rectwv_coeff : RectW...
17,814
def isObservableElement(self, elementName): if not(isinstance(elementName, str)): raise TypeError( "Element name should be a string ." + "I receive this {0}" .format(elementName)) return (True if (elementName == "*") e...
Mention if an element is an observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool
17,815
def is_admin_user(self): user = api.user.get_current() roles = user.getRoles() return "LabManager" in roles or "Manager" in roles
Checks if the user is the admin or a SiteAdmin user. :return: Boolean
17,816
def _finish_add(self, num_bytes_to_add, num_partition_bytes_to_add): for pvd in self.pvds: pvd.add_to_space_size(num_bytes_to_add + num_partition_bytes_to_add) if self.joliet_vd is not None: self.joliet_vd.add_to_space_size(num_bytes_to_add + num_partition_bytes...
An internal method to do all of the accounting needed whenever something is added to the ISO. This method should only be called by public API implementations. Parameters: num_bytes_to_add - The number of additional bytes to add to all descriptors. ...
17,817
def convert_H2OFrame_2_DMatrix(self, predictors, yresp, h2oXGBoostModel): import xgboost as xgb import pandas as pd import numpy as np from scipy.sparse import csr_matrix assert isinstance(predictors, list) or isinstance(predictors, tuple) assert h2oXGBoostModel...
This method requires that you import the following toolboxes: xgboost, pandas, numpy and scipy.sparse. This method will convert an H2OFrame to a DMatrix that can be used by native XGBoost. The H2OFrame contains numerical and enum columns alone. Note that H2O one-hot-encoding introduces a missing(NA) ...
17,818
def list_pending_work_units(self, work_spec_name, start=0, limit=None): return self.registry.filter(WORK_UNITS_ + work_spec_name, priority_min=time.time(), start=start, limit=limit)
Get a dictionary of in-progress work units for some work spec. The dictionary is from work unit name to work unit definiton. Units listed here should be worked on by some worker.
17,819
def complete_sum(self): node = self.node.complete_sum() if node is self.node: return self else: return _expr(node)
Return an equivalent DNF expression that includes all prime implicants.
17,820
def _generate_destination_for_source(self, src_ase): for sa, cont, name, dpath in self._get_destination_paths(): if self._spec.options.rename: name = str(pathlib.Path(name)) if name == : raise RuntimeError( ...
Generate entities for source path :param SyncCopy self: this :param blobxfer.models.azure.StorageEntity src_ase: source ase :rtype: blobxfer.models.azure.StorageEntity :return: destination storage entity
17,821
def isModified(self): return self.info_modified or \ self._content and self._content_digest() != self.digest
Check if either the datastream content or profile fields have changed and should be saved to Fedora. :rtype: boolean
17,822
def set(self, id_, lineno, value=, fname=None, args=None): if fname is None: if CURRENT_FILE: fname = CURRENT_FILE[-1] else: fname = sys.argv[0] self.table[id_] = ID(id_, args, value, lineno, fname)
Like the above, but issues no warning on duplicate macro definitions.
17,823
def write_training_metrics(self): with open(self.path, ) as file: writer = csv.writer(file) writer.writerow(FIELD_NAMES) for row in self.rows: writer.writerow(row)
Write Training Metrics to CSV
17,824
def load_config(path): args = [] with open(path, ) as fp: for line in fp.readlines(): if line.strip() and not line.startswith(" args.append(line.replace("\n", "")) return args
Load device configuration from file path and return list with parsed lines. :param path: Location of configuration file. :type path: str :rtype: list
17,825
def decompile_pyc(bin_pyc, output=sys.stdout): from turicreate.meta.asttools import python_source bin = bin_pyc.read() code = marshal.loads(bin[8:]) mod_ast = make_module(code) python_source(mod_ast, file=output)
decompile apython pyc or pyo binary file. :param bin_pyc: input file objects :param output: output file objects
17,826
def memory_usage(self, index=True, deep=False): result = Series([c.memory_usage(index=False, deep=deep) for col, c in self.iteritems()], index=self.columns) if index: result = Series(self.index.memory_usage(deep=deep), index=[]).a...
Return the memory usage of each column in bytes. The memory usage can optionally include the contribution of the index and elements of `object` dtype. This value is displayed in `DataFrame.info` by default. This can be suppressed by setting ``pandas.options.display.memory_usage`` to Fa...
17,827
def check(dependency=None, timeout=60): hello.c exists\hello.c compiles\prints "Hello, world!\\\\n\ def decorator(check): _check_names.append(check.__name__) check._check_dependency = dependency @functools.wraps(check) def wrapper(checks_root, dependency_state...
Mark function as a check. :param dependency: the check that this check depends on :type dependency: function :param timeout: maximum number of seconds the check can run :type timeout: int When a check depends on another, the former will only run if the latter passes. Additionally, the dependen...
17,828
def add_params(endpoint, params): p = PreparedRequest() p.prepare(url=endpoint, params=params) if PY2: return unicode(p.url) else: return p.url
Combine query endpoint and params. Example:: >>> add_params("https://www.google.com/search", {"q": "iphone"}) https://www.google.com/search?q=iphone
17,829
def ping(self): ret, data = self.sendmess(MSG_NOP, bytes()) if data or ret > 0: raise ProtocolError() if ret < 0: raise OwnetError(-ret, self.errmess[-ret])
sends a NOP packet and waits response; returns None
17,830
def get_git_isolation(): ctx = click.get_current_context(silent=True) if ctx and GIT_ISOLATION in ctx.meta: return ctx.meta[GIT_ISOLATION]
Get Git isolation from the current context.
17,831
def getPDFstr(s): if not bool(s): return "()" def make_utf16be(s): r = hexlify(bytearray([254, 255]) + bytearray(s, "UTF-16BE")) t = r if fitz_py2 else r.decode() return "<" + t + ">" r = "" for c in s: oc = ord(c) if oc...
Return a PDF string depending on its coding. Notes: If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the UTF-16BE encoding of ...
17,832
def rm_file_or_dir(path, ignore_errors=True): if os.path.exists(path): if os.path.isdir(path): if os.path.islink(path): os.unlink(path) else: shutil.rmtree(path, ignore_errors=ignore_errors) else: if os.path.islink(path): ...
Helper function to clean a certain filepath Parameters ---------- path Returns -------
17,833
def check_policies(self, account, account_policies, aws_policies): self.log.debug(.format(account.account_name)) sess = get_aws_session(account) iam = sess.client() added = {} for policyName, account_policy in account_policies.items(): if isinst...
Iterate through the policies of a specific account and create or update the policy if its missing or does not match the policy documents from Git. Returns a dict of all the policies added to the account (does not include updated policies) Args: account (:obj:`Account`): Account to c...
17,834
def pypi_search(self): spec = self.pkg_spec search_arg = self.options.pypi_search spec.insert(0, search_arg.strip()) (spec, operator) = self.parse_search_spec(spec) if not spec: return 1 for pkg in self.pypi.search(spec, operator): ...
Search PyPI by metadata keyword e.g. yolk -S name=yolk AND license=GPL @param spec: Cheese Shop search spec @type spec: list of strings spec examples: ["name=yolk"] ["license=GPL"] ["name=yolk", "AND", "license=GPL"] @returns: 0 on success or 1 if...
17,835
def AddWarning(self, warning): self._RaiseIfNotWritable() self._storage_file.AddWarning(warning) self.number_of_warnings += 1
Adds an warning. Args: warning (ExtractionWarning): an extraction warning. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
17,836
def get_user_groups(self, user_name): res = self._make_ocs_request( , self.OCS_SERVICE_CLOUD, + user_name + , ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree, [100]) ret...
Get a list of groups associated to a user. :param user_name: name of user to list groups :returns: list of groups :raises: HTTPResponseError in case an HTTP error status was returned
17,837
def match(self, s=): match = s.lower() res = {} for k in sorted(self): s = str(k) + \ if match in s.lower(): res[k] = self[k] return CMAOptions(res, unchecked=True)
return all options that match, in the name or the description, with string `s`, case is disregarded. Example: ``cma.CMAOptions().match('verb')`` returns the verbosity options.
17,838
def for_entity(obj, check_support_attachments=False): if check_support_attachments and not supports_attachments(obj): return [] return getattr(obj, ATTRIBUTE)
Return attachments on an entity.
17,839
def create(conversion_finder, parsed_att: Any, attribute_type: Type[Any], errors: Dict[Type, Exception] = None): if conversion_finder is None: msg = "No conversion finder provided to find a converter between parsed attribute of type " \ " and expected type .".format(patt=...
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param parsed_att: :param attribute_type: :param conversion_finder: :return:
17,840
def get_vcsrc(self): try: vimrc = create_module(, settings.VCSRC_PATH) except IOError: self.stderr.write("No module or package at %s\n" % settings.VCSRC_PATH) vimrc = None return vimrc
Returns in-memory created module pointing at user's configuration and extra code/commands. By default tries to create module from :setting:`VCSRC_PATH`.
17,841
def timings(reps,func,*args,**kw): return timings_out(reps,func,*args,**kw)[0:2]
timings(reps,func,*args,**kw) -> (t_total,t_per_call) Execute a function reps times, return a tuple with the elapsed total CPU time in seconds and the time per call. These are just the first two values in timings_out().
17,842
def _local_list_files(self, args): if len(args) < 2: raise SPMInvocationError() pkg_file = args[1] if not os.path.exists(pkg_file): raise SPMPackageError(.format(pkg_file)) formula_tar = tarfile.open(pkg_file, ) pkg_files = formula_tar.getmembers...
List files for a package file
17,843
def create(self, metadata, publisher_account, service_descriptors=None, providers=None, use_secret_store=True): assert isinstance(metadata, dict), f if not metadata or not Metadata.validate(metadata): raise OceanInvalidMetadata( ...
Register an asset in both the keeper's DIDRegistry (on-chain) and in the Metadata store ( Aquarius). :param metadata: dict conforming to the Metadata accepted by Ocean Protocol. :param publisher_account: Account of the publisher registering this asset :param service_descriptors: list of...
17,844
def main(): args = sys.argv if in args: print(main.__doc__) sys.exit() dataframe = extractor.command_line_dataframe([ [, False, ], [, False, ], [, False, ], [, False, ], [, False, ],...
NAME core_depthplot.py DESCRIPTION plots various measurements versus core_depth or age. plots data flagged as 'FS-SS-C' as discrete samples. SYNTAX core_depthplot.py [command line options] # or, for Anaconda users: core_depthplot_anaconda [command line options] OP...
17,845
def load_ns_sequence(eos_name): ns_sequence = [] if eos_name == : ns_sequence_path = os.path.join(pycbc.tmpltbank.NS_SEQUENCE_FILE_DIRECTORY, ) ns_sequence = np.loadtxt(ns_sequence_path) else: print() print() print() raise Exception() max_n...
Load the data of an NS non-rotating equilibrium sequence generated using the equation of state (EOS) chosen by the user. [Only the 2H 2-piecewise polytropic EOS is currently supported. This yields NSs with large radiss (15-16km).] Parameters ----------- eos_name: string NS equation of...
17,846
def _router_address(self, data): args = data.split()[1:] try: self._relay_attrs[].extend(args) except KeyError: self._relay_attrs[] = list(args)
only for IPv6 addresses
17,847
def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuse...
Return a dictionary of what changes need to be made for a file .. versionchanged:: Neon selinux attributes added CLI Example: .. code-block:: bash salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '...
17,848
def beatExtraction(st_features, win_len, PLOT=False): toWatch = [0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] max_beat_time = int(round(2.0 / win_len)) hist_all = numpy.zeros((max_beat_time,)) for ii, i in enumerate(toWatch): ...
This function extracts an estimate of the beat rate for a musical signal. ARGUMENTS: - st_features: a numpy array (n_feats x numOfShortTermWindows) - win_len: window size in seconds RETURNS: - BPM: estimates of beats per minute - Ratio: a confidence measure
17,849
def _get_code_dir(self, code_path): decompressed_dir = None try: if os.path.isfile(code_path) and code_path.endswith(self.SUPPORTED_ARCHIVE_EXTENSIONS): decompressed_dir = _unzip_file(code_path) yield decompressed_dir else: ...
Method to get a path to a directory where the Lambda function code is available. This directory will be mounted directly inside the Docker container. This method handles a few different cases for ``code_path``: - ``code_path``is a existent zip/jar file: Unzip in a temp directory and return ...
17,850
def p_variable(self, p): p[0] = [_Segment(_BINDING, p[2])] if len(p) > 4: p[0].extend(p[4]) else: p[0].append(_Segment(_TERMINAL, )) self.segment_count += 1 p[0].append(_Segment(_END_BINDING, ))
variable : LEFT_BRACE LITERAL EQUALS unbound_segments RIGHT_BRACE | LEFT_BRACE LITERAL RIGHT_BRACE
17,851
def _get_blob(self): if not self.__blob: self.__blob = self.repo.get_object(self.id) return self.__blob
read blob on access only because get_object is slow
17,852
def _kl_independent(a, b, name="kl_independent"): p = a.distribution q = b.distribution if (tensorshape_util.is_fully_defined(a.event_shape) and tensorshape_util.is_fully_defined(b.event_shape)): if a.event_shape == b.event_shape: if p.event_shape == q.event_shape: num_redu...
Batched KL divergence `KL(a || b)` for Independent distributions. We can leverage the fact that ``` KL(Independent(a) || Independent(b)) = sum(KL(a || b)) ``` where the sum is over the `reinterpreted_batch_ndims`. Args: a: Instance of `Independent`. b: Instance of `Independent`. name: (optiona...
17,853
def proxies(self, url): netloc = urllib.parse.urlparse(url).netloc proxies = {} if settings.PROXIES and settings.PROXIES.get(netloc): proxies["http"] = settings.PROXIES[netloc] proxies["https"] = settings.PROXIES[netloc] elif settings.PROXY_URL: ...
Get the transport proxy configuration :param url: string :return: Proxy configuration dictionary :rtype: Dictionary
17,854
def partition_dumps(self): manifest = self.manifest_class() manifest_size = 0 manifest_files = 0 for resource in self.resources: manifest.add(resource) manifest_size += resource.length manifest_files += 1 if (manifest_size >= self....
Yeild a set of manifest object that parition the dumps. Simply adds resources/files to a manifest until their are either the the correct number of files or the size limit is exceeded, then yields that manifest.
17,855
def model_post_save(sender, instance, created=False, **kwargs): if sender._meta.app_label == : return def notify(): table = sender._meta.db_table if created: notify_observers(table, ORM_NOTIFY_KIND_CREATE, instance.pk) else: notify_observer...
Signal emitted after any model is saved via Django ORM. :param sender: Model class that was saved :param instance: The actual instance that was saved :param created: True if a new row was created
17,856
async def take_control(self, password): cmd = "takecontrol %s" % password return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Take control of QTM. :param password: Password as entered in QTM.
17,857
def findGlyph(self, glyphName): glyphName = normalizers.normalizeGlyphName(glyphName) groupNames = self._findGlyph(glyphName) groupNames = [self.keyNormalizer.__func__( groupName) for groupName in groupNames] return groupNames
Returns a ``list`` of the group or groups associated with **glyphName**. **glyphName** will be an :ref:`type-string`. If no group is found to contain **glyphName** an empty ``list`` will be returned. :: >>> font.groups.findGlyph("A") ["A_accented"]
17,858
def xy_spectrail_arc_intersections(self, slitlet2d=None): if self.list_arc_lines is None: raise ValueError("Arc lines not sought") number_spectrum_trails = len(self.list_spectrails) if number_spectrum_trails == 0: raise ValueError("Number of available s...
Compute intersection points of spectrum trails with arc lines. The member list_arc_lines is updated with new keyword:keyval values for each arc line. Parameters ---------- slitlet2d : numpy array Slitlet image to be displayed with the computed boundaries ...
17,859
def css_property(self) -> str: prop = self.random.choice(list(CSS_PROPERTIES.keys())) val = CSS_PROPERTIES[prop] if isinstance(val, list): val = self.random.choice(val) elif val == : val = self.__text.hex_color() elif val == : val = ....
Generate a random snippet of CSS that assigns value to a property. :return: CSS property. :Examples: 'background-color: #f4d3a1'
17,860
def __driver_stub(self, text, state): origline = readline.get_line_buffer() line = origline.lstrip() if line and line[-1] == : self.__driver_helper(line) else: toks = shlex.split(line) return self.__driver_completer(toks, text, state)
Display help messages or invoke the proper completer. The interface of helper methods and completer methods are documented in the helper() decorator method and the completer() decorator method, respectively. Arguments: text: A string, that is the current completion scope. ...
17,861
def get_field_value_from_context(field_name, context_list): field_path = field_name.split() if field_path[0] == : context_index = 0 field_path.pop(0) else: context_index = -1 while field_path[0] == : context_index -= 1 field_path.pop(0) try:...
Helper to get field value from string path. String '<context>' is used to go up on context stack. It just can be used at the beginning of path: <context>.<context>.field_name_1 On the other hand, '<root>' is used to start lookup from first item on context.
17,862
def fillna_value(self, df, left, **concat_args): value = pd.Series( 0, index=[c for c in df.columns if c.endswith() and c.find() == -1]) return value
This method gives subclasses the opportunity to define how join() fills missing values. Return value must be compatible with DataFrame.fillna() value argument. Examples: - return 0: replace missing values with zero - return df.mean(): replace missing values with column mean ...
17,863
async def get_connection(self, container): if self._connpool: conn = self._connpool.pop() return RedisClientBase(conn, self) else: conn = self._create_client(container) await RedisClientBase._get_connection(self, container, conn) await...
Get an exclusive connection, useful for blocked commands and transactions. You must call release or shutdown (not recommanded) to return the connection after use. :param container: routine container :returns: RedisClientBase object, with some commands same as RedisClie...
17,864
def func_on_enter(func): def function_after_enter_pressed(ev): ev.stopPropagation() if ev.keyCode == 13: func(ev) return function_after_enter_pressed
Register the `func` as a callback reacting only to ENTER. Note: This function doesn't bind the key to the element, just creates sort of filter, which ignores all other events.
17,865
def remove_entry(self, offset, length): for index, entry in enumerate(self._entries): if entry.offset == offset and entry.length == length: del self._entries[index] break else: raise pycdlibexception.PyCdlibInternalError()
Given an offset and length, find and remove the entry in this block that corresponds. Parameters: offset - The offset of the entry to look for. length - The length of the entry to look for. Returns: Nothing.
17,866
def check(self, dsm, independence_factor=5, **kwargs): least_common_mechanism = False message = data = dsm.data categories = dsm.categories dsm_size = dsm.size[0] if not categories: categories = [] * dsm_size dependent_mod...
Check least common mechanism. Args: dsm (:class:`DesignStructureMatrix`): the DSM to check. independence_factor (int): if the maximum dependencies for one module is inferior or equal to the DSM size divided by the independence factor, then this criterion ...
17,867
def modifyModlist( old_entry: dict, new_entry: dict, ignore_attr_types: Optional[List[str]] = None, ignore_oldexistent: bool = False) -> Dict[str, Tuple[str, List[bytes]]]: ignore_attr_types = _list_dict(map(str.lower, (ignore_attr_types or []))) modlist: Dict[str, Tuple[str, List[bytes]]] ...
Build differential modify list for calling LDAPObject.modify()/modify_s() :param old_entry: Dictionary holding the old entry :param new_entry: Dictionary holding what the new entry should be :param ignore_attr_types: List of attribute type names to be ignored completely :param i...
17,868
def get_urlhash(self, url, fmt): with self.open(os.path.basename(url)) as f: return {: fmt(url), : filehash(f, )}
Returns the hash of the file of an internal url
17,869
def app_authorize(self, account=None, flush=True, bailout=False): with self._get_account(account) as account: user = account.get_name() password = account.get_authorization_password() if password is None: password = account.get_password() ...
Like app_authenticate(), but uses the authorization password of the account. For the difference between authentication and authorization please google for AAA. :type account: Account :param account: An account object, like login(). :type flush: bool :param flu...
17,870
def add_months_to_date(months, date): month = date.month new_month = month + months years = 0 while new_month < 1: new_month += 12 years -= 1 while new_month > 12: new_month -= 12 years += 1 year = date.year + years try: return datetime.d...
Add a number of months to a date
17,871
def url_to_filename(url: str, etag: str = None) -> str: url_bytes = url.encode() url_hash = sha256(url_bytes) filename = url_hash.hexdigest() if etag: etag_bytes = etag.encode() etag_hash = sha256(etag_bytes) filename += + etag_hash.hexdigest() return filename
Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to the url's, delimited by a period.
17,872
def deploy(self, driver, location_id=config.DEFAULT_LOCATION_ID, size=config.DEFAULT_SIZE): logger.debug( % (self.name, driver)) args = {: self.name} if hasattr(config, ): args[] = config.SSH_KEY_NAME if hasattr(config, ): args[] = con...
Use driver to deploy node, with optional ability to specify location id and size id. First, obtain location object from driver. Next, get the size. Then, get the image. Finally, deploy node, and return NodeProxy.
17,873
def event_stream(self, filters=None): if filters is None: filters = {} return self._docker.events(decode=True, filters=filters)
:param filters: filters to apply on messages. See docker api. :return: an iterable that contains events from docker. See the docker api for content.
17,874
def compute(): if what == "numpy": y = eval(expr) else: y = ne.evaluate(expr) return len(y)
Compute the polynomial.
17,875
def create_diff_storage(self, target, variant): if not isinstance(target, IMedium): raise TypeError("target can only be an instance of type IMedium") if not isinstance(variant, list): raise TypeError("variant can only be an instance of type list") for a in varian...
Starts creating an empty differencing storage unit based on this medium in the format and at the location defined by the @a target argument. The target medium must be in :py:attr:`MediumState.not_created` state (i.e. must not have an existing storage unit). Upon successful ...
17,876
def get_headers(self, container): uri = "/%s" % utils.get_name(container) resp, resp_body = self.api.method_head(uri) return resp.headers
Return the headers for the specified container.
17,877
def parse_object(lexer: Lexer, is_const: bool) -> ObjectValueNode: start = lexer.token item = cast(Callable[[Lexer], Node], partial(parse_object_field, is_const=is_const)) return ObjectValueNode( fields=any_nodes(lexer, TokenKind.BRACE_L, item, TokenKind.BRACE_R), loc=loc(lexer, start),...
ObjectValue[Const]
17,878
def initialize_socket(self): try: _LOGGER.debug("Trying to open socket.") self._socket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) self._socket.bind((, self._udp_port)) except socket.error as err: ...
initialize the socket
17,879
def ListTimeZones(self): max_length = 0 for timezone_name in pytz.all_timezones: if len(timezone_name) > max_length: max_length = len(timezone_name) utc_date_time = datetime.datetime.utcnow() table_view = views.ViewsFactory.GetTableView( self._views_format_type, column_names...
Lists the timezones.
17,880
def nonNegativeDerivative(requestContext, seriesList, maxValue=None): results = [] for series in seriesList: newValues = [] prev = None for val in series: if None in (prev, val): newValues.append(None) prev = val continue...
Same as the derivative function above, but ignores datapoints that trend down. Useful for counters that increase for a long time, then wrap or reset. (Such as if a network interface is destroyed and recreated by unloading and re-loading a kernel module, common with USB / WiFi cards. Example:: ...
17,881
def shuffle(self, x, random=None): if random is None: random = self.random _int = int for i in reversed(xrange(1, len(x))): j = _int(random() * (i+1)) x[i], x[j] = x[j], x[i]
x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the standard random.random.
17,882
def database_names(self, session=None): warnings.warn("database_names is deprecated. Use list_database_names " "instead.", DeprecationWarning, stacklevel=2) return self.list_database_names(session)
**DEPRECATED**: Get a list of the names of all databases on the connected server. :Parameters: - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. .. versionchanged:: 3.7 Deprecated. Use :meth:`list_database_names` instead. .. ver...
17,883
def db_to_specifier(db_string): local_match = PLAIN_RE.match(db_string) remote_match = URL_RE.match(db_string) if local_match: return + local_match.groupdict()[] elif remote_match: hostname, portnum, database = map(remote_match.groupdict().get, (, , )...
Return the database specifier for a database string. This accepts a database name or URL, and returns a database specifier in the format accepted by ``specifier_to_db``. It is recommended that you consult the documentation for that function for an explanation of the format.
17,884
def unitigs(args): p = OptionParser(unitigs.__doc__) p.add_option("--maxerr", default=2, type="int", help="Maximum error rate") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bestedges, = args G = read_graph(bestedges, maxerr=opts.maxerr, directed=...
%prog unitigs best.edges Reads Celera Assembler's "best.edges" and extract all unitigs.
17,885
def getAccessURL(self, CorpNum, UserID): result = self._httpget(, CorpNum, UserID) return result.url
ํŒ๋นŒ ๋กœ๊ทธ์ธ URL args CorpNum : ํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ UserID : ํšŒ์› ํŒ๋นŒ์•„์ด๋”” return 30์ดˆ ๋ณด์•ˆ ํ† ํฐ์„ ํฌํ•จํ•œ url raise PopbillException
17,886
def compare_packages(rpm_str_a, rpm_str_b, arch_provided=True): logger.debug(, rpm_str_a, rpm_str_b) evr_a = parse_package(rpm_str_a, arch_provided)[] evr_b = parse_package(rpm_str_b, arch_provided)[] return labelCompare(evr_a, evr_b)
Compare two RPM strings to determine which is newer Parses version information out of RPM package strings of the form returned by the ``rpm -q`` command and compares their versions to determine which is newer. Provided strings *do not* require an architecture at the end, although if providing strings w...
17,887
def normalize_pts(pts, ymax, scaler=2): return [(x * scaler, ymax - (y * scaler)) for x, y in pts]
scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left)
17,888
def find(self, name, required): if name == None: raise Exception("Name cannot be null") locator = self._locate(name) if locator == None: if required: raise ReferenceException(None, name) return None return sel...
Finds all matching dependencies by their name. :param name: the dependency name to locate. :param required: true to raise an exception when no dependencies are found. :return: a list of found dependencies
17,889
def create_variable(self, varname, vtype=None): var_types = (, , , ) vname = varname var = None type_from_name = if in varname: type_from_name, vname = varname.split() if type_from_name not in (var_types): ...
Create a tk variable. If the variable was created previously return that instance.
17,890
def subkeys(self, path): for _ in subpaths_for_path_range(path, hardening_chars="'pH"): yield self.subkey_for_path(_)
A generalized form that can return multiple subkeys.
17,891
def __deftype_impls( ctx: ParserContext, form: ISeq ) -> Tuple[List[DefTypeBase], List[Method]]: current_interface_sym: Optional[sym.Symbol] = None current_interface: Optional[DefTypeBase] = None interfaces = [] methods: List[Method] = [] interface_methods: MutableMapping[sym.Symbol, List...
Roll up deftype* declared bases and method implementations.
17,892
def raw_broadcast(self, destination, message, **kwargs): self._broadcast(destination, message, **kwargs)
Broadcast a raw (unmangled) message. This may cause errors if the receiver expects a mangled message. :param destination: Topic name to send to :param message: Either a string or a serializable object to be sent :param **kwargs: Further parameters for the transport layer. For example ...
17,893
def get_metric_names(self, agent_id, re=None, limit=5000): self._api_rate_limit_exceeded(self.get_metric_names) parameters = {: re, : limit} endpoint = "https://api.newrelic.com" uri = "{endpoint}/api/v1/applications/{agent_id}/metrics.xml"\ .fo...
Requires: application ID Optional: Regex to filter metric names, limit of results Returns: A dictionary, key: metric name, value: list of fields available for a given metric Method: Get Restrictions: Rate limit to 1x per minute Errors: 403...
17,894
def numberofnetworks(self): sels1 = selectiontools.Selections() sels2 = selectiontools.Selections() complete = selectiontools.Selection(, self.nodes, self.elements) for node in self.endnodes: sel = complete.copy(node.name)....
The number of distinct networks defined by the|Node| and |Element| objects currently handled by the |HydPy| object.
17,895
def lock(self, name, ttl=None, lock_id=None): return Lock(self, name, ttl, lock_id)
Create a named :py:class:`Lock` instance. The lock implements an API similar to the standard library's ``threading.Lock``, and can also be used as a context manager or decorator. :param str name: The name of the lock. :param int ttl: The time-to-live for the lock in milliseconds ...
17,896
def get(self, request, bot_id, handler_id, id, format=None): return super(UrlParameterDetail, self).get(request, bot_id, handler_id, id, format)
Get url parameter by id --- serializer: AbsParamSerializer responseMessages: - code: 401 message: Not authenticated
17,897
def rule_command_cmdlist_interface_u_interface_fe_leaf_interface_fortygigabitethernet_leaf(self, **kwargs): config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_key = ET.SubElement(rule, "index") index_key.text = kwar...
Auto Generated Code
17,898
def get_remaining_time(program): now = datetime.datetime.now() program_start = program.get() program_end = program.get() if not program_start or not program_end: _LOGGER.error() _LOGGER.debug(, program) return if now > program_end: _LOGGER.error() _LOGGER...
Get the remaining time in seconds of a program that is currently on.
17,899
def urlopen(self, method, url, redirect=True, **kw): "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." u = parse_url(url) if u.scheme == "http": return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.