code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def remove(self): xmlrpc = XMLRPCConnection() try: xmlrpc.connection.remove_vrf( { 'vrf': { 'id': self.id }, 'auth': self._auth_opts.options }) except xmlrpclib.Fault as xml_fault: raise _fault_to_exc...
Remove VRF. Maps to the function :py:func:`nipap.backend.Nipap.remove_vrf` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values.
def create(cls, service=None, endpoint=None, data=None, *args, **kwargs): cls.validate(data) if service is None and endpoint is None: raise InvalidArguments(service, endpoint) if endpoint is None: sid = service['id'] if isinstance(service, Entity) else service ...
Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service.
def data_filler_customer(self, number_of_rows, pipe): try: for i in range(number_of_rows): pipe.hmset('customer:%s' % i, { 'id': rnd_id_generator(self), 'name': self.faker.first_name(), 'lastname': self.faker.last_name(), ...
creates keys with customer data
def _get_csv_fieldnames(csv_reader): fieldnames = [] for row in csv_reader: for col in row: field = ( col.strip() .replace('"', "") .replace(" ", "") .replace("(", "") .replace(")", "") .lower() ...
Finds fieldnames in Polarion exported csv file.
def information_title_header_element(feature, parent): _ = feature, parent header = information_title_header['string_format'] return header.capitalize()
Retrieve information title header string from definitions.
def _create_job_details(self, key, job_config, logfile, status): self.update_args(job_config) job_details = JobDetails(jobname=self.full_linkname, jobkey=key, appname=self.appname, logfile=logfile, ...
Create a `JobDetails` for a single job Parameters ---------- key : str Key used to identify this particular job job_config : dict Dictionary with arguements passed to this particular job logfile : str Name of the associated log file ...
def DeleteSubjects(self, subjects, sync=False): for subject in subjects: self.DeleteSubject(subject, sync=sync)
Delete multiple subjects at once.
def _get_bandfilenames(self, **options): conf = options[self.platform_name + '-viirs'] rootdir = conf['rootdir'] for section in conf: if not section.startswith('section'): continue bandnames = conf[section]['bands'] for band in bandnames: ...
Get filename for each band
def is_auth_alive(self): "Return true if the auth is not expired, else false" model = self.model('ir.model') try: model.search([], None, 1, None) except ClientError as err: if err and err.message['code'] == 403: return False raise ...
Return true if the auth is not expired, else false
def is_exchange(self, reaction_id): reaction = self.get_reaction(reaction_id) return (len(reaction.left) == 0) != (len(reaction.right) == 0)
Whether the given reaction is an exchange reaction.
def wait(hotkey=None, suppress=False, trigger_on_release=False): if hotkey: lock = _Event() remove = add_hotkey(hotkey, lambda: lock.set(), suppress=suppress, trigger_on_release=trigger_on_release) lock.wait() remove_hotkey(remove) else: while True: _time.slee...
Blocks the program execution until the given hotkey is pressed or, if given no parameters, blocks forever.
def load_personae(): dataset_path = _load('personae') X = _load_csv(dataset_path, 'data') y = X.pop('label').values return Dataset(load_personae.__doc__, X, y, accuracy_score, stratify=True)
Personae Dataset. The data of this dataset is a 2d numpy array vector containing 145 entries that include texts written by Dutch users in Twitter, with some additional information about the author, and the target is a 1d numpy binary integer array indicating whether the author was extrovert or not.
def enter_maintenance_mode(self): cmd = self._cmd('enterMaintenanceMode') if cmd.success: self._update(get_host(self._get_resource_root(), self.hostId)) return cmd
Put the host in maintenance mode. @return: Reference to the completed command. @since: API v2
def absolute_path(self, path, start): if posixpath.isabs(path): path = posixpath.join(staticfiles_storage.location, path) else: path = posixpath.join(start, path) return posixpath.normpath(path)
Return the absolute public path for an asset, given the path of the stylesheet that contains it.
def inserir(self, id_user, id_group): if not is_valid_int_param(id_user): raise InvalidParameterError( u'The identifier of User is invalid or was not informed.') if not is_valid_int_param(id_group): raise InvalidParameterError( u'The identifier of ...
Create a relationship between User and Group. :param id_user: Identifier of the User. Integer value and greater than zero. :param id_group: Identifier of the Group. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'user_group': {'i...
def make_step_rcont (transition): if not np.isfinite (transition): raise ValueError ('"transition" argument must be finite number; got %r' % transition) def step_rcont (x): x = np.asarray (x) x1 = np.atleast_1d (x) r = (x1 >= transition).astype (x.dtype) if x.ndim == 0: ...
Return a ufunc-like step function that is right-continuous. Returns 1 if x >= transition, 0 otherwise.
def dependency_state(widgets, drop_defaults=True): if widgets is None: state = Widget.get_manager_state(drop_defaults=drop_defaults, widgets=None)['state'] else: try: widgets[0] except (IndexError, TypeError): widgets = [widgets] state = {} for wid...
Get the state of all widgets specified, and their dependencies. This uses a simple dependency finder, including: - any widget directly referenced in the state of an included widget - any widget in a list/tuple attribute in the state of an included widget - any widget in a dict attribute in the state...
def from_text_files(cls, path, field, train, validation, test=None, bs=64, bptt=70, **kwargs): trn_ds, val_ds, test_ds = ConcatTextDataset.splits( path, text_field=field, train=train, validation=validation, test=test) return cls(path, field, trn_ds, val_ds, test_ds, bs, bptt, **kwargs)
Method used to instantiate a LanguageModelData object that can be used for a supported nlp task. Args: path (str): the absolute path in which temporary model data will be saved field (Field): torchtext field train (str): file location of the training data ...
def list(self, *args, **kwargs): return [ self.prepare_model(n) for n in self.client.api.nodes(*args, **kwargs) ]
List swarm nodes. Args: filters (dict): Filters to process on the nodes list. Valid filters: ``id``, ``name``, ``membership`` and ``role``. Default: ``None`` Returns: A list of :py:class:`Node` objects. Raises: :py:class:`doc...
def fix_coordinate_decimal(d): try: for idx, n in enumerate(d["geo"]["geometry"]["coordinates"]): d["geo"]["geometry"]["coordinates"][idx] = round(n, 5) except Exception as e: logger_misc.error("fix_coordinate_decimal: {}".format(e)) return d
Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal. Round them down to 5 decimals :param dict d: Metadata :return dict d: Metadata
def _do_packet_out(self, datapath, data, in_port, actions): ofproto = datapath.ofproto parser = datapath.ofproto_parser out = parser.OFPPacketOut( datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER, data=data, in_port=in_port, actions=actions) datapath.send_msg(ou...
send a packet.
def facetrecordtrees(table, key, start='start', stop='stop'): import intervaltree getstart = attrgetter(start) getstop = attrgetter(stop) getkey = attrgetter(key) trees = dict() for rec in records(table): k = getkey(rec) if k not in trees: trees[k] = intervaltree.Inte...
Construct faceted interval trees for the given table, where each node in the tree is a record.
def mark_as_duplicate(self, duplicated_cid, master_cid, msg=''): content_id_from = self.get_post(duplicated_cid)["id"] content_id_to = self.get_post(master_cid)["id"] params = { "cid_dupe": content_id_from, "cid_to": content_id_to, "msg": msg } ...
Mark the post at ``duplicated_cid`` as a duplicate of ``master_cid`` :type duplicated_cid: int :param duplicated_cid: The numeric id of the duplicated post :type master_cid: int :param master_cid: The numeric id of an older post. This will be the post that gets kept and ``...
def is_state_machine_stopped_to_proceed(selected_sm_id=None, root_window=None): if not state_machine_execution_engine.finished_or_stopped(): if selected_sm_id is None or selected_sm_id == state_machine_manager.active_state_machine_id: message_string = "A state machine is still running. This stat...
Check if state machine is stopped and in case request user by dialog how to proceed The function checks if a specific state machine or by default all state machines have stopped or finished execution. If a state machine is still running the user is ask by dialog window if those should be stopped or not. ...
def get_grade_entries_by_ids(self, grade_entry_ids): collection = JSONClientValidated('grading', collection='GradeEntry', runtime=self._runtime) object_id_list = [] for i in grade_entry_ids: object_id_l...
Gets a ``GradeEntryList`` corresponding to the given ``IdList``. arg: grade_entry_ids (osid.id.IdList): the list of ``Ids`` to retrieve return: (osid.grading.GradeEntryList) - the returned ``GradeEntry`` list raise: NotFound - an ``Id was`` not found ...
def devices_in_group(self): try: devices = self.get_parameter('devices') except AttributeError: return [] ctor = DeviceFactory return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]
Fetch list of devices in group.
def login(self): pg = self.getPage("http://www.neopets.com") form = pg.form(action="/login.phtml") form.update({'username': self.username, 'password': self.password}) pg = form.submit() logging.getLogger("neolib.user").info("Login check", {'pg': pg}) return self.username ...
Logs the user in, returns the result Returns bool - Whether or not the user logged in successfully
def j0(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_j0, (BigFloat._implicit_convert(x),), context, )
Return the value of the first kind Bessel function of order 0 at x.
def size(self, units="MiB"): self.open() size = lvm_pv_get_size(self.handle) self.close() return size_convert(size, units)
Returns the physical volume size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB.
def get_assets(self, bbox, **kwargs): response = self._get_assets(bbox, **kwargs) assets = [] for asset in response['_embedded']['assets']: asset_url = asset['_links']['self'] uid = asset_url['href'].split('/')[-1] asset['uid'] = uid del(asset['_li...
Query the assets stored in the intelligent environment for a given bounding box and query. Assets can be filtered by type of asset, event, or media available. - device_type=['DATASIM'] - asset_type=['CAMERA'] - event_type=['PKIN'] - media_type=['IMAGE'] ...
def _render_list(self, items, empty='<pre>&lt;empty&gt;</pre>'): if not items or len(items) == 0: self._segments.append(empty) return self._segments.append('<ul>') for o in items: self._segments.append('<li>') self._segments.append(str(o)) self._segments.append('</li>') sel...
Renders an HTML list with the specified list of strings. Args: items: the iterable collection of objects to render. empty: what to render if the list is None or empty.
def ReadTrigger(self, trigger_link, options=None): if options is None: options = {} path = base.GetPathFromLink(trigger_link) trigger_id = base.GetResourceIdOrFullNameFromLink(trigger_link) return self.Read(path, 'triggers', trigger_id, None, options)
Reads a trigger. :param str trigger_link: The link to the trigger. :param dict options: The request options for the request. :return: The read Trigger. :rtype: dict
def url_for_token(self, token): book_url = self.get_config_value("pages", token) book, _, url_tail = book_url.partition(':') book_base = settings.HELP_TOKENS_BOOKS[book] url = book_base lang = getattr(settings, "HELP_TOKENS_LANGUAGE_CODE", None) if lang is not None: ...
Find the full URL for a help token.
def copy_path(self): path = cairo.cairo_copy_path(self._pointer) result = list(_iter_path(path)) cairo.cairo_path_destroy(path) return result
Return a copy of the current path. :returns: A list of ``(path_operation, coordinates)`` tuples of a :ref:`PATH_OPERATION` string and a tuple of floats coordinates whose content depends on the operation type: * :obj:`MOVE_TO <PATH_MOVE_TO>`: 1 point ...
def UpdateFrom(self, src): if not isinstance(src, PathInfo): raise TypeError("expected `%s` but got `%s`" % (PathInfo, type(src))) if self.path_type != src.path_type: raise ValueError( "src [%s] does not represent the same path type as self [%s]" % (src.path_type, self.path_type)...
Merge path info records. Merges src into self. Args: src: An rdfvalues.objects.PathInfo record, will be merged into self. Raises: ValueError: If src does not represent the same path.
def freeze_js(html): matches = js_src_pattern.finditer(html) if not matches: return html for match in reversed(tuple(matches)): file_name = match.group(1) file_path = os.path.join(js_files_path, file_name) with open(file_path, "r", encoding="utf-8") as f: file_con...
Freeze all JS assets to the rendered html itself.
def build_strings(strings, prefix): strings = [ ( make_c_str(prefix + str(number), value), reloc_ptr( prefix + str(number), 'reloc_delta', 'char *' ) ) for value, number in sort_values(strings) ] return [...
Construct string definitions according to the previously maintained table.
def mul(left, right): from .mv_mul import MvMul length = max(left, right) if length == 1: return Mul(left, right) return MvMul(left, right)
Distribution multiplication. Args: left (Dist, numpy.ndarray) : left hand side. right (Dist, numpy.ndarray) : right hand side.
def check_types(func): call = PythonCall(func) @wraps(func) def decorator(*args, **kwargs): parameters = call.bind(args, kwargs) for arg_name, expected_type in func.__annotations__.items(): if not isinstance(parameters[arg_name], expected_type): raise TypeError("{...
Check if annotated function arguments are of the correct type
def _SkipGroup(buffer, pos, end): while 1: (tag_bytes, pos) = ReadTag(buffer, pos) new_pos = SkipField(buffer, pos, end, tag_bytes) if new_pos == -1: return pos pos = new_pos
Skip sub-group. Returns the new position.
def purge_dict(idict): odict = {} for key, val in idict.items(): if is_null(val): continue odict[key] = val return odict
Remove null items from a dictionary
def _refresh(self): new_token = self.authenticate(self._username, self._password) self._token = new_token logger.info('New API token received: "{}".'.format(new_token)) return self._token
Refresh the API token using the currently bound credentials. This is simply a convenience method to be invoked automatically if authentication fails during normal client use.
def run(): _parser_options() set_verbose(args["verbose"]) if _check_global_settings(): _load_db() else: exit(-1) _setup_server() if args["rollback"]: _server_rollback() okay("The server rollback appears to have been successful.") exit(0) _server_enable...
Main script entry to handle the arguments given to the script.
def search_one(self, keyword, arg=None, children=None): if children is None: children = self.substmts for ch in children: if ch.keyword == keyword and (arg is None or ch.arg == arg): return ch return None
Return receiver's substmt with `keyword` and optionally `arg`.
def set_examples(self, examples): self.store('examples', examples) if len(examples) > 0: self.store('are_sequence_examples', isinstance(examples[0], tf.train.SequenceExample)) return self
Sets the examples to be displayed in WIT. Args: examples: List of example protos. Returns: self, in order to enabled method chaining.
def _get_explicit_environ_credentials(): explicit_file = os.environ.get(environment_vars.CREDENTIALS) if explicit_file is not None: credentials, project_id = _load_credentials_from_file( os.environ[environment_vars.CREDENTIALS]) return credentials, project_id else: return...
Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment variable.
def load_sensor_composites(self, sensor_name): config_filename = sensor_name + ".yaml" LOG.debug("Looking for composites config file %s", config_filename) composite_configs = config_search_paths( os.path.join("composites", config_filename), self.ppp_config_dir, check_exis...
Load all compositor configs for the provided sensor.
def get_properties(obj): properties = {} for property_name in dir(obj): property = getattr(obj, property_name) if PropertyReflector._is_property(property, property_name): properties[property_name] = property return properties
Get values of all properties in specified object and returns them as a map. :param obj: an object to get properties from. :return: a map, containing the names of the object's properties and their values.
def set_mime_type(self, mime_type): try: self.set_lexer_from_mime_type(mime_type) except ClassNotFound: _logger().exception('failed to get lexer from mimetype') self._lexer = TextLexer() return False except ImportError: _logger().warnin...
Update the highlighter lexer based on a mime type. :param mime_type: mime type of the new lexer to setup.
def tag_timexes(self): if not self.is_tagged(ANALYSIS): self.tag_analysis() if not self.is_tagged(TIMEXES): if self.__timex_tagger is None: self.__timex_tagger = load_default_timex_tagger() self.__timex_tagger.tag_document(self, **self.__kwargs) ...
Create ``timexes`` layer. Depends on morphological analysis data in ``words`` layer and tags it automatically, if it is not present.
def set_value(self, value, block_events=False): if block_events: self.block_events() self._widget.setValue(value) if block_events: self.unblock_events()
Sets the current value of the number box. Setting block_events=True will temporarily block the widget from sending any signals when setting the value.
def delete_request( self, alias, uri, data=None, json=None, params=None, headers=None, allow_redirects=None, timeout=None): session = self._cache.switch(alias) data = self._format_data_according_t...
Send a DELETE request on the session object found using the given `alias` ``alias`` that will be used to identify the Session object in the cache ``uri`` to send the DELETE request to ``json`` a value that will be json encoded and sent as request data if data is not spe...
def task_transaction(channel): with channel.lock: if channel.poll(0): task = channel.recv() channel.send(Acknowledgement(os.getpid(), task.id)) else: raise RuntimeError("Race condition between workers") return task
Ensures a task is fetched and acknowledged atomically.
def convert(cls, value, from_unit, to_unit): value_ms = value * cls.UNITS_IN_MILLISECONDS[from_unit] return value_ms / cls.UNITS_IN_MILLISECONDS[to_unit]
Convert a value from one time unit to another. :return: the numeric value converted to the desired unit :rtype: float
def isinstance(instance, ifaces): ifaces = _ensure_ifaces_tuple(ifaces) for iface in ifaces: attributes = ( attr for attr in iface.__abstractmethods__ if hasattr(getattr(iface, attr), '__iattribute__') ) for attribute in attributes: if not ...
Check if a given instance is an implementation of the interface.
def get_con_id(self): con_id = "" if "contribution" in self.tables: if "id" in self.tables["contribution"].df.columns: con_id = str(self.tables["contribution"].df["id"].values[0]) return con_id
Return contribution id if available
def convert_ids_to_tokens(self, ids): tokens = [] for i in ids: tokens.append(self.ids_to_tokens[i]) return tokens
Converts a sequence of ids in wordpiece tokens using the vocab.
def clear_license(self): if (self.get_license_metadata().is_read_only() or self.get_license_metadata().is_required()): raise errors.NoAccess() self._my_map['license'] = dict(self._license_default)
Removes the license. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
def unlistify(n, depth=1, typ=list, get=None): i = 0 if depth is None: depth = 1 index_desired = get or 0 while i < depth and isinstance(n, typ): if len(n): if len(n) > index_desired: n = n[index_desired] i += 1 else: return...
Return the desired element in a list ignoring the rest. >>> unlistify([1,2,3]) 1 >>> unlistify([1,[4, 5, 6],3], get=1) [4, 5, 6] >>> unlistify([1,[4, 5, 6],3], depth=2, get=1) 5 >>> unlistify([1,(4, 5, 6),3], depth=2, get=1) (4, 5, 6) >>> unlistify([1,2,(4, 5, 6)], depth=2, get=2) ...
def InstallNanny(self): new_config = config.CONFIG.MakeNewConfig() new_config.SetWriteBack(config.CONFIG["Config.writeback"]) for option in self.nanny_options: new_config.Set(option, config.CONFIG.Get(option)) new_config.Write() args = [ config.CONFIG["Nanny.binary"], "--service_key", ...
Install the nanny program.
def to_string_with_default(value, default_value): result = StringConverter.to_nullable_string(value) return result if result != None else default_value
Converts value into string or returns default when value is None. :param value: the value to convert. :param default_value: the default value. :return: string value or default when value is null.
def get(self, var, default=None): try: return self.__get(var) except (KeyError, IndexError): return default
Return a value from configuration. Safe version which always returns a default value if the value is not found.
def get_mean_values(self, C, sites, rup, dists, a1100): if isinstance(a1100, np.ndarray): temp_vs30 = sites.vs30 temp_z2pt5 = sites.z2pt5 else: temp_vs30 = 1100.0 * np.ones(len(sites.vs30)) temp_z2pt5 = self._select_basin_model(1100.0) *\ n...
Returns the mean values for a specific IMT
def add_column(self, column_name, column_values): if isinstance(column_values, list) and isinstance(column_values[0], list): raise ValueError('"column_values" must be a flat list, but we detected ' 'that its first entry is a list') if isinstance(column_values, np.ndarray) and column...
Adds a named column of metadata values. Args: column_name: Name of the column. column_values: 1D array/list/iterable holding the column values. Must be of length `num_points`. The i-th value corresponds to the i-th point. Raises: ValueError: If `column_values` is not 1D array, or o...
def get_sentences_list(self, sentences=1): if sentences < 1: raise ValueError('Param "sentences" must be greater than 0.') sentences_list = [] while sentences: num_rand_words = random.randint(self.MIN_WORDS, self.MAX_WORDS) random_sentence = self.make_sentence...
Return sentences in list. :param int sentences: how many sentences :returns: list of strings with sentence :rtype: list
def lock_option(self, key, subkey): key, subkey = _lower_keys(key, subkey) _entry_must_exist(self.gc, key, subkey) self.gc.loc[ (self.gc["k1"] == key) & (self.gc["k2"] == subkey), "locked"] = True
Make an option unmutable. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. :raise: :NotRegisteredError: If ``key`` or ``subkey`` do not define any option.
def resolve_nested_dict(nested_dict): res = {} for k, v in nested_dict.items(): if isinstance(v, dict): for k_, v_ in resolve_nested_dict(v).items(): res[(k, ) + k_] = v_ else: res[(k, )] = v return res
Flattens a nested dict by joining keys into tuple of paths. Can then be passed into `format_vars`.
def _estimate_p_values(self): if not self._is_fitted: raise AttributeError('GAM has not been fitted. Call fit first.') p_values = [] for term_i in range(len(self.terms)): p_values.append(self._compute_p_value(term_i)) return p_values
estimate the p-values for all features
def scene_name(sequence_number, scene_id, name): return MessageWriter().string("scene.name").uint64(sequence_number).uint32(scene_id).string(name).get()
Create a scene.name message
def get_pwm_list(pwm_id_list, pseudocountProb=0.0001): l = load_motif_db(HOCOMOCO_PWM) l = {k.split()[0]: v for k, v in l.items()} pwm_list = [PWM(_normalize_pwm(l[m]) + pseudocountProb, name=m) for m in pwm_id_list] return pwm_list
Get a list of HOCOMOCO PWM's. # Arguments pwm_id_list: List of id's from the `PWM_id` column in `get_metadata()` table pseudocountProb: Added pseudocount probabilities to the PWM # Returns List of `concise.utils.pwm.PWM` instances.
def _customer_lifetime_value( transaction_prediction_model, frequency, recency, T, monetary_value, time=12, discount_rate=0.01, freq="D" ): df = pd.DataFrame(index=frequency.index) df["clv"] = 0 steps = np.arange(1, time + 1) factor = {"W": 4.345, "M": 1.0, "D": 30, "H": 30 * 24}[freq] for i in ...
Compute the average lifetime value for a group of one or more customers. This method computes the average lifetime value for a group of one or more customers. Parameters ---------- transaction_prediction_model: the model to predict future transactions frequency: array_like the freq...
def _resource_prefix(self, resource=None): px = 'ELASTICSEARCH' if resource and config.DOMAIN[resource].get('elastic_prefix'): px = config.DOMAIN[resource].get('elastic_prefix') return px
Get elastic prefix for given resource. Resource can specify ``elastic_prefix`` which behaves same like ``mongo_prefix``.
def get_backspace_count(self, buffer): if TriggerMode.ABBREVIATION in self.modes and self.backspace: if self._should_trigger_abbreviation(buffer): abbr = self._get_trigger_abbreviation(buffer) stringBefore, typedAbbr, stringAfter = self._partition_input(buffer, abbr) ...
Given the input buffer, calculate how many backspaces are needed to erase the text that triggered this folder.
def _create_driver(self, **kwargs): if self.driver is None: self.driver = self.create_driver(**kwargs) self.init_driver_func(self.driver)
Create webdriver, assign it to ``self.driver``, and run webdriver initiation process, which is usually used for manual login.
def parse(self, module): self.parse_block(module.refstring, module, module, 0) min_start = len(module.refstring) for x in module.executables: if module.executables[x].start < min_start: min_start = module.executables[x].start module.contains = module.refstring...
Extracts all the subroutine and function definitions from the specified module.
def _dirdiffandupdate(self, dir1, dir2): self._dowork(dir1, dir2, None, self._update)
Private function which does directory diff & update
def collect_blame_info(cls, matches): old_area = None for filename, ranges in matches: area, name = os.path.split(filename) if not area: area = '.' if area != old_area: print("\n\n%s/\n" % area) old_area = area ...
Runs git blame on files, for the specified sets of line ranges. If no line range tuples are provided, it will do all lines.
def AddFileEntry( self, path, file_entry_type=definitions.FILE_ENTRY_TYPE_FILE, file_data=None, link_data=None): if path in self._paths: raise KeyError('File entry already set for path: {0:s}.'.format(path)) if file_data and file_entry_type != definitions.FILE_ENTRY_TYPE_FILE: raise Valu...
Adds a fake file entry. Args: path (str): path of the file entry. file_entry_type (Optional[str]): type of the file entry object. file_data (Optional[bytes]): data of the fake file-like object. link_data (Optional[bytes]): link data of the fake file entry object. Raises: KeyError...
def on_key_press(self, event): key = event.key if event.modifiers: return if self.enable_keyboard_pan and key in self._arrows: self._pan_keyboard(key) if key in self._pm: self._zoom_keyboard(key) if key == 'R': self.reset()
Pan and zoom with the keyboard.
def get_clonespec_for_valid_snapshot(config_spec, object_ref, reloc_spec, template, vm_): moving = True if QUICK_LINKED_CLONE == vm_['snapshot']['disk_move_type']: reloc_spec.diskMoveType = QUICK_LINKED_CLONE elif CURRENT_STATE_LINKED_CLONE == vm_['snapshot']['disk_move_type']: reloc_spec.di...
return clonespec only if values are valid
def facts(): ret = {} try: ret['facts'] = __proxy__['junos.get_serialized_facts']() ret['out'] = True except Exception as exception: ret['message'] = 'Could not display facts due to "{0}"'.format( exception) ret['out'] = False return ret
Displays the facts gathered during the connection. These facts are also stored in Salt grains. CLI Example: .. code-block:: bash salt 'device_name' junos.facts
def view_job_info(token, dstore): data = [['task', 'sent', 'received']] for task in dstore['task_info']: dset = dstore['task_info/' + task] if 'argnames' in dset.attrs: argnames = dset.attrs['argnames'].split() totsent = dset.attrs['sent'] sent = ['%s=%s' % (a...
Determine the amount of data transferred from the controller node to the workers and back in a classical calculation.
def get_parent_catalogs(self, catalog_id): if self._catalog_session is not None: return self._catalog_session.get_parent_catalogs(catalog_id=catalog_id) return CatalogLookupSession( self._proxy, self._runtime).get_catalogs_by_ids( list(self.get_parent_...
Gets the parent catalogs of the given ``id``. arg: catalog_id (osid.id.Id): the ``Id`` of the ``Catalog`` to query return: (osid.cataloging.CatalogList) - the parent catalogs of the ``id`` raise: NotFound - a ``Catalog`` identified by ``Id is`` not ...
def _build_cookie_jar(cls, session: AppSession): if not session.args.cookies: return if session.args.load_cookies or session.args.save_cookies: session.factory.set('CookieJar', BetterMozillaCookieJar) cookie_jar = session.factory.new('CookieJar') if sessio...
Build the cookie jar
def ms_to_datetime(ms): dt = datetime.datetime.utcfromtimestamp(ms / 1000) return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)
Converts a millisecond accuracy timestamp to a datetime
def pad_char(text: str, width: int, char: str = '\n') -> str: dis = width - len(text) if dis < 0: raise ValueError if dis > 0: text += char * dis return text
Pads a text until length width.
def _call(self, x): pointwise_norm = self.pointwise_norm(x) return pointwise_norm.inner(pointwise_norm.space.one())
Return the group L1-norm of ``x``.
def polygon_from_points(points): polygon = [] for pair in points.split(" "): x_y = pair.split(",") polygon.append([float(x_y[0]), float(x_y[1])]) return polygon
Constructs a numpy-compatible polygon from a page representation.
def bind_filter(self, direction, filter_name): if direction not in self._dynamips_direction: raise DynamipsError("Unknown direction {} to bind filter {}:".format(direction, filter_name)) dynamips_direction = self._dynamips_direction[direction] yield from self._hypervisor.send("nio bi...
Adds a packet filter to this NIO. Filter "freq_drop" drops packets. Filter "capture" captures packets. :param direction: "in", "out" or "both" :param filter_name: name of the filter to apply
def create_spot_datafeed_subscription(self, bucket, prefix): params = {'Bucket' : bucket} if prefix: params['Prefix'] = prefix return self.get_object('CreateSpotDatafeedSubscription', params, SpotDatafeedSubscription, verb='POST')
Create a spot instance datafeed subscription for this account. :type bucket: str or unicode :param bucket: The name of the bucket where spot instance data will be written. The account issuing this request must have FULL_CONTROL access to the bucket ...
def process_fields(self, fields): result = [] strip = ''.join(self.PREFIX_MAP) for field in fields: direction = self.PREFIX_MAP[''] if field[0] in self.PREFIX_MAP: direction = self.PREFIX_MAP[field[0]] field = field.lstrip(strip) result.append((field, direction)) return result
Process a list of simple string field definitions and assign their order based on prefix.
def load_dotenv(dotenv_path, verbose=False): if not os.path.exists(dotenv_path): if verbose: warnings.warn(f"Not loading {dotenv_path}, it doesn't exist.") return None for k, v in dotenv_values(dotenv_path).items(): os.environ.setdefault(k, v) return True
Read a .env file and load into os.environ. :param dotenv_path: :type dotenv_path: str :param verbose: verbosity flag, raise warning if path does not exist :return: success flag
def iv(b, **kwargs): import matplotlib.pyplot as plt import imview.imviewer as imview b = checkma(b) fig = plt.figure() imview.bma_fig(fig, b, **kwargs) plt.show() return fig
Quick access to imview for interactive sessions
def withconfig(self, keysuffix): def decorator(cls): return self.loadconfig(keysuffix, cls) return decorator
Load configurations with this decorator
def run(self): self.files_exist() self.info_file() sources = self.sources if len(sources) > 1 and self.sbo_sources != sources: sources = self.sbo_sources BuildPackage(self.script, sources, self.path, auto=True).build() raise SystemExit()
Build package and fix ordelist per checksum
def return_features_numpy(self, names='all'): if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return return_features_numpy_base(self.dbpath, self._set_object, self.points_amt, names)
Returns a 2d numpy array of extracted features Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', all features will be returned, default value: 'all' Returns ------- A numpy arra...
def query(self, variables, evidence=None, joint=True): return self._query(variables=variables, operation='marginalize', evidence=evidence, joint=joint)
Query method using belief propagation. Parameters ---------- variables: list list of variables for which you want to compute the probability evidence: dict a dict key, value pair as {var: state_of_var_observed} None if no evidence joint: boo...
def getReferenceByName(self, name): if name not in self._referenceNameMap: raise exceptions.ReferenceNameNotFoundException(name) return self._referenceNameMap[name]
Returns the reference with the specified name.
def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int: if not isinstance(token, str): raise ValueError("Vocabulary tokens must be strings, or saving and loading will break." " Got %s (with type %s)" % (repr(token), type(token))) if token...
Adds ``token`` to the index, if it is not already present. Either way, we return the index of the token.
def get_vexrc(options, environ): if options.config and not os.path.exists(options.config): raise exceptions.InvalidVexrc("nonexistent config: {0!r}".format(options.config)) filename = options.config or os.path.expanduser('~/.vexrc') vexrc = config.Vexrc.from_file(filename, environ) return vexrc
Get a representation of the contents of the config file. :returns: a Vexrc instance.