Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
361,600
def get_descriptor_by_id(self, id, is_master_id=None): route_values = {} if id is not None: route_values[] = self._serialize.url(, id, ) query_parameters = {} if is_master_id is not None: query_parameters[] = self._serialize.query(, is_master_id, ) ...
GetDescriptorById. [Preview API] :param str id: :param bool is_master_id: :rtype: :class:`<str> <azure.devops.v5_0.identity.models.str>`
361,601
def execute_java(classpath, main, jvm_options=None, args=None, executor=None, workunit_factory=None, workunit_name=None, workunit_labels=None, cwd=None, workunit_log_config=None, distribution=None, create_synthetic_jar=True, synthetic_jar_dir=None, stdin=None): r...
Executes the java program defined by the classpath and main. If `workunit_factory` is supplied, does so in the context of a workunit. :param list classpath: the classpath for the java program :param string main: the fully qualified class name of the java program's entry point :param list jvm_options: an optio...
361,602
def _normalize_tags_type(self, tags, device_name=None, metric_name=None): normalized_tags = [] if device_name: self._log_deprecation() normalized_tags.append(.format(ensure_unicode(device_name))) if tags is not None: for tag in tags: ...
Normalize tags contents and type: - append `device_name` as `device:` tag - normalize tags type - doesn't mutate the passed list, returns a new list
361,603
def by_location(self, location, cc=None): header, content = self._http_request(self.BASE_URL, location=location, cc=cc) return json.loads(content)
Perform a Yelp Neighborhood API Search based on a location specifier. Args: location - textual location specifier of form: "address, city, state or zip, optional country" cc - ISO 3166-1 alpha-2 country code. (Optional)
361,604
def generate_mtime_map(opts, path_map): file_map = {} for saltenv, path_list in six.iteritems(path_map): for path in path_list: for directory, _, filenames in salt.utils.path.os_walk(path): for item in filenames: try: file_path...
Generate a dict of filename -> mtime
361,605
def _set_persistent_module(mod): if not mod or mod in mod_list(True) or mod not in \ available(): return set() __salt__[](_LOADER_CONF, _LOAD_MODULE.format(mod)) return set([mod])
Add a module to loader.conf to make it persistent.
361,606
def get_or_add_image_part(self, image_file): image_part = self._package.get_or_add_image_part(image_file) rId = self.relate_to(image_part, RT.IMAGE) return image_part, rId
Return an ``(image_part, rId)`` 2-tuple corresponding to an |ImagePart| object containing the image in *image_file*, and related to this slide with the key *rId*. If either the image part or relationship already exists, they are reused, otherwise they are newly created.
361,607
def _hotellings_time(self): df = self._df R = self._A - np.dot(self._X, self._Bhat) Sigma_Z = np.dot(R.T,R)*(1./df) T_2_list = [] p_value_list = [] for i in np.arange(0,self._Bhat.shape[0]): Bstar = self._Bhat[i,np.arange(0,np....
hotelling's T2 tests for time domain waveforms
361,608
def __vciFormatError(library_instance, function, HRESULT): buf = ctypes.create_string_buffer(constants.VCI_MAX_ERRSTRLEN) ctypes.memset(buf, 0, constants.VCI_MAX_ERRSTRLEN) library_instance.vciFormatError(HRESULT, buf, constants.VCI_MAX_ERRSTRLEN) return "function {} failed ({})".format(function._n...
Format a VCI error and attach failed function and decoded HRESULT :param CLibrary library_instance: Mapped instance of IXXAT vcinpl library :param callable function: Failed function :param HRESULT HRESULT: HRESULT returned by vcinpl call :return: ...
361,609
def _set_module_names_for_sphinx(modules: List, new_name: str): for obj in modules: obj.__module__ = new_name
Trick sphinx into displaying the desired module in these objects' documentation.
361,610
def swipe_bottom(self, steps=10, *args, **selectors): self.device(**selectors).swipe.down(steps=steps)
Swipe the UI object with *selectors* from center to bottom See `Swipe Left` for more details.
361,611
def ignore_import_warnings_for_related_fields(orig_method, self, node): consumer = self._to_consume[0] continue new_things[name] = stmts consumer._atomic = ScopeConsumer(new_things, consumer.consumed, consumer.scope_type) self._to_consume = [consumer] retur...
Replaces the leave_module method on the VariablesChecker class to prevent unused-import warnings which are caused by the ForeignKey and OneToOneField transformations. By replacing the nodes in the AST with their type rather than the django field, imports of the form 'from django.db.models import OneToOn...
361,612
def subs(self, *args): cols = [, , ] out = self.copy() def get_subs_f(*args): def subs_function(x): if hasattr(x, ): x = x.subs(*args) try: x = float(x) except TypeError: ...
Substitute a symbolic expression in ``['x', 'y', 'z']`` This is a wrapper around the substitution mechanism of `sympy <http://docs.sympy.org/latest/tutorial/basic_operations.html>`_. Any symbolic expression in the columns ``['x', 'y', 'z']`` of ``self`` will be substituted with ...
361,613
def get(self, uri): cache_key = self._build_cache_key(uri) value = self._get(cache_key) if value is not None: return self._decode_node(uri, value)
Return node for uri or None if not exists: {uri: x, content: y}
361,614
def job_history(backend): year = widgets.Output(layout=widgets.Layout(display=, align_items=, min_height=)) month = widgets.Output(layout=widgets.Layout(display=, ...
Widget for displaying job history Args: backend (IBMQbackend): The backend. Returns: Tab: A tab widget for history images.
361,615
def _fill_form_exclude_cols(self, exclude_cols, form): for filter_key in exclude_cols: filter_value = self._filters.get_filter_value(filter_key) rel_obj = self.datamodel.get_related_obj(filter_key, filter_value) if hasattr(form, filter_key): field = g...
fill the form with the suppressed cols, generated from exclude_cols
361,616
def setMinimumWidth(self, width): super(XView, self).setMinimumWidth(width) if ( not self.signalsBlocked() ): self.sizeConstraintChanged.emit()
Sets the minimum width value to the inputed width and emits the \ sizeConstraintChanged signal. :param width | <int>
361,617
def get(self, key, default=None): if not isinstance(key, bytes): key = key.encode() return self.b_get_value(key) or default
Returns a list of payloads (as byte objects) for a given key or ``default`` if the key is not found.
361,618
def hours(start, end=None): return iterate.between(start, datetime.timedelta(hours=1), end)
Iterate over the hours between the given datetime_tzs. Args: start: datetime_tz to start from. end: (Optional) Date to end at, if not given the iterator will never terminate. Returns: An iterator which generates datetime_tz objects a hour apart.
361,619
def cvm_unif_fix1(statistic): args = fix1_args / statistic kvs = kv((.25, .75, 1.25), args[:, :, newaxis]) gs, hs = exp(-args) * tensordot(((1, 1, 0), (2, 3, -1)), kvs, axes=(1, 2)) a = dot((7, 16, 7), fix1_csa * gs).sum() / statistic ** 1.5 b = dot((1, 0, 24), fix1_csb * hs).sum() / statistic ...
Approximates the first-term of the small sample count Gotze expansion. After equation 1.10 (with coefficients pulled out as csa / csb).
361,620
def _init_map(self): self.my_osid_object_form._my_map[] = \ self._zone_conditions_metadata[][0] self.my_osid_object_form._my_map[] = \ self._coordinate_conditions_metadata[][0] self.my_osid_object_form._my_map[] = \ self._spatial_unit_conditions_metad...
stub
361,621
def _handle_processing_error(err, errstream, client): errors = sorted(err.events, key=operator.attrgetter("index")) failed = [e.event for e in errors] silent = all(isinstance(e.error, OutOfOrderError) for e in errors) if errstream: _deliver_errored_events(errstream, failed) must_ra...
Handle ProcessingError exceptions.
361,622
def from_product(cls, iterables, sortorder=None, names=None): from pandas.core.arrays.categorical import _factorize_from_iterables from pandas.core.reshape.util import cartesian_product if not is_list_like(iterables): raise TypeError("Input must be a list / sequence of iter...
Make a MultiIndex from the cartesian product of multiple iterables. Parameters ---------- iterables : list / sequence of iterables Each iterable has unique labels for each level of the index. sortorder : int or None Level of sortedness (must be lexicographically ...
361,623
def pretty_template_plot(template, size=(10.5, 7.5), background=False, picks=False, **kwargs): import matplotlib.pyplot as plt fig, axes = plt.subplots(len(template), 1, sharex=True, figsize=size) if len(template) > 1: axes = axes.ravel() if not background: ...
Plot of a single template, possibly within background data. :type template: obspy.core.stream.Stream :param template: Template stream to plot :type size: tuple :param size: tuple of plot size :type background: obspy.core.stream.stream :param background: Stream to plot the template within. :...
361,624
def enrich(self, columns): for column in columns: if column not in self.data.columns: return self.data first_column = list(self.data[columns[0]]) count = 0 append_df = pandas.DataFrame() for cell in first_column: ...
This method appends at the end of the dataframe as many rows as items are found in the list of elemnents in the provided columns. This assumes that the length of the lists for the several specified columns is the same. As an example, for the row A {"C1":"V1", "C2":field1, "C3":f...
361,625
def copy_path_to_clipboard(self): path = self.get_current_path() QtWidgets.QApplication.clipboard().setText(path) debug( % path)
Copies the file path to the clipboard
361,626
def users_forgot_password(self, email, **kwargs): return self.__call_api_post(, email=email, data=kwargs)
Send email to reset your password.
361,627
def _fetch_AlignmentMapper(self, tx_ac, alt_ac, alt_aln_method): return hgvs.alignmentmapper.AlignmentMapper( self.hdp, tx_ac=tx_ac, alt_ac=alt_ac, alt_aln_method=alt_aln_method)
Get a new AlignmentMapper for the given transcript accession (ac), possibly caching the result.
361,628
def tree_to_stream(entries, write): ord_zero = ord() bit_mask = 7 for binsha, mode, name in entries: mode_str = b for i in xrange(6): mode_str = bchr(((mode >> (i * 3)) & bit_mask) + ord_zero) + mode_str if byte_ord(mode_str[0]) == ord...
Write the give list of entries into a stream using its write method :param entries: **sorted** list of tuples with (binsha, mode, name) :param write: write method which takes a data string
361,629
def to_xdr_object(self): selling = self.selling.to_xdr_object() buying = self.buying.to_xdr_object() price = Operation.to_xdr_price(self.price) price = Xdr.types.Price(price[], price[]) amount = Operation.to_xdr_amount(self.amount) manage_offer_op = Xdr.types.M...
Creates an XDR Operation object that represents this :class:`ManageOffer`.
361,630
def chshell(name, shell): * pre_info = info(name) if not pre_info: raise CommandExecutionError( {0}\.format(name) ) if shell == pre_info[]: return True cmd = [, , shell, name] __salt__[](cmd, python_shell=False) return info(name).get() == shell
Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh
361,631
def on_action_begin(self, action, logs={}): for callback in self.callbacks: if callable(getattr(callback, , None)): callback.on_action_begin(action, logs=logs)
Called at beginning of each action for each callback in callbackList
361,632
def _id(self): return (self.__class__, self.number_of_needles, self.needle_positions, self.left_end_needle)
What this object is equal to.
361,633
def url_download(url, topath=None, create_dirs=True): if topath: topath = os.path.expanduser(os.path.expandvars(topath)) if create_dirs and topath: dnm = os.path.dirname(topath) if not os.path.isdir(dnm): os.makedirs(os.path.abspath(dnm), 0o755) if six.PY2: response = urlli...
url_download(url) yields the contents of the given url as a byte-string. url_download(url, topath) downloads the given url to the given path, topath and yields that path on success. The option create_dirs (default: True) may be set to False to prevent the topath directory from being created.
361,634
def _convert_rename(self, fc): old = fc.old_path new = fc.new_path keep_old = self._path_to_be_kept(old) keep_new = self._path_to_be_kept(new) if keep_old and keep_new: fc.old_path = self._adjust_for_new_root(old) fc.new_path = self._adjust_for_ne...
Convert a FileRenameCommand into a new FileCommand. :return: None if the rename is being ignored, otherwise a new FileCommand based on the whether the old and new paths are inside or outside of the interesting locations.
361,635
def save_all(yaml_dicts, filepath): yamldict.dump_all(yaml_dicts, open(filepath, ), default_flow_style=False)
Save *all* YAML settings to the specified file path.
361,636
def _validate_config(self, config): required_keys = [ self.KEY_IDP_CONFIG, self.KEY_ENDPOINTS, ] if not config: raise ValueError("No configuration given") for key in required_keys: try: _val = config[key] ...
Validates some parts of the module config :type config: dict[str, dict[str, Any] | str] :param config: The module config
361,637
def stop(self, timeout=None): with self._lock: if self._thread: self._queue.put_nowait(self._terminator) self._thread.join(timeout=timeout) self._thread = None self._thread_for_pid = None
Stops the task thread. Synchronous!
361,638
def get_organization(self, **kwargs): resp = self._get(self._u(self._ORGANIZATION_ENDPOINT_SUFFIX), **kwargs) resp.raise_for_status() return resp.json()
Get the organization to which the user belongs Returns: dictionary of the response
361,639
def insert(self, index, child, **kwargs): if child: script = self.script(child, **kwargs) if script not in self.children: if index is None: self.children.append(script) else: self.children.insert(index, scri...
add a new script to the container. :param child: a ``string`` representing an absolute path to the script or relative path (does not start with ``http`` or ``/``), in which case the :attr:`Media.media_path` attribute is prepended.
361,640
def get_explore_posts(self) -> Iterator[Post]: data = self.context.get_json(, {}) yield from (Post(self.context, node) for node in self.context.graphql_node_list("df0dcc250c2b18d9fd27c5581ef33c7c", {}, , ...
Get Posts which are worthy of exploring suggested by Instagram. :return: Iterator over Posts of the user's suggested posts.
361,641
def groups(self): return Groups(url="%s/groups" % self.root, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initalize=False)
returns the group object
361,642
def settings_api(): variables = [ "%s = %s" % (var, repr(getattr(settings, var))) for var in sorted(dir(settings)) if (not var.startswith("_") and var.upper() == var and not var.startswith("SEEDER")) ] return PY_HEADER + "\n\n".join(variables)
Virtual ``settings.py`` with values transported from real :mod:`settings.py`, so the Brython frontend may be configured same way as backend. Some of the critical values are intentionally left out.
361,643
def check_file_paths(self, *args): for path in enumerate(args): path = path[1] if path is not None: try: self.check_file_path(path) except OSError as ex: logger.warn(ex) raise ret...
Ensure all arguments provided correspond to a file
361,644
def AddOption(self, descriptor, constant=False): if self.initialized: raise AlreadyInitializedError( "Config was already initialized when defining %s" % descriptor.name) descriptor.section = descriptor.name.split(".")[0] if descriptor.name in self.type_infos: logging.warning("Con...
Registers an option with the configuration system. Args: descriptor: A TypeInfoObject instance describing the option. constant: If this is set, the option is treated as a constant - it can be read at any time (before parsing the configuration) and it's an error to try to override it in ...
361,645
def version_state(name, prefix=False, no_content=False): if env.project_fullname: full_name = .join([env.project_fullname,name]) else: full_name = name current_state = False state = State(full_name) state_path = % full_name if not prefix and not no_content and exists(state_path): co...
If the server state exists return parsed json as a python object or True prefix=True returns True if any files exist with ls [prefix]*
361,646
def libvlc_video_set_aspect_ratio(p_mi, psz_aspect): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,), (1,),), None, None, MediaPlayer, ctypes.c_char_p) return f(p_mi, psz_aspect)
Set new video aspect ratio. @param p_mi: the media player. @param psz_aspect: new video aspect-ratio or NULL to reset to default @note Invalid aspect ratios are ignored.
361,647
def split(self, into = "edges", loc = None, at = "labels", sort_index = True): if type(loc) == type(None): elements = self.elements else: elements = self.elements.loc[loc] out = [] for etype, group in elements.groupby([("type", "argiope", "")]): try: output_...
Returns the decomposition of the elements. Inputs: * into: must be in ['edges', 'faces', 'simplices', 'angles'] * loc: None or labels of the chosen elements. * at: must be in ['labels', 'coords']
361,648
def _delete_deployment(self, deployment_name): api_response = self.kube_client.delete_namespaced_deployment( name=deployment_name, namespace=self.namespace, body=client.V1DeleteOptions( propagation_policy=, grace_period_seconds=5)) ...
Delete deployment
361,649
def color(self) -> str: colors = self._data[] return self.random.choice(colors)
Get a random name of color. :return: Color name. :Example: Red.
361,650
def guest_create_disks(self, userid, disk_list): if disk_list == [] or disk_list is None: LOG.debug("No disk specified when calling guest_create_disks, " "nothing happened") return action = "create disks for guest " % (str(disk_list),...
Add disks to an existing guest vm. :param userid: (str) the userid of the vm to be created :param disk_list: (list) a list of disks info for the guest. It has one dictionary that contain some of the below keys for each disk, the root disk should be the first element in the...
361,651
def is_game_over(self, *, claim_draw: bool = False) -> bool: if self.is_seventyfive_moves(): return True if self.is_insufficient_material(): return True if not any(self.generate_legal_moves()): return True ...
Checks if the game is over due to :func:`checkmate <chess.Board.is_checkmate()>`, :func:`stalemate <chess.Board.is_stalemate()>`, :func:`insufficient material <chess.Board.is_insufficient_material()>`, the :func:`seventyfive-move rule <chess.Board.is_seventyfive_moves()>`, :func:...
361,652
def load_krebsregister(block=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], missing_values=None, shuffle=True): for i in range(1, 11): filepath = os.path.join(os.path.dirname(__file__), , .format(i)) if not os.path.exists(filepath): _...
Load the Krebsregister dataset. This dataset of comparison patterns was obtained in a epidemiological cancer study in Germany. The comparison patterns were created by the Institute for Medical Biostatistics, Epidemiology and Informatics (IMBEI) and the University Medical Center of Johannes Gutenber...
361,653
def measurementReport(): a = TpPd(pd=0x6) b = MessageType(mesType=0x15) c = MeasurementResults() packet = a / b / c return packet
MEASUREMENT REPORT Section 9.1.21
361,654
def write_run_output(run, **kwargs): write_dead = kwargs.pop(, True) write_stats = kwargs.pop(, True) posteriors = kwargs.pop(, False) equals = kwargs.pop(, False) stats_means_errs = kwargs.pop(, True) fmt = kwargs.pop(, ) n_simulate = kwargs.pop(, 100) if kwargs: raise Type...
Writes PolyChord output files corresponding to the input nested sampling run. The file root is .. code-block:: python root = os.path.join(run['output']['base_dir'], run['output']['file_root']) Output files which can be made with this function (see the PolyChord doc...
361,655
def _patch_dict(diff, base): for k, v in diff.items(): if isinstance(v, dict): base[k] = _patch_dict(v, base.get(k, {})) elif not v: base.pop(k, None) else: base[k] = v return base
Patch a dictionary, substituting in changed items from the nested diff.
361,656
def parse(cls, args): try: (options, args) = cls.optparser.parse_args(args) if options.mode not in ["1", "2"]: raise ParseError("mode must be either or ", cls.optparser.format_help()) if (options.dbtap_id is None) o...
Parse command line arguments to construct a dictionary of command parameters that can be used to create a command Args: `args`: sequence of arguments Returns: Dictionary that can be used in create method Raises: ParseError: when the arguments are no...
361,657
def saves(self, store_password): if self.store_type == : keystore = MAGIC_NUMBER_JKS elif self.store_type == : raise NotImplementedError("Saving of JCEKS keystores is not implemented") else: raise UnsupportedKeystoreTypeException("Only JKS and JCEKS ...
Saves the keystore so that it can be read by other applications. If any of the private keys are unencrypted, they will be encrypted with the same password as the keystore. :param str store_password: Password for the created keystore (and for any unencrypted keys) :returns: A...
361,658
def _MakeMethodDescriptor(self, method_proto, service_name, package, scope, index): full_name = .join((service_name, method_proto.name)) input_type = self._GetTypeFromScope( package, method_proto.input_type, scope) output_type = self._GetTypeFromScope( packag...
Creates a method descriptor from a MethodDescriptorProto. Args: method_proto: The proto describing the method. service_name: The name of the containing service. package: Optional package name to look up for types. scope: Scope containing available types. index: Index of the method in ...
361,659
def starts_new_line(item: str) -> bool: if item in TAF_NEWLINE: return True for start in TAF_NEWLINE_STARTSWITH: if item.startswith(start): return True return False
Returns True if the given element should start a new report line
361,660
def _temporary_filenames(total): temp_files = [_get_temporary_filename() for i in range(total)] yield temp_files for temp_file in temp_files: try: os.remove(temp_file) except OSError: pass
Context manager to create temporary files and remove them after use.
361,661
def _get_specification(self, specification): result = six.moves.urllib.parse.urlparse(specification) if result.scheme in [, ]: response = requests.get(specification) spec_json = response.json() else: with open(specification...
Read the specification provided. It can either be a url or a file location.
361,662
def format_page(self, page, link_resolver, output): debug( % page.link.ref, ) if output: actual_output = os.path.join(output, ) if not os.path.exists(actual_output): os.makedirs(actual_output) else: ...
Called by `project.Project.format_page`, to leave full control to extensions over the formatting of the pages they are responsible of. Args: page: tree.Page, the page to format. link_resolver: links.LinkResolver, object responsible for resolving links pot...
361,663
def save_nd_to_pickle(nd, path=, filename=None): abs_path = os.path.abspath(path) if len(nd._mv_grid_districts) > 1: name_extension = .format( number=nd._mv_grid_districts[0].id_db, number2=nd._mv_grid_districts[-1].id_db) else: name_extension = .format(number=...
Use pickle to save the whole nd-object to disc The network instance is entirely pickled to a file. Parameters ---------- nd : NetworkDing0 Ding0 grid container object path : str Absolute or relative path where pickle should be saved. Default is '' which means pickle is save...
361,664
def apply_queryset_rules(self, qs): clauses = { : [], : []} for rule in self.drip_model.queryset_rules.all(): clause = clauses.get(rule.method_type, clauses[]) kwargs = rule.filter_kwargs(qs, now=self.now) clause.append(Q(**kwargs))...
First collect all filter/exclude kwargs and apply any annotations. Then apply all filters at once, and all excludes at once.
361,665
def parse_list(cls, api, json_list): results = [] for json_obj in json_list: if json_obj: obj = cls.parse(api, json_obj) results.append(obj) return results
Parse a list of JSON objects into a result set of model instances.
361,666
def call (self, to, **options): self._steps.append(Call (to, **options).obj)
Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API to tell Tropo to launch your code. Arguments: to is a String. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/call
361,667
def _dump(self, tree): schema = [] if tree.tables: for table in tree.tables: desc = self.describe(table, refresh=True, require=True) schema.append(desc.schema) else: for table in self.describe_all(): schema.append(t...
Run a DUMP statement
361,668
def add_or_update(uid, post_data): cur_rec = MPost.get_by_uid(uid) if cur_rec: MPost.update(uid, post_data) else: MPost.create_post(uid, post_data)
Add or update the post.
361,669
def block_windows(self, res=None): if res is None: res = max(self._res_indices.keys()) self._windows_res = res a_file_index_given_res = self._res_indices[res][0] with rasterio.open(self._layer_files[a_file_index_given_res]) as src: wins_of_first_dst_re...
Load windows for chunks-wise processing from raster internal tiling (first raster of given resolution). Arguments: res {numeric} -- Resolution determining the raster (1st of resolution group) from which to take the tiling.
361,670
def text_to_data(self, text, elt, ps): if text is None: return None m = Duration.lex_pattern.match(text) if m is None: raise EvaluateException(, ps.Backtrace(elt)) d = m.groupdict() if d[] and (d[] is None and d[] is None and d[] is None): ...
convert text into typecode specific data.
361,671
def init(self, settings_file="zappa_settings.json"): if os.path.isfile(settings_file): raise ClickException("This project already has a " + click.style("{0!s} file".format(settings_file), fg="red", bold=True) + "!") click.echo(click.style(u, fg=, bold=True)) ...
Initialize a new Zappa project by creating a new zappa_settings.json in a guided process. This should probably be broken up into few separate componants once it's stable. Testing these inputs requires monkeypatching with mock, which isn't pretty.
361,672
def get_backdoor(self, name, version=): params = {} params[] = 1 params[] = name params[] = name r = requests.get(.format(self.url), params=params, verify=self.verify, proxies=self.proxies) ...
Searches for the backdoor based on name and version. Args: name: The name of the backdoor. This can be an alias. version: The version. Returns: Returns a JSON object contain one or more backdoor results or None if not found.
361,673
def parse_argv(self, argv=None): arguments = vars(self.create_argument_parser().parse_args(argv)) seed = None if self.requires_seed: seed_filepath = arguments.pop() seed = ( self.seed_from_filepath(seed_filepath) if seed...
Parses arguments for the command. :param argv: Arguments to pass to the argument parser. If ``None``, defaults to ``sys.argv[1:]``.
361,674
def display_view(self): self.idx_start.setText(str(self.parent.value())) self.idx_length.setText(str(self.parent.value())) self.idx_scaling.setText(str(self.parent.value())) self.idx_distance.setText(str(self.parent.value()))
Update information about the size of the traces.
361,675
def insert_media(self, url): try: super(VirtualMedia, self).insert_media(url, write_protected=True) except sushy_exceptions.SushyError: target_uri = self._get_action_element().target_uri data = {: url} self._conn.post(target_uri, data=data)
Inserts Virtual Media to the device :param url: URL to image. :raises: SushyError, on an error from iLO.
361,676
def prettify(elem): from xml.etree import ElementTree from xml.dom import minidom rough_string = ElementTree.tostring(elem, ) reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ")
Return a pretty-printed XML string for the Element.
361,677
def write_grid_tpl(self,name,tpl_file,zn_array): parnme,x,y = [],[],[] with open(os.path.join(self.m.model_ws,tpl_file),) as f: f.write("ptf ~\n") for i in range(self.m.nrow): for j in range(self.m.ncol): if zn_array[i,j] < 1: ...
write a template file a for grid-based multiplier parameters Parameters ---------- name : str the base parameter name tpl_file : str the template file to write zn_array : numpy.ndarray an array used to skip inactive cells Returns ...
361,678
def _robust_column_name(base_name, column_names): robust_name = base_name i = 1 while robust_name in column_names: robust_name = base_name + .format(i) i += 1 return robust_name
Generate a new column name that is guaranteed not to conflict with an existing set of column names. Parameters ---------- base_name : str The base of the new column name. Usually this does not conflict with the existing column names, in which case this function simply returns `b...
361,679
def login(self, principal, loginProperties): self.send_login(principal, loginProperties) return self.recv_login()
Parameters: - principal - loginProperties
361,680
def get_form(self, key, form_class=None): if form_class is None: form_class = self.get_form_class(key) return form_class(**self.get_form_kwargs(key))
Returns an instance of the form to be used in this view.
361,681
def random_split(df, first_portion=.1): mask = np.random.binomial(1, first_portion, size=len(df)).astype(bool) return df[mask].copy(), df[~mask].copy()
Randomly sample Dataframe rows. Typically for testset/training set cross-valication random_split(pd.DataFrame())
361,682
def CLI(ctx, config, list_lookups): loglevel = verbosity = getattr(logging, loglevel.upper(), ) ctx.obj = { : verbosity, : None, : {: {}}, } logfmt = logging.basicConfig(format=logfmt, level=verbosity) debug(.format(os.getcwd())) with open(CONFIG_...
Lookup basic phone number information or send SMS messages
361,683
def connect(self): self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.settimeout(self._connect_timeout) SocketError.wrap(self._socket.connect, (self.host, self.port)) self._socket.settimeout(None) self._socket_file = self._socket.makefile()
Connect to beanstalkd server.
361,684
def strftime_string(C, msformat): "convert Word date/time picture (msformat) into a strftime format string" s = msformat s = re.sub(r"%", "%%", s) s = re.sub(r"(?<!%)\b(y(?:yyy)?)\b", "%Y", s) s = re.sub(r"(?<!%)\b(yy)\b", "%y", s) s = re.sub(r"...
convert Word date/time picture (msformat) into a strftime format string
361,685
def this_year(self): start_date, end_date = get_date_range_this_year() return Announcement.objects.filter(added__gte=start_date, added__lte=end_date)
Get AnnouncementRequests from this school year only.
361,686
def _add_model(self, model): name = model._name existing = self._models.get(name, None) if not existing: self._models[name] = model elif model.__name__ != existing.__name__ or model._creation_source != existing._creation_source: raise ImplementationError(...
Save this model as one existing on this database, to deny many models with same namespace and name. If the model already exists, check if it is the same. It can happen if the module is imported twice in different ways. If it's a new model or an existing and valid one, return the model in...
361,687
def metadata(sceneid, pmin=2, pmax=98, **kwargs): scene_params = _cbers_parse_scene_id(sceneid) cbers_address = "{}/{}".format(CBERS_BUCKET, scene_params["key"]) bands = scene_params["bands"] ref_band = scene_params["reference_band"] info = {"sceneid": sceneid} addresses = [ "{}/{...
Return band bounds and statistics. Attributes ---------- sceneid : str CBERS sceneid. pmin : int, optional, (default: 2) Histogram minimum cut. pmax : int, optional, (default: 98) Histogram maximum cut. kwargs : optional These are passed to 'rio_tiler.utils.raste...
361,688
def reset_input_generators(self, seed): seed_generator = SeedGenerator().reset(seed=seed) for gen in self.input_generators: gen.reset(next(seed_generator)) try: gen.reset_input_generators(next(seed_generator)) ...
Helper method which explicitly resets all input generators to the derived generator. This should only ever be called for testing or debugging.
361,689
def print_tf_op(tf_op, indent="| ", max_depth=-1, depth=0): offset = depth * indent line = "tf op: %s (%s)" % (tf_op.name, tf_op.type) print(offset + line) if max_depth < 0 or max_depth > depth: for tf_tensor in tf_op.inputs: print_tf_tensor(tf_tensor, indent=indent, max_dep...
print_tf_op(tf_tensor, indent=" ", max_depth=-1) Prints the dependency graph of a tensorflow operation *tf_op*, where each new level is indented by *indent*. When *max_depth* is positive, the graph is truncated at that depth, where each tensor and each op count as a level.
361,690
def FromDict(cls, obj): timestamp = obj.get() if timestamp is not None: import dateutil.parser timestamp = dateutil.parser.parse(timestamp) return IOTileEvent(obj.get(), obj.get(), obj.get(), obj.get(), reading_id=obj.get(), reading_t...
Create an IOTileEvent from the result of a previous call to asdict(). Args: obj (dict): A dictionary produced by a call to IOTileEvent.asdict() Returns: IOTileEvent: The converted IOTileEvent object.
361,691
def add_block_parser(subparsers, parent_parser): parser = subparsers.add_parser( , description= , help=) grand_parsers = parser.add_subparsers( title=, dest=) grand_parsers.required = True description = ( ) list_parse...
Adds arguments parsers for the block list and block show commands Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object
361,692
def get_node_mapping(H): node_set = H.get_node_set() nodes_to_indices, indices_to_nodes = {}, {} node_index = 0 for node in node_set: nodes_to_indices.update({node: node_index}) indices_to_nodes.update({node_index: node}) node_index += 1 return indices_to_nodes, nodes_...
Generates mappings between the set of nodes and integer indices (where every node corresponds to exactly 1 integer index). :param H: the hypergraph to find the node mapping on. :returns: dict -- for each integer index, maps the index to the node. dict -- for each node, maps the node to the in...
361,693
def add_units(self, units, factor, latexrepr=None): if units in self._units: raise ValueError( % units) if factor == 1: raise ValueError() if latexrepr is None: latexrepr = units self._units[units] = factor self._latexrepr[units] = la...
Add new possible units. :arg units: units :type units: :class:`str` :arg factor: multiplication factor to convert new units into base units :type factor: :class:`float` :arg latexrepr: LaTeX representation of units (if ``None``, use *units) :ty...
361,694
def draw_label(self, layout_info, ax): label_info = layout_info[list(self.vars)] label_info._meta = {: } label_info = self.labeller(label_info) self.draw_strip_text(label_info, , ax)
Draw facet label onto the axes. This function will only draw labels if they are needed. Parameters ---------- layout_info : dict-like facet information ax : axes Axes to label
361,695
def buy_margin(self): return sum(position.buy_margin for position in six.itervalues(self._positions))
[float] 买方向保证金
361,696
def configure(level=logging.WARNING, handler=None, formatter=None): if formatter is None: formatter = LogrFormatter() if handler is None: handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(level) Logr.handler = ha...
Configure Logr @param handler: Logger message handler @type handler: logging.Handler or None @param formatter: Logger message Formatter @type formatter: logging.Formatter or None
361,697
def collect(self): if not psutil: self.log.error() self.log.error() return None for process in psutil.process_iter(): self.collect_process_info(process) for pg_name, counters in self.processes_info.iteritems(): if co...
Collects resources usage of each process defined under the `process` subsection of the config file
361,698
def _serie_format(self, serie, value): kwargs = {: self, : serie, : None} formatter = (serie.formatter or self.formatter or self._value_format) kwargs = filter_kwargs(formatter, kwargs) return formatter(value, **kwargs)
Format an independent value for the serie
361,699
def _order_as_range(order): order = order.split() order = [int(o) for o in order] if len(order) > 1: order = range(order[0], (order[-1] + 1)) return order
Convert a hyphenated string representing order for derivative or exponential terms into a range object that can be passed as input to the appropriate expansion function.