code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, codepage=, **kwargs): value_string = value = registry_key.GetValueByName(.format(entry_number)) if value is None: parser_mediator.ProduceExtractionWarning( .format( ...
Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): ...
def nlmsg_flags(self, value): self.bytearray[self._get_slicers(2)] = bytearray(c_uint16(value or 0))
Message flags setter.
def handle_profile_save(self, sender, instance, **kwargs): self.handle_save(instance.user.__class__, instance.user)
Custom handler for user profile save
def create_manager(self, instance, superclass): rel_model = self.rating_model rated_model = self.rated_model class RelatedManager(superclass): def get_query_set(self): qs = RatingsQuerySet(rel_model, rated_model=rated_model) return qs.filter(...
Dynamically create a RelatedManager to handle the back side of the (G)FK
def is_static(*p): return all(is_CONST(x) or is_number(x) or is_const(x) for x in p)
A static value (does not change at runtime) which is known at compile time
def get_env_args(env): for arg, val in env.vars.get(, {}).items(): if val is True: yield % arg elif isinstance(val, int): for _ in range(val): yield % arg elif val is None: continue else: yield % (arg, val)
Yield options to inject into the slcli command from the environment.
def collect(cls, sources): source_stats_dict = {} for src in sources: trt = src[] if trt not in source_stats_dict: source_stats_dict[trt] = SourceGroup(trt) sg = source_stats_dict[trt] if not sg.sources: ...
:param sources: dictionaries with a key 'tectonicRegion' :returns: an ordered list of SourceGroup instances
def set_mac_addr_adv_interval(self, name, vrid, value=None, disable=False, default=False, run=True): if not default and not disable: if not int(value) or int(value) < 1 or int(value) > 3600: raise ValueError("vrrp property must " ...
Set the mac_addr_adv_interval property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. value (integer): mac-address advertisement-interval value to assign to the vrrp. disabl...
def get_backends(): IGNORE_DIRS = ["core", "tools", "utils"] global backends if backends is None: backends = {} i3pystatus_dir = os.path.dirname(i3pystatus.__file__) subdirs = [ x for x in next(os.walk(i3pystatus_dir))[1] if not x.startswith(...
Get backends info so that we can find the correct one. We just look in the directory structure to find modules.
def execute(self, command, *args, encoding=_NOTSET): if self._reader is None or self._reader.at_eof(): msg = self._close_msg or "Connection closed or corrupted" raise ConnectionClosedError(msg) if command is None: raise TypeError("command must not be None") ...
Executes redis command and returns Future waiting for the answer. Raises: * TypeError if any of args can not be encoded as bytes. * ReplyError on redis '-ERR' responses. * ProtocolError when response can not be decoded meaning connection is broken. * ConnectionClosedEr...
def with_stmt__26(self, with_loc, context, with_var, colon_loc, body): if with_var: as_loc, optional_vars = with_var item = ast.withitem(context_expr=context, optional_vars=optional_vars, as_loc=as_loc, loc=context.loc.join(optional_vars.loc)) ...
(2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite
def scope_groups(self): import ns1.rest.ipam return ns1.rest.ipam.Scopegroups(self.config)
Return a new raw REST interface to scope_group resources :rtype: :py:class:`ns1.rest.ipam.Scopegroups`
def run(self, *args): params = self.parser.parse_args(args) uuid = params.uuid organization = params.organization try: from_date = utils.str_to_datetime(params.from_date) to_date = utils.str_to_datetime(params.to_date) code = self.withdraw...
Withdraw a unique identity from an organization.
def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue name = param_names[index] kvstore.push(name, grad_list,...
Perform update of param_arrays from grad_arrays on kvstore.
def parse_docopt_string(docopt_string): from re import match, DOTALL only_usage_pattern = r usage_and_options_pattern = r usage, options = , if match(usage_and_options_pattern, docopt_string, DOTALL): usage = match(usage_and_options_pattern, docopt_string, DOTALL).groupdict()[] ...
returns a 2-tuple (usage, options)
def qteAddMiniApplet(self, appletObj: QtmacsApplet): if self._qteMiniApplet is not None: msg = self.qteLogger.warning(msg) return False if appletObj.layout() is None: appLayout = QtGui.QHBoxLayout() ...
Install ``appletObj`` as the mini applet in the window layout. At any given point there can ever only be one mini applet in the entire Qtmacs application, irrespective of how many windows are open. Note that this method does nothing if a custom mini applet is already active. Us...
def init(opts): if not in opts[]: log.critical(host\) return False if not in opts[]: log.critical(username\) return False if not in opts[]: log.critical(passwords\) return False DETAILS[] = .format(opts[][]) DETAILS[] = {: , ...
This function gets called when the proxy starts up.
def write_segment(buff, segment, ver, ver_range, eci=False): mode = segment.mode append_bits = buff.append_bits if eci and mode == consts.MODE_BYTE \ and segment.encoding != consts.DEFAULT_BYTE_ENCODING: append_bits(consts.MODE_ECI, 4) append_bits(get_eci_assignment_num...
\ Writes a segment. :param buff: The byte buffer. :param _Segment segment: The segment to serialize. :param ver: ``None`` if a QR Code is written, "M1", "M2", "M3", or "M4" if a Micro QR Code is written. :param ver_range: "M1", "M2", "M3", or "M4" if a Micro QR Code is written, ...
def _get_jenks_config(): config_file = (get_configuration_file() or os.path.expanduser(os.path.join("~", CONFIG_FILE_NAME))) if not os.path.exists(config_file): open(config_file, ).close() with open(config_file, ) as fh: return JenksData( yaml.load(fh.re...
retrieve the jenks configuration object
def find_actions(namespace, action_prefix): actions = {} for key, value in iteritems(namespace): if key.startswith(action_prefix): actions[key[len(action_prefix):]] = analyse_action(value) return actions
Find all the actions in the namespace.
def render_customizations(self): disable_plugins = self.pt.customize_conf.get(, []) if not disable_plugins: logger.debug() else: for plugin in disable_plugins: try: self.pt.remove_plugin(plugin[], plugin[], ...
Customize template for site user specified customizations
def close_connection (self): if self.url_connection is not None: try: self.url_connection.quit() except Exception: pass self.url_connection = None
Release the open connection from the connection pool.
def compute_transformed(context): key_composite = compute_key_composite( password=context._._.password, keyfile=context._._.keyfile ) kdf_parameters = context._.header.value.dynamic_header.kdf_parameters.data.dict if context._._.transformed_key is not None: transformed_key...
Compute transformed key for opening database
def send_command(self, command, args=None): if args: if isinstance(args, str): final_command = command + + args + else: return self._recv_data()
Send a command to VNDB and then get the result. :param command: What command are we sending :param args: What are the json args for this command :return: Servers Response :rtype: Dictionary (See D11 docs on VNDB)
def open_resource(self, resource_name, access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE, resource_pyclass=None, **kwargs): if resource_pyclass is None: info = self.reso...
Return an instrument for the resource name. :param resource_name: name or alias of the resource to open. :param access_mode: access mode. :type access_mode: :class:`pyvisa.constants.AccessModes` :param open_timeout: time out to open. :param resource_pyclass: resource python clas...
def add_matplotlib_cmaps(fail_on_import_error=True): try: from matplotlib import cm as _cm from matplotlib.cbook import mplDeprecation except ImportError: if fail_on_import_error: raise return for name in _cm.cmap_d: if not isinstance(name, ...
Add all matplotlib colormaps.
def times_called(self, n): if self._last_declared_call_name: actual_last_call = self._declared_calls[self._last_declared_call_name] if isinstance(actual_last_call, CallStack): raise FakeDeclarationError("Cannot use times_called() in combination with next_call()")...
Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>> auth.login() Traceback (m...
def city_center_distance(self): try: infos = self._ad_page_content.find_all( , {"class": "map_info_box"}) for info in infos: if in info.text: distance_list = re.findall( , info.text) ...
This method gets the distance to city center, in km. :return:
def load_combo_catalog(): user_dir = user_data_dir() global_dir = global_data_dir() desc = cat_dirs = [] if os.path.isdir(user_dir): cat_dirs.append(user_dir + ) cat_dirs.append(user_dir + ) if os.path.isdir(global_dir): cat_dirs.append(global_dir + ) cat_di...
Load a union of the user and global catalogs for convenience
def query( self, *, time: Timestamp, duration: Union[Duration, timedelta] = Duration(), qubits: Iterable[Qid] = None, include_query_end_time=False, include_op_end_times=False) -> List[ScheduledOperation]: duration = D...
Finds operations by time and qubit. Args: time: Operations must end after this time to be returned. duration: Operations must start by time+duration to be returned. qubits: If specified, only operations touching one of the included qubits will...
def _download_chunk(self, chunk_offset, chunk_size): range_id = .format( chunk_offset, chunk_offset + chunk_size - 1) return self._blob_service.get_blob( container_name=self._container_name, blob_name=self._blob_name, x_ms_range=range_id)
Reads or downloads the received blob from the system.
def process_response(self, request, response, spider): if not self.is_cloudflare_challenge(response): return response logger = logging.getLogger() logger.debug( , response.url ) cloudflare_tokens, __ = get_tokens( reque...
Handle the a Scrapy response
def verify(self): c = self.database.cursor() non_exist = set() no_db_entry = set(os.listdir(self.cache_dir)) try: no_db_entry.remove() no_db_entry.remove() except: pass for row in c.execute("SELECT path FROM files"): ...
Check that the database accurately describes the state of the repository
def channel_history(current): current.output = { : , : 201, : [] } for msg in list(Message.objects.filter(channel_id=current.input[], updated_at__lte=current.input[])[:20]): current.output[].insert(0, msg.serialize(current.user)) ...
Get old messages for a channel. 20 messages per request .. code-block:: python # request: { 'view':'_zops_channel_history, 'channel_key': key, 'timestamp': datetime, # timestamp data of oldest shown message } ...
def resource_moved(self, resource, new_resource): if self.moved is not None: self.moved(resource, new_resource)
It is called when a resource is moved
def cvtToMag(rh, size): rh.printSysLog("Enter generalUtils.cvtToMag") mSize = size = size / (1024 * 1024) if size > (1024 * 5): size = size / 1024 mSize = "%.1fG" % size else: mSize = "%.1fM" % size rh.printSysLog("Exit generalUtils.cvtToMag, m...
Convert a size value to a number with a magnitude appended. Input: Request Handle Size bytes Output: Converted value with a magnitude
def ret_glob_minions(self): minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions
Return minions that match via glob
def importSite(self, location): params = { "location" : location, "f" : "json" } url = self._url + "/importSite" return self._post(url=url, param_dict=params)
This operation imports the portal site configuration to a location you specify.
def create(self, data, **kwargs): base_path = if in data and in data: path = base_path % data else: path = self._compute_path(base_path) return CreateMixin.create(self, data, path=path, **kwargs)
Create a new object. Args: data (dict): Parameters to send to the server to create the resource **kwargs: Extra options to send to the server (e.g. sudo or 'ref_name', 'stage', 'name', 'all') Raises: GitlabAuthenticatio...
def setup_logging(): global console_handler if console_handler: return console_handler = logging.StreamHandler() console_handler.setFormatter(LogFormatter()) logging.getLogger("law").addHandler(console_handler) for name, level in Config.instance().items("logging"):...
Sets up the internal logging mechanism, i.e., it creates the :py:attr:`console_handler`, sets its formatting, and mounts on on the main ``"law"`` logger. It also sets the levels of all loggers that are given in the law config.
def spherical_matrix(theta, phi, axes=): result = euler_matrix(0.0, phi, theta, axes=axes) return result
Give a spherical coordinate vector, find the rotation that will transform a [0,0,1] vector to those coordinates Parameters ----------- theta: float, rotation angle in radians phi: float, rotation angle in radians Returns ---------- matrix: (4,4) rotation matrix where the following wi...
def delete_tags(self, arg): if len(arg) > 0: raw = html.fromstring(arg) return raw.text_content().strip() return arg
Removes html-tags from extracted data. :param arg: A string, the string which shall be cleaned :return: A string, the cleaned string
def shell(commands, splitlines=False, ignore_errors=False): s ``run_shell_command``. Args: commands (string, list): command or list of commands to execute spltlines (bool): optionally have the output split by lines ignore_errors (bool): ignore errors when executing these commands lo...
Subprocess based implementation of pyinfra/api/ssh.py's ``run_shell_command``. Args: commands (string, list): command or list of commands to execute spltlines (bool): optionally have the output split by lines ignore_errors (bool): ignore errors when executing these commands
def run_profilers(run_object, prof_config, verbose=False): if len(prof_config) > len(set(prof_config)): raise AmbiguousConfigurationError( % prof_config) available_profilers = {opt for opt, _ in _PROFILERS} for option in prof_config: if option not in available_profilers: ...
Runs profilers on run_object. Args: run_object: An object (string or tuple) for profiling. prof_config: A string with profilers configuration. verbose: True if info about running profilers should be shown. Returns: An ordered dictionary with collected stats. Raises: ...
def _CreateNewShowDir(self, showName): stripedDir = util.StripSpecialCharacters(showName) goodlogging.Log.Info("RENAMER", "Suggested show directory name is: ".format(stripedDir)) if self._skipUserInput is False: response = goodlogging.Log.Input(, "Enter to accept this directory, to skip this s...
Create new directory name for show. An autogenerated choice, which is the showName input that has been stripped of special characters, is proposed which the user can accept or they can enter a new name to use. If the skipUserInput variable is True the autogenerated value is accepted by default. Par...
def prepare_destruction(self): try: self.relieve_model(self.state_machine_model) assert self.__buffered_root_state_model is self.state_machine_model.root_state self.relieve_model(self.__buffered_root_state_model) self.state_machine_model = None ...
Prepares the model for destruction Un-registers itself as observer from the state machine and the root state
def open(url, wait=10): post = None if isinstance(url, URLParser) and url.method == "post": post = urllib.urlencode(url.query) url = str(url) if os.path.exists(url): return urllib.urlopen(url) else: socket.setdefaulttimeout(wait) try: ...
Returns a connection to a url which you can read(). When the wait amount is exceeded, raises a URLTimeout. When an error occurs, raises a URLError. 404 errors specifically return a HTTP404NotFound.
def present(name, service_name, auth=None, **kwargs): ret = {: name, : {}, : True, : } kwargs = __utils__[](**kwargs) __salt__[](auth) success, val = _, endpoint = _common(ret, name, service_name, kwargs) if not success: return val if not endpoin...
Ensure an endpoint exists and is up-to-date name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint enabled Boolean to control if endpoint is enabled
def get_trial_info(current_trial): if current_trial.end_time and ("_" in current_trial.end_time): time_obj = datetime.datetime.strptime(current_trial.end_time, "%Y-%m-%d_%H-%M-%S") end_time = time_obj.strftime("%Y-%m-%d %H...
Get job information for current trial.
def _argtop(y_score, k=None): if k is None: return slice(0, len(y_score)) else: return _argsort(y_score, k)
Returns the indexes of the top k scores (not necessarily sorted)
def create_node(vm_): content = ET.Element() name = ET.SubElement(content, ) name.text = vm_[] desc = ET.SubElement(content, ) desc.text = config.get_cloud_config_value( , vm_, __opts__, default=vm_[], search_global=False ) cpu = ET.SubElement(content, ) ...
Build and submit the XML to create a node
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.
def save(self, *args, **kwargs): old_instance = None if self.pk: old_instance = self.__class__._default_manager.get(pk=self.pk) self.slug = slugify(force_text(self.subject), allow_unicode=True) super().save(*args, **kwargs) ...
Saves the topic instance.
def Lazarek_Black(m, D, mul, kl, Hvap, q=None, Te=None): r G = m/(pi/4*D**2) Relo = G*D/mul if q: Bg = Boiling(G=G, q=q, Hvap=Hvap) return 30*Relo**0.857*Bg**0.714*kl/D elif Te: return 27000*30**(71/143)*(1./(G*Hvap))**(357/143)*Relo**(857/286)*Te**(357/143)*kl**(500...
r'''Calculates heat transfer coefficient for film boiling of saturated fluid in vertical tubes for either upward or downward flow. Correlation is as shown in [1]_, and also reviewed in [2]_ and [3]_. Either the heat flux or excess temperature is required for the calculation of heat transfer coeffic...
def gnomonicImageToSphere(x, y): x = x - 360.*(x>180) x = np.asarray(x) y = np.asarray(y) lon = np.degrees(np.arctan2(y, x)) r_theta = np.sqrt(x**2 + y**2) lat = np.degrees(np.arctan(180. / (np.pi * r_theta))) return lon, lat
Inverse gnomonic projection (deg).
def get_element_id(self, complete_name): [group, name] = complete_name.split() element = self.get_element(group, name) if element: return element.ident else: logger.warning(, complete_name) return None
Get the TocElement element id-number of the element with the supplied name.
def lookup_entry( self, linked_resource=None, sql_resource=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): if "lookup_entry" not in self._inner_api_calls: sel...
Get an entry by target resource name. This method allows clients to use the resource name from the source Google Cloud Platform service to get the Cloud Data Catalog Entry. Example: >>> from google.cloud import datacatalog_v1beta1 >>> >>> client = datacatalog...
def save(func): def aux(self, *args, **kwargs): out = func(self, *args, **kwargs) path = (hasattr(self, ) and self.path or os.path.join(os.getcwd(), )) gpath = (hasattr(self, ) and self.gpath or os.path.expanduser()) if os.path.exists(path): ...
@decorator: Saves data after executing :func:. Also performs modifications set as permanent options.
def from_text(self, line, line_index, column, is_escaped): begin = self._begin end = self._end single = self._single single_len = len(single) start_len = len(begin) if _token_at_col_in_line(line, column, single, single_len): return (STATE_IN_COMMENT...
Return the new state of the comment parser.
def _area_settings(area, setting, value, validate_value): if validate_value: if (setting == CONST.SETTING_EXIT_DELAY_AWAY and value not in CONST.VALID_SETTING_EXIT_AWAY): raise AbodeException(ERROR.INVALID_SETTING_VALUE, ...
Will validate area settings and values, returns data packet.
def proxyval(self, visited): if self.as_address() in visited: return ProxyAlreadyVisited() visited.add(self.as_address()) pyop_attr_dict = self.get_attr_dict() if pyop_attr_dict: attr_dict = pyop_attr_dict.proxyval(visited) else: ...
Support for new-style classes. Currently we just locate the dictionary using a transliteration to python of _PyObject_GetDictPtr, ignoring descriptors
def get_desc2nts_fnc(self, hdrgo_prt=True, section_prt=None, top_n=None, use_sections=True): nts_flat = self.get_nts_flat(hdrgo_prt, use_sections) if nts_flat: flds = nts_flat[0]._fields if not use_sections: return {:self...
Return grouped, sorted namedtuples in either format: flat, sections.
def _init_metadata(self): self._objective_bank_id_metadata = { : Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, ), : , : , : False, : False, : ...
stub
def from_coordinates(cls, coordinates): prim = cls() for coord in coordinates: pm = PseudoMonomer(ampal_parent=prim) pa = PseudoAtom(coord, ampal_parent=pm) pm.atoms = OrderedDict([(, pa)]) prim.append(pm) prim.relabel_all() return...
Creates a `Primitive` from a list of coordinates.
def ListHashes(age=aff4.NEWEST_TIME): if age == aff4.ALL_TIMES: raise ValueError("age==aff4.ALL_TIMES is not allowed.") urns = [] for fingerprint_type, hash_types in iteritems(HashFileStore.HASH_TYPES): for hash_type in hash_types: urns.append(HashFileStore.PATH.Add(fingerprint_typ...
Yields all the hashes in the file store. Args: age: AFF4 age specification. Only get hits corresponding to the given age spec. Should be aff4.NEWEST_TIME or a time range given as a tuple (start, end) in microseconds since Jan 1st, 1970. If just a microseconds value is given it's treat...
def get_row(self, row): if isinstance(self.fields, dict): return dict([ (key, text_type(value).format(**row) if RE_FORMATTED.match(value) else row[value]) for key, value in self.fields.items() ]) else: return [text_type(field)...
Format a single row (if necessary)
def error(transaction, code): transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.type = defines.Types["RST"] transaction.response.token = transaction.request.token ...
Notifies generic error on blockwise exchange. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction
def shift_image(im, shift, borderValue=0): im = np.asarray(im, dtype=np.float32) rows, cols = im.shape M = np.asarray([[1, 0, shift[1]], [0, 1, shift[0]]], dtype=np.float32) return cv2.warpAffine(im, M, (cols, rows), borderMode=cv2.BORDER_CONSTANT, ...
shift the image Parameters ---------- im: 2d array The image shift: 2 numbers (y,x) the shift in y and x direction borderValue: number, default 0 The value for the pixels outside the border (default 0) Returns ------- im: 2d array The shifted image ...
def delete(self): response = delete_payment_profile(self.customer_profile.profile_id, self.payment_profile_id) response.raise_if_error() return super(CustomerPaymentProfile, self).delete()
Delete the customer payment profile remotely and locally
def write_to_manifest(self): self.manifest.remove_section(self.feature_name) self.manifest.add_section(self.feature_name) for k, v in self.raw_dict.items(): self.manifest.set(self.feature_name, k, v)
Overwrites the section of the manifest with the featureconfig's value
def entropy_score(var,bins, w=None, decimate=True): if w is None: n = len(var) w = np.arange(0,n,n//bins) / float(n) if decimate: n = len(var) var = var[0:n:n//bins] score = w * np.log(var * w * np.sqrt(2*np.pi*np.exp(1))) score[np.isnan(score)]=np.Inf return sco...
Compute entropy scores, given a variance and # of bins
def save(fname, data): if isinstance(data, NDArray): data = [data] handles = c_array(NDArrayHandle, []) if isinstance(data, dict): str_keys = data.keys() nd_vals = data.values() if any(not isinstance(k, string_types) for k in str_keys) or \ any(not isinsta...
Saves a list of arrays or a dict of str->array to file. Examples of filenames: - ``/path/to/file`` - ``s3://my-bucket/path/to/file`` (if compiled with AWS S3 supports) - ``hdfs://path/to/file`` (if compiled with HDFS supports) Parameters ---------- fname : str The filename. da...
def get_devices(self): def process_result(result): return [self.get_device(dev) for dev in result] return Command(, [ROOT_DEVICES], process_result=process_result)
Return the devices linked to the gateway. Returns a Command.
def perform_action(self, action): form = ToolForm s_action = form_action = action.split()[0] form_name = s_action.title() + cores = False a_type = forms = [action.upper() + ] form_args = {: , : [s_action], : for...
Perform actions in the api from the CLI
def best_prefix(bytes, system=NIST): if isinstance(bytes, Bitmath): value = bytes.bytes else: value = bytes return Byte(value).best_prefix(system=system)
Return a bitmath instance representing the best human-readable representation of the number of bytes given by ``bytes``. In addition to a numeric type, the ``bytes`` parameter may also be a bitmath type. Optionally select a preferred unit system by specifying the ``system`` keyword. Choices for ``system`` are ``bitmat...
def download(self, source_file, source_len=0, info_cb=DEFAULT_MESSAGE_CALLBACK, progress_callback=None): if isinstance(source_file, six.string_types): source_len = os.stat(source_file).st_size source_file = open(source_file) if source_len == 0: data = source_file.re...
Downloads a file to the device. Args: source_file: A filename or file-like object to download to the device. source_len: Optional length of source_file. If source_file is a file-like object and source_len is not provided, source_file is read into memory. info_cb: Optional call...
def dispatch_request(self): if current_user.is_authenticated: return redirect(self.next) if in session: del session[] res = self.app.authorized_response() if res is None: if self.flash: flash(self.auth_failed_msg, ) ret...
Handle redirect back from provider
def getLoadAvg(self): try: fp = open(loadavgFile, ) line = fp.readline() fp.close() except: raise IOError( % loadavgFile) arr = line.split() if len(arr) >= 3: return [float(col) for col in arr[:3]] else: ...
Return system Load Average. @return: List of 1 min, 5 min and 15 min Load Average figures.
def asset_url_for(self, asset): if in asset: return asset if asset not in self.assets: return None return .format(self.assets_url, self.assets[asset])
Lookup the hashed asset path of a file name unless it starts with something that resembles a web address, then take it as is. :param asset: A logical path to an asset :type asset: str :return: Asset path or None if not found
def init(self, force_deploy=False, client=None): _force_deploy = self.provider_conf.force_deploy self.provider_conf.force_deploy = _force_deploy or force_deploy self._provider_conf = self.provider_conf.to_dict() r = api.Resources(self._provider_conf, client=client) r.lau...
Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be redeployed Raises: MissingNetworkError: If ...
def setup_seasonal(self): if self.ns.doge_path is not None and not self.ns.no_shibe: return now = datetime.datetime.now() for season, data in wow.SEASONS.items(): start, end = data[] start_dt = datetime.datetime(now.year, start[0]...
Check if there's some seasonal holiday going on, setup appropriate Shibe picture and load holiday words. Note: if there are two or more holidays defined for a certain date, the first one takes precedence.
def unsubscribe(request, message_id, dispatch_id, hashed, redirect_to=None): return _generic_view( , sig_unsubscribe_failed, request, message_id, dispatch_id, hashed, redirect_to=redirect_to )
Handles unsubscribe request. :param Request request: :param int message_id: :param int dispatch_id: :param str hashed: :param str redirect_to: :return:
def _request(self, method, *relative_path_parts, **kwargs): uri = self._create_api_uri(*relative_path_parts) response = get(uri, params=self._get_params(**kwargs)) self.is_initial = False self.before_cursor = response.headers.get(, None) self.after_cursor = response.headers.get(, None) retu...
Sends an HTTP request to the REST API and receives the requested data. Additionally sets up pagination cursors. :param str method: HTTP method name :param relative_path_parts: the relative paths for the request URI :param kwargs: argument keywords :returns: requested data :raises APIError: for ...
def add_leverage(self): if self.leverage is True: pass else: self.leverage = True self.z_no += 1 self.latent_variables.z_list.pop() self.latent_variables.z_list.pop() self.latent_variables.z_list.pop() ...
Adds leverage term to the model Returns ---------- None (changes instance attributes)
def handle_command_line(options): options = merge(options, constants.DEFAULT_OPTIONS) engine = plugins.ENGINES.get_engine( options[constants.LABEL_TEMPLATE_TYPE], options[constants.LABEL_TMPL_DIRS], options[constants.LABEL_CONFIG_DIR], ) if options[constants.LABEL_TEMPLATE] ...
act upon command options
def GetLayerFromFeatureService(self, fs, layerName="", returnURLOnly=False): layers = None table = None layer = None sublayer = None try: layers = fs.layers if (layers is None or len(layers) == 0) and fs.url is not None: fs = arcre...
Obtains a layer from a feature service by feature service reference. Args: fs (FeatureService): The feature service from which to obtain the layer. layerName (str): The name of the layer. Defaults to ``""``. returnURLOnly (bool): A boolean value to return the URL of the laye...
def get_model_creation_kwargs(model_obj): model_abbrev = get_model_abbrev(model_obj) model_kwargs = {"model_type": model_abbrev, "names": model_obj.name_spec, "intercept_names": model_obj.intercept_names, "intercept_ref_pos": model...
Get a dictionary of the keyword arguments needed to create the passed model object using `pylogit.create_choice_model`. Parameters ---------- model_obj : An MNDC_Model instance. Returns ------- model_kwargs : dict. Contains the keyword arguments and the required values that are nee...
def clean_expired_user_attempts(attempt_time: datetime = None) -> int: if settings.AXES_COOLOFF_TIME is None: log.debug() return 0 threshold = get_cool_off_threshold(attempt_time) count, _ = AccessAttempt.objects.filter(attempt_time__lt=threshold).delete() log.info(, count, thresh...
Clean expired user attempts from the database.
def clean_username(self): try: user = get_user_model().objects.get(username=self.cleaned_data["username"]) except get_user_model().DoesNotExist: pass else: raise forms.ValidationError( self.error_messages[]) if ...
Validate that the username is unique and not listed in ``defaults.ACCOUNTS_FORBIDDEN_USERNAMES`` list.
def local_time_to_online(dt=None): is_dst = None utc_offset = None try: if dt is None: dt = datetime.datetime.now() is_dst = time.daylight > 0 and time.localtime().tm_isdst > 0 utc_offset = (time.altzone if is_dst else time.timezone) return (time.mktime(dt...
Converts datetime object to a UTC timestamp for AGOL. Args: dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`. Returns: float: A UTC timestamp as understood by AGOL (time in ms since Unix epoch * 1000) Examples...
def psetex(self, name, time_ms, value): if isinstance(time_ms, datetime.timedelta): time_ms = int(time_ms.total_seconds() * 1000) return self.execute_command(, name, time_ms, value)
Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object
def configure(self, name=None, rules=None, query=None, **options): self.name = name if not name: raise AssertionError("Alerts rules is invalid" % name) self.rules = [parse_rule(rule) for rule in rules] self.rules = list(sorted(self.rules, key=lambda r: LEVELS.get(r.g...
Configure the alert.
def set_secure_boot_mode(self, secure_boot_enable): if self._is_boot_mode_uefi(): self._change_secure_boot_settings(, secure_boot_enable) else: msg = ( ) raise exception.IloCommandNotSupportedIn...
Enable/Disable secure boot on the server. :param secure_boot_enable: True, if secure boot needs to be enabled for next boot, else False. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
def build(client, repository_tag, docker_file, tag=None, use_cache=False): if not isinstance(client, docker.Client): raise TypeError("client needs to be of type docker.Client.") if not isinstance(docker_file, six.string_types) or not os.path.exists(docker_file): ...
Build a docker image
def callJavaFunc(func, *args): gateway = _get_gateway() args = [_py2java(gateway, a) for a in args] result = func(*args) return _java2py(gateway, result)
Call Java Function
def extra_space_exists(str1: str, str2: str) -> bool: ls1, ls2 = len(str1), len(str2) if str1.isdigit(): if str2 in [, ]: return True if ls2 > 2 and str2[0] == and str2[1:].isdigit(): return True if str2.isdigit(): if str1 in...
Return True if a space shouldn't exist between two items
def entity(self, entity_type, identifier=None): entity = _ACLEntity(entity_type=entity_type, identifier=identifier) if self.has_entity(entity): entity = self.get_entity(entity) else: self.add_entity(entity) return entity
Factory method for creating an Entity. If an entity with the same type and identifier already exists, this will return a reference to that entity. If not, it will create a new one and add it to the list of known entities for this ACL. :type entity_type: str :param enti...
def since(self, ts): spec = {: {: ts}} cursor = self.query(spec) while True: for doc in cursor: yield doc if not cursor.alive: break time.sleep(1)
Query the oplog for items since ts and then return
def _matcher(self, other): if isinstance(other, MoleculeContainer): return GraphMatcher(other, self, lambda x, y: y == x, lambda x, y: y == x) elif isinstance(other, (QueryContainer, QueryCGRContainer)): return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: ...
QueryContainer < MoleculeContainer QueryContainer < QueryContainer[more general] QueryContainer < QueryCGRContainer[more general]
def new(path=, template=None): path = abspath(path.rstrip(sep)) template = template or DEFAULT_TEMPLATE_URL render_skeleton( template, path, include_this=[], filter_this=[ , , , , , , , , , , ] ) print(H...
Creates a new project