Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
383,100
def _process_counter_example(self, mma, w_string): diff = len(w_string) same = 0 membership_answer = self._membership_query(w_string) while True: i = (same + diff) / 2 access_string = self._run_in_hypothesis(mma, w_string, i) if membership_ans...
Process a counterexample in the Rivest-Schapire way. Args: mma (DFA): The hypothesis automaton w_string (str): The examined string to be consumed Returns: None
383,101
def _set_options_headers(self, methods): request = self.request response = request.response response.headers[] = .join(sorted(methods)) if in request.headers: response.headers[] = \ .join(sorted(methods)) if in request.headers: ...
Set proper headers. Sets following headers: Allow Access-Control-Allow-Methods Access-Control-Allow-Headers Arguments: :methods: Sequence of HTTP method names that are value for requested URI
383,102
def observed_data_to_xarray(self): data = self.observed_data if not isinstance(data, dict): raise TypeError("DictConverter.observed_data is not a dictionary") if self.dims is None: dims = {} else: dims = self.dims observed_data = dict(...
Convert observed_data to xarray.
383,103
def locale(self) -> tornado.locale.Locale: if not hasattr(self, "_locale"): loc = self.get_user_locale() if loc is not None: self._locale = loc else: self._locale = self.get_browser_locale() assert self._locale ...
The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Add...
383,104
def _power_mismatch_dc(self, buses, generators, B, Pbusinj, base_mva): nb, ng = len(buses), len(generators) gen_bus = array([g.bus._i for g in generators]) neg_Cg = csr_matrix((-ones(ng), (gen_bus, range(ng))), (nb, ng)) Amis = hstack([B, neg_Cg], format="csr") ...
Returns the power mismatch constraint (B*Va + Pg = Pd).
383,105
def parse_params(self, n_samples=None, dx_min=-0.1, dx_max=0.1, n_dxs=2, dy_min=-0.1, dy_max=0.1, n_dys=2, angle_min=-30, angle_max=30, ...
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. :param n_samples: (optional) The number of transformations sampled to construct the attack. Set it to None to run full grid attack. :param dx_min: (optional flo...
383,106
def p_text(self, text): item = text[1] text[0] = item if item[0] != "\n" else u"" if len(text) > 2: text[0] += "\n"
text : TEXT PARBREAK | TEXT | PARBREAK
383,107
def participant_ids(self): return [user.UserID(chat_id=id_.chat_id, gaia_id=id_.gaia_id) for id_ in self._event.membership_change.participant_ids]
:class:`~hangups.user.UserID` of users involved (:class:`list`).
383,108
def get_log_entry_mdata(): return { : { : { : , : str(DEFAULT_LANGUAGE_TYPE), : str(DEFAULT_SCRIPT_TYPE), : str(DEFAULT_FORMAT_TYPE), }, : { : , : str(DEFAULT_LANGUAGE_TYP...
Return default mdata map for LogEntry
383,109
def center (self): Cx = 0.0 Cy = 0.0 denom = 6.0 * self.area() for segment in self.segments(): x = (segment.p.x + segment.q.x) y = (segment.p.y + segment.q.y) xy = (segment.p.x * segment.q.y) - (segment.q.x * segment.p.y) Cx += (x * xy) Cy += (y * xy) ...
center() -> (x, y) Returns the center (of mass) point of this Polygon. See http://en.wikipedia.org/wiki/Polygon Examples: >>> p = Polygon() >>> p.vertices = [ Point(3, 8), Point(6, 4), Point(0, 3) ] >>> p.center() Point(2.89285714286, 4.82142857143)
383,110
def _get_managed_files(self): if self.grains_core.os_data().get() == : return self.__get_managed_files_dpkg() elif self.grains_core.os_data().get() in [, ]: return self.__get_managed_files_rpm() return list(), list(), list()
Build a in-memory data of all managed files.
383,111
def consume_texture_coordinates(self): while True: yield ( float(self.values[1]), float(self.values[2]), ) try: self.next_line() except StopIteration: break if...
Consume all consecutive texture coordinates
383,112
def update_last_wm_layers(self, service_id, num_layers=10): from hypermap.aggregator.models import Service LOGGER.debug( % (num_layers, num_layers) ) service = Service.objects.get(id=service_id) if service.type == : from hypermap.aggregator.models impo...
Update and index the last added and deleted layers (num_layers) in WorldMap service.
383,113
def rmon_alarm_entry_alarm_rising_threshold(self, **kwargs): config = ET.Element("config") rmon = ET.SubElement(config, "rmon", xmlns="urn:brocade.com:mgmt:brocade-rmon") alarm_entry = ET.SubElement(rmon, "alarm-entry") alarm_index_key = ET.SubElement(alarm_entry, "alarm-index")...
Auto Generated Code
383,114
def stringClade(taxrefs, name, at): string = [] for ref in taxrefs: d = float(at-ref.level) ident = re.sub("\s", "_", ref.ident) string.append(.format(ident, d)) string = .join(string) string = .format(string, name) return string
Return a Newick string from a list of TaxRefs
383,115
def recovery(self, using=None, **kwargs): return self._get_connection(using).indices.recovery(index=self._name, **kwargs)
The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.recovery`` unchanged.
383,116
def getObjectByPid(self, pid): self._check_initialized() opid = rdflib.term.Literal(pid) res = [o for o in self.subjects(predicate=DCTERMS.identifier, object=opid)] return res[0]
Args: pid : str Returns: str : URIRef of the entry identified by ``pid``.
383,117
def vm_snapshot_create(vm_name, kwargs=None, call=None): if call != : raise SaltCloudSystemExit( ) if kwargs is None: kwargs = {} snapshot_name = kwargs.get(, None) if snapshot_name is None: raise SaltCloudSystemExit( snapshot_name\ ...
Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create...
383,118
def port(self, value=None): if value is not None: return URL._mutate(self, port=value) return self._tuple.port
Return or set the port :param string value: the new port to use :returns: string or new :class:`URL` instance
383,119
def check_is_spam(content, content_object, request, backends=None): if backends is None: backends = SPAM_CHECKER_BACKENDS for backend_path in backends: spam_checker = get_spam_checker(backend_path) if spam_checker is not None: is_spam = spam_checker(co...
Return True if the content is a spam, else False.
383,120
def module_ids(self, rev=False): shutit_global.shutit_global_object.yield_to_draw() ids = sorted(list(self.shutit_map.keys()),key=lambda module_id: self.shutit_map[module_id].run_order) if rev: return list(reversed(ids)) return ids
Gets a list of module ids guaranteed to be sorted by run_order, ignoring conn modules (run order < 0).
383,121
def create_environment(component_config): ret = os.environ.copy() for env in component_config.get_list("dp.env_list"): real_env = env.upper() value = os.environ.get(real_env) value = _prepend_env(component_config, env, value) value = _append_env(component_config, env, value)...
Create a modified environment. Arguments component_config - The configuration for a component.
383,122
def run(self, endpoint: str, loop: AbstractEventLoop = None): if not loop: loop = asyncio.get_event_loop() try: loop.run_until_complete(self.run_async(endpoint)) except KeyboardInterrupt: self._shutdown()
Run server main task. :param endpoint: Socket endpoint to listen to, e.g. "tcp://*:1234" :param loop: Event loop to run server in (alternatively just use run_async method)
383,123
def sorted_enums(self) -> List[Tuple[str, int]]: return sorted(self.enum.items(), key=lambda x: x[1])
Return list of enum items sorted by value.
383,124
def attribute_path(self, attribute, missing=None, visitor=None): _parameters = {"node": self, "attribute": attribute} if missing is not None: _parameters["missing"] = missing if visitor is not None: _parameters["visitor"] = visitor return self.__class__.o...
Generates a list of values of the `attribute` of all ancestors of this node (as well as the node itself). If a value is ``None``, then the optional value of `missing` is used (by default ``None``). By default, the ``getattr(node, attribute, None) or missing`` mechanism i...
383,125
def create_comment(self, access_token, video_id, content, reply_id=None, captcha_key=None, captcha_text=None): url = data = { : self.client_id, : access_token, : video_id, : content, : reply_id, : ca...
doc: http://open.youku.com/docs/doc?id=41
383,126
def elcm_profile_set(irmc_info, input_data): if isinstance(input_data, dict): data = jsonutils.dumps(input_data) else: data = input_data _irmc_info = dict(irmc_info) _irmc_info[] = PROFILE_SET_TIMEOUT content_type = if input_data[].get(): content_ty...
send an eLCM request to set param values To apply param values, a new session is spawned with status 'running'. When values are applied or error, the session ends. :param irmc_info: node info :param input_data: param values to apply, eg. { 'Server': { 'SystemCon...
383,127
def open_buffer(self, location=None, show_in_current_window=False): eb = self._get_or_create_editor_buffer(location) if show_in_current_window: self.show_editor_buffer(eb)
Open/create a file, load it, and show it in a new buffer.
383,128
def to_api_repr(self): resource = {self.entity_type: self.entity_id} if self.role is not None: resource["role"] = self.role return resource
Construct the API resource representation of this access entry Returns: Dict[str, object]: Access entry represented as an API resource
383,129
def copy_and_run(config, src_dir): job = fake_fetch_job(config, src_dir) if job: job._run_validate() return True else: return False
Local-only operation of the executor. Intended for validation script developers, and the test suite. Please not that this function only works correctly if the validator has one of the following names: - validator.py - validator.zip Returns True when a job was prepared and executed....
383,130
def maxlike(self,nseeds=50): m0,age0,feh0 = self.ic.random_points(nseeds) d0 = 10**(rand.uniform(0,np.log10(self.max_distance),size=nseeds)) AV0 = rand.uniform(0,self.maxAV,size=nseeds) costs = np.zeros(nseeds) if self.fit_for_distance: pfits = np...
Returns the best-fit parameters, choosing the best of multiple starting guesses :param nseeds: (optional) Number of starting guesses, uniformly distributed throughout allowed ranges. Default=50. :return: list of best-fit parameters: ``[m,age,feh,[distance,A_V]]``. ...
383,131
def get_repositories(self, digests): if self.workflow.push_conf.pulp_registries: registries = self.workflow.push_conf.pulp_registries else: registries = self.workflow.push_conf.all_registries output_images = [] for registry in r...
Build the repositories metadata :param digests: dict, image -> digests
383,132
def read_handshake(self): msg = self.read_message() pid_dir, _conf, _context = msg["pidDir"], msg["conf"], msg["context"] open(join(pid_dir, str(self.pid)), "w").close() self.send_message({"pid": self.pid}) return _conf, _context
Read and process an initial handshake message from Storm.
383,133
def _login(self, max_tries=2): if not self.current_url.startswith(_KindleCloudReaderBrowser._SIGNIN_URL): raise BrowserError( % (self.current_url, _KindleCloudReaderBrowser._SIGNIN_URL)) email_field_loaded = lambda br: br.find_elements_by_id() self._wait().until(email_field...
Logs in to Kindle Cloud Reader. Args: max_tries: The maximum number of login attempts that will be made. Raises: BrowserError: If method called when browser not at a signin URL. LoginError: If login unsuccessful after `max_tries` attempts.
383,134
def sort_topologically(dag): dag = copy.deepcopy(dag) sorted_nodes = [] independent_nodes = deque(get_independent_nodes(dag)) while independent_nodes: node = independent_nodes.popleft() sorted_nodes.append(node) downstream_nodes = dag[node] while downstream_...
Sort the dag breath first topologically. Only the nodes inside the dag are returned, i.e. the nodes that are also keys. Returns: a topological ordering of the DAG. Raises: an error if this is not possible (graph is not valid).
383,135
def connect(self): future = concurrent.Future() if self.connected: raise exceptions.ConnectError() LOGGER.debug(, self.name) self.io_loop.add_future( self._client.connect(self.host, self.port), lambda f: self._on_connected(f, future)) ...
Connect to the Redis server if necessary. :rtype: :class:`~tornado.concurrent.Future` :raises: :class:`~tredis.exceptions.ConnectError` :class:`~tredis.exceptinos.RedisError`
383,136
def _read_credential_file(self, cfg): self.username = cfg.get("keystone", "username") self.password = cfg.get("keystone", "password", raw=True) self.tenant_id = cfg.get("keystone", "tenant_id")
Implements the default (keystone) behavior.
383,137
def get_readwrite_instance(cls, working_dir, restore=False, restore_block_height=None): log.warning("!!! Getting raw read/write DB instance !!!") import virtualchain_hooks db_path = virtualchain.get_db_filename(virtualchain_hooks, working_dir) db = BlockstackDB(db_path, DISPOSI...
Get a read/write instance to the db, without the singleton check. Used for low-level operations like db restore. Not used in the steady state behavior of the system.
383,138
def purge_old_files(date_time, directory_path, custom_prefix="backup"): for file_name in listdir(directory_path): try: file_date_time = get_backup_file_time_tag(file_name, custom_prefix=custom_prefix) except ValueError as e: if "does not match format" in e.message:...
Takes a datetime object and a directory path, runs through files in the directory and deletes those tagged with a date from before the provided datetime. If your backups have a custom_prefix that is not the default ("backup"), provide it with the "custom_prefix" kwarg.
383,139
def index(config): client = Client() client.prepare_connection() group_api = API(client) print(group_api.index())
Display group info in raw format.
383,140
def afterqc_general_stats_table(self): headers = OrderedDict() headers[] = { : , : , : 100, : 0, : , : , } headers[] = { : .format(config.read_count_prefix), : .format(config.read_co...
Take the parsed stats from the Afterqc report and add it to the General Statistics table at the top of the report
383,141
def _set_buttons(self, chat, bot): if isinstance(self.reply_markup, ( types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)): self._buttons = [[ MessageButton(self._client, button, chat, bot, self.id) for button in row.buttons ] for ...
Helper methods to set the buttons given the input sender and chat.
383,142
def get_place_tags(index_page, domain): ip_address = get_ip_address(domain) dom = dhtmlparser.parseString(index_page) place_tags = [ get_html_geo_place_tags(dom), get_whois_tags(ip_address), ] return sum(place_tags, [])
Return list of `place` tags parsed from `meta` and `whois`. Args: index_page (str): HTML content of the page you wisht to analyze. domain (str): Domain of the web, without ``http://`` or other parts. Returns: list: List of :class:`.SourceString` objects.
383,143
def create_resource(output_model, rtype, unique, links, existing_ids=None, id_helper=None): if isinstance(id_helper, str): idg = idgen(id_helper) elif isinstance(id_helper, GeneratorType): idg = id_helper elif id_helper is None: idg = default_idgen(None) else: ...
General-purpose routine to create a new resource in the output model, based on data provided output_model - Versa connection to model to be updated rtype - Type IRI for the new resource, set with Versa type unique - list of key/value pairs for determining a unique hash for the new res...
383,144
def dec2dms(dec): DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. dec = float(dec) sign = np.copysign(1.0,dec) fdeg = np.abs(dec) deg = int(fdeg) fminute = (fdeg - deg)*MINUTE minute = int(fminute) second = (fminute - minute)*MINUTE deg = int(deg * ...
ADW: This should really be replaced by astropy
383,145
def load_params_from_file(self, fname: str): utils.check_condition(os.path.exists(fname), "No model parameter file found under %s. " "This is either not a model directory or the first training " "c...
Loads and sets model parameters from file. :param fname: Path to load parameters from.
383,146
def __del_running_bp(self, tid, bp): "Auxiliary method." self.__runningBP[tid].remove(bp) if not self.__runningBP[tid]: del self.__runningBP[tid]
Auxiliary method.
383,147
def to_det_oid(self, det_id_or_det_oid): try: int(det_id_or_det_oid) except ValueError: return det_id_or_det_oid else: return self.get_det_oid(det_id_or_det_oid)
Convert det OID or ID to det OID
383,148
def install_sql(self, site=None, database=, apps=None, stop_on_error=0, fn=None): stop_on_error = int(stop_on_error) site = site or ALL name = database r = self.local_renderer paths = glob.glob(r.format(r.env.install_sql_path_template)) apps = [_ fo...
Installs all custom SQL.
383,149
def updateTable(self, networkId, tableType, body, class_, verbose=None): response=api(url=self.___url++str(networkId)++str(tableType)+, method="PUT", body=body, verbose=verbose) return response
Updates the table specified by the `tableType` and `networkId` parameters. New columns will be created if they do not exist in the target table. Current limitations: * Numbers are handled as Double * List column is not supported in this version :param networkId: SUID containin...
383,150
def _check_endings(self): if self.slug.startswith("/") and self.slug.endswith("/"): raise InvalidSlugError( _("Invalid slug. Did you mean {}, without the leading and trailing slashes?".format(self.slug.strip("/")))) elif self.slug.startswith("/"): raise I...
Check begin/end of slug, raises Error if malformed.
383,151
def _default_verify_function(instance, answer, result_host, atol, verbose): if len(instance.arguments) != len(answer): raise TypeError("The length of argument list and provided results do not match.") for i, arg in enumerate(instance.arguments): if answer[i] is not None: ...
default verify function based on numpy.allclose
383,152
def Drop(self: dict, n): n = len(self) - n if n <= 0: yield from self.items() else: for i, e in enumerate(self.items()): if i == n: break yield e
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ]
383,153
def ToPath(self): if self.path_type == PathInfo.PathType.OS: return os.path.join("fs", "os", *self.path_components) elif self.path_type == PathInfo.PathType.TSK: return os.path.join("fs", "tsk", *self.path_components) elif self.path_type == PathInfo.PathType.REGISTRY: return os.path....
Converts a reference into a VFS file path.
383,154
def run(self): if self.stdout: sys.stdout.write("extracted json data:\n" + json.dumps( self.metadata, default=to_str) + "\n") else: extract_dist.class_metadata = self.metadata
Sends extracted metadata in json format to stdout if stdout option is specified, assigns metadata dictionary to class_metadata variable otherwise.
383,155
def query(ra ,dec, rad=0.1, query=None): if query is None: query=( .format(ra,dec,rad) ) tapURL = "http://TAPVizieR.u-strasbg.fr/TAPVizieR/tap/sync" tapParams={: , : , : , : ...
Query the CADC TAP service to determine the list of images for the NewHorizons Search. Things to determine: a- Images to have the reference subtracted from. b- Image to use as the 'REFERENCE' image. c- Images to be used for input into the reference image Logic: Given a particular Image/CCD find all the ...
383,156
def delete_guest(userid): guest_list_info = client.send_request() print("\nFailed to delete guest %s!" % userid) else: print("\nSucceeded to delete guest %s!" % userid)
Destroy a virtual machine. Input parameters: :userid: USERID of the guest, last 8 if length > 8
383,157
def add_key_filter(self, *args): if self._input_mode == : raise ValueError() self._key_filters.append(args) return self
Add a single key filter to the inputs. :param args: a filter :type args: list :rtype: :class:`RiakMapReduce`
383,158
def GroupsUsersPost(self, parameters, group_id): if self.__SenseApiCall__(.format(group_id = group_id), , parameters = parameters): return True else: self.__error__ = "api call unsuccessful" return False
Add users to a group in CommonSense. @param parameters (dictonary) - Dictionary containing the users to add. @return (bool) - Boolean indicating whether GroupsPost was successful.
383,159
def _run_incremental_transforms(self, si, transforms): for transform in transforms: try: stream_id = si.stream_id si_new = transform(si, context=self.context) if si_new is None: logger.warn(, ...
Run transforms on stream item. Item may be discarded by some transform. Writes successful items out to current self.t_chunk Returns transformed item or None.
383,160
def hour(self, value=None): if value is not None: try: value = int(value) except ValueError: raise ValueError( .format(value)) if value < 1: raise ValueError( ...
Corresponds to IDD Field `hour` Args: value (int): value for IDD Field `hour` value >= 1 value <= 24 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ...
383,161
def write_config_value_to_file(key, value, config_path=None): if config_path is None: config_path = DEFAULT_CONFIG_PATH config = _get_config_dict_from_file(config_path) config[key] = value mkdir_parents(os.path.dirname(config_path)) with open(config_path, "w") as...
Write key/value pair to config file.
383,162
def _client_builder(self): client_config = self.app.config.get() or {} client_config.setdefault( , self.app.config.get()) client_config.setdefault(, RequestsHttpConnection) return Elasticsearch(**client_config)
Build Elasticsearch client.
383,163
def get_bool_value(self, section, option, default=True): try: return self.parser.getboolean(section, option) except NoOptionError: return bool(default)
Get the bool value of an option, if it exists.
383,164
def begin(self, **options): if self.transaction is not None: raise InvalidTransaction("A transaction is already begun.") else: self.transaction = Transaction(self, **options) return self.transaction
Begin a new :class:`Transaction`. If this :class:`Session` is already in a :ref:`transactional state <transactional-state>`, an error will occur. It returns the :attr:`transaction` attribute. This method is mostly used within a ``with`` statement block:: with session.begin() as t: t.add(...) ...
383,165
def send_notification(self, method, *args): message = self._version.create_request(method, args, notification=True) self.send_message(message)
Send a JSON-RPC notification. The notification *method* is sent with positional arguments *args*.
383,166
def _ReadFloatingPointDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): return self._ReadFixedSizeDataTypeDefinition( definitions_registry, definition_values, data_types.FloatingPointDefinition, definition_name, self._SUPPO...
Reads a floating-point data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the d...
383,167
def longitude(self, value=0.0): if value is not None: try: value = float(value) except ValueError: raise ValueError( .format(value)) if value < -180.0: raise ValueError( ...
Corresponds to IDD Field `longitude` - is West, + is East, degree minutes represented in decimal (i.e. 30 minutes is .5) Args: value (float): value for IDD Field `longitude` Unit: deg Default value: 0.0 value >= -180.0 value <...
383,168
def parser_factory(fake_args=None): parser = ArgumentParser(description=) subparsers = parser.add_subparsers(dest=, help= ) extract_file_args(subparsers) environment_args(subparsers) aws_env_args(subparsers) seed_...
Return a proper contextual OptionParser
383,169
def read_mda(attribute): lines = attribute.split() mda = {} current_dict = mda path = [] prev_line = None for line in lines: if not line: continue if line == : break if prev_line: ...
Read HDFEOS metadata and return a dict with all the key/value pairs.
383,170
def get_all_subdomains(offset=0, count=100, proxy=None, hostport=None): assert proxy or hostport, if proxy is None: proxy = connect_hostport(hostport) offset = int(offset) count = int(count) page_schema = { : , : { : { : , :...
Get all subdomains within the given range. Return the list of names on success Return {'error': ...} on failure
383,171
def check_subdomain_transition(cls, existing_subrec, new_subrec): if existing_subrec.get_fqn() != new_subrec.get_fqn(): return False if existing_subrec.n + 1 != new_subrec.n: return False if not new_subrec.verify_signature(existing_subrec.address): ...
Given an existing subdomain record and a (newly-discovered) new subdomain record, determine if we can use the new subdomain record (i.e. is its signature valid? is it in the right sequence?) Return True if so Return False if not
383,172
def _strict_match(self, struct1, struct2, fu, s1_supercell=True, use_rms=False, break_on_match=False): if fu < 1: raise ValueError("fu cannot be less than 1") mask, s1_t_inds, s2_t_ind = self._get_mask(struct1, struct2, ...
Matches struct2 onto struct1 (which should contain all sites in struct2). Args: struct1, struct2 (Structure): structures to be matched fu (int): size of supercell to create s1_supercell (bool): whether to create the supercell of struct1 (vs struct2) ...
383,173
def authenticate_nova_user(self, keystone, user, password, tenant): self.log.debug(.format(user)) ep = keystone.service_catalog.url_for(service_type=, interface=) if keystone.session: return nova_client.Client(NOVA_CLIENT_VERSION...
Authenticates a regular user with nova-api.
383,174
def _setup(self): "Resets the state and prepares for running the example." self.example.error = None self.example.traceback = c = Context(parent=self.context) self.context = c if self.is_root_runner: run.before_all.execute(self.cont...
Resets the state and prepares for running the example.
383,175
def chartbeat_top(parser, token): bits = token.split_contents() if len(bits) > 1: raise TemplateSyntaxError(" takes no arguments" % bits[0]) return ChartbeatTopNode()
Top Chartbeat template tag. Render the top Javascript code for Chartbeat.
383,176
def _is_executable_file(path): fpath = os.path.realpath(path) if not os.path.isfile(fpath): return False return os.access(fpath, os.X_OK)
Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. This function was forked from pexpect originally: Copyright (c) 2013-2014, Pexpect development team Copyright (c) 2012, Noah Spurrier <noah@noah.org> PE...
383,177
def render(directory, opt): if not os.path.exists(directory) and not os.path.isdir(directory): os.mkdir(directory) a_secretfile = render_secretfile(opt) s_path = "%s/Secretfile" % directory LOG.debug("writing Secretfile to %s", s_path) open(s_path, ).write(a_secretfile) ctx = Conte...
Render any provided template. This includes the Secretfile, Vault policies, and inline AWS roles
383,178
def xform_key(self, key): t need to worry about cache keys containing invalid charactersutf-8')) return newkey.hexdigest()
we transform cache keys by taking their sha1 hash so that we don't need to worry about cache keys containing invalid characters
383,179
def is_classmethod(meth): if inspect.ismethoddescriptor(meth): return isinstance(meth, classmethod) if not inspect.ismethod(meth): return False if not inspect.isclass(meth.__self__): return False if not hasattr(meth.__self__, meth.__name__): return False return m...
Detects if the given callable is a classmethod.
383,180
def get(self, key, timeout=None): key = self.pre_identifier + key unpickled_entry = self.client.get(key) if not unpickled_entry: return None entry = pickle.loads(unpickled_entry) if timeout is None: timeout...
Given a key, returns an element from the redis table
383,181
def find_connected_atoms(struct, tolerance=0.45, ldict=JmolNN().el_radius): n_atoms = len(struct.species) fc = np.array(struct.frac_coords) species = list(map(str, struct.species)) for i,item in enumerate(species): if not item in ldict.keys(): species[i]=str(Specie.from_str...
Finds the list of bonded atoms. Args: struct (Structure): Input structure tolerance: length in angstroms used in finding bonded atoms. Two atoms are considered bonded if (radius of atom 1) + (radius of atom 2) + (tolerance) < (distance between atoms 1 and 2). Default value = 0.45, the value used by...
383,182
def cmd(send, msg, args): parser = arguments.ArgParser(args[]) parser.add_argument(, nargs=, action=arguments.DateParser) try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: send(str(e)) return if not cmdargs.date: send("Time until when...
Reports the difference between now and some specified time. Syntax: {command} <time>
383,183
def _normalize(value): if hasattr(value, ): value = value.value if value is not None: value = long(value) return value
Normalize handle values.
383,184
def frictional_resistance_coef(length, speed, **kwargs): Cf = 0.075 / (np.log10(reynolds_number(length, speed, **kwargs)) - 2) ** 2 return Cf
Flat plate frictional resistance of the ship according to ITTC formula. ref: https://ittc.info/media/2021/75-02-02-02.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param kwargs: optional could take in temperature to take account change of water property :re...
383,185
def check(self, instance): istio_mesh_endpoint = instance.get() istio_mesh_config = self.config_map[istio_mesh_endpoint] self.process(istio_mesh_config) process_mixer_endpoint = instance.get() process_mixer_config = self.config_map[process_m...
Process both the istio_mesh instance and process_mixer instance associated with this instance
383,186
def is_success(self): for _session in self._sessions.values(): if not _session.is_success(): return False return True
check all sessions to see if they have completed successfully
383,187
def store_vdp_vsi(self, port_uuid, mgrid, typeid, typeid_ver, vsiid_frmt, vsiid, filter_frmt, gid, mac, vlan, new_network, reply, oui_id, oui_data, vsw_cb_fn, vsw_cb_data, reason): if port_uuid in self.vdp_vif_map: LOG.debug(...
Stores the vNIC specific info for VDP Refresh. :param uuid: vNIC UUID :param mgrid: MGR ID :param typeid: Type ID :param typeid_ver: Version of the Type ID :param vsiid_frmt: Format of the following VSI argument :param vsiid: VSI value :param filter_frmt: Filter ...
383,188
async def whowas(self, nickname): if protocol.ARGUMENT_SEPARATOR.search(nickname) is not None: result = self.eventloop.create_future() result.set_result(None) return result if nickname not in self._pending[]: await self.rawmsg(, nickname...
Return information about offline user. This is an blocking asynchronous method: it has to be called from a coroutine, as follows: info = await self.whowas('Nick')
383,189
def output_paas(gandi, paas, datacenters, vhosts, output_keys, justify=11): output_generic(gandi, paas, output_keys, justify) if in output_keys: output_line(gandi, , paas[], justify) if in output_keys: for entry in vhosts: output_line(gandi, , entry, justify) if in...
Helper to output a paas information.
383,190
def rot90(img): s = img.shape if len(s) == 3: if s[2] in (3, 4): out = np.empty((s[1], s[0], s[2]), dtype=img.dtype) for i in range(s[2]): out[:, :, i] = np.rot90(img[:, :, i]) else: out = np.empty((s[0], s[2], s[1]), dtype=img....
rotate one or multiple grayscale or color images 90 degrees
383,191
async def inline_query(self, bot, query, *, offset=None, geo_point=None): bot = await self.get_input_entity(bot) result = await self(functions.messages.GetInlineBotResultsRequest( bot=bot, peer=types.InputPeerEmpty(), query=query, offset=offset or...
Makes the given inline query to the specified bot i.e. ``@vote My New Poll`` would be as follows: >>> client = ... >>> client.inline_query('vote', 'My New Poll') Args: bot (`entity`): The bot entity to which the inline query should be made. quer...
383,192
def GetInput(self): "Build the INPUT structure for the action" actions = 1 if self.up and self.down: actions = 2 inputs = (INPUT * actions)() vk, scan, flags = self._get_key_info() for inp in inputs: inp.type = INPUT_KEYBOARD ...
Build the INPUT structure for the action
383,193
def _reconnect_delay(self): if self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED: if self._reconnect_attempts >= len(self.RECONNECT_DELAYS): return self.RECONNECT_DELAYS[-1] else: return self.RECONNECT_DELAYS[self._reconnect_attempts] els...
Calculate reconnection delay.
383,194
def hash(value, arg): arg = str(arg).lower() if sys.version_info >= (3,0): value = value.encode("utf-8") if not arg in get_available_hashes(): raise TemplateSyntaxError("The %s hash algorithm does not exist. Supported algorithms are: %" % (arg, get_available_hashes())) try: ...
Returns a hex-digest of the passed in value for the hash algorithm given.
383,195
def stem(self, text): stemmed_text = for word in text.split(): if word not in self.stops: word, in_que_pass_list = self._checkremove_que(word) if not in_que_pass_list: word, was_stemmed = ...
Stem each word of the Latin text.
383,196
def query(usr, pwd, *hpo_terms): raw_result = query_phenomizer(usr, pwd, *hpo_terms) for line in raw_result.text.split(): if len(line) > 1: if not line.startswith(): yield parse_result(line)
Query the phenomizer web tool Arguments: usr (str): A username for phenomizer pwd (str): A password for phenomizer hpo_terms (list): A list with hpo terms yields: parsed_term (dict): A dictionary with the parsed information from phenomizer
383,197
def _bss_decomp_mtifilt_images(reference_sources, estimated_source, j, flen, Gj=None, G=None): nsampl = np.shape(estimated_source)[0] nchan = np.shape(estimated_source)[1] saveg = Gj is not None and G is not None s_true = np.hstack((np.reshape(reference...
Decomposition of an estimated source image into four components representing respectively the true source image, spatial (or filtering) distortion, interference and artifacts, derived from the true source images using multichannel time-invariant filters. Adapted version to work with multichannel sources...
383,198
def _close_holding(self, trade): left_quantity = trade.last_quantity delta = 0 if trade.side == SIDE.BUY: if trade.position_effect == POSITION_EFFECT.CLOSE and len(self._sell_old_holding_list) != 0: old_price, old_quantity = self._sell_old_holdin...
应用平仓,并计算平仓盈亏 买平: delta_realized_pnl = sum of ((trade_price - cost_price)* quantity) of closed trades * contract_multiplier 卖平: delta_realized_pnl = sum of ((cost_price - trade_price)* quantity) of closed trades * contract_multiplier :param trade: rqalpha.model.trade.Trade ...
383,199
def domain_delete(domain, logger): if domain is not None: try: if domain.isActive(): domain.destroy() except libvirt.libvirtError: logger.exception("Unable to destroy the domain.") try: domain.undefine() except libvirt.libvirtE...
libvirt domain undefinition. @raise: libvirt.libvirtError.