Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
352,500
def reading_time(self, text: TextT): wc = re.findall(r, text) period = 60.0 / settings.USERS_READING_SPEED return float(len(wc)) * period + settings.USERS_READING_BUBBLE_START
Computes the time in seconds that the user will need to read a bubble containing the text passed as parameter.
352,501
def modify(self, fields=None, **fields_kwargs): modified_fields = set() fields = self.make_dict(fields, fields_kwargs) fields = self._modify(fields) for field_name, field_val in fields.items(): in_schema = field_name in self.schema.fields if in_schema: ...
update the fields of this instance with the values in dict fields this should rarely be messed with, if you would like to manipulate the fields you should override _modify() :param fields: dict, the fields in a dict :param **fields_kwargs: dict, if you would like to pass the fields as ...
352,502
def parse_subnet(self, global_params, region, subnet): vpc_id = subnet[] manage_dictionary(self.vpcs, vpc_id, SingleVPCConfig(self.vpc_resource_types)) subnet_id = subnet[] get_name(subnet, subnet, ) subnet[] = get_subnet_flow_logs_list(self, subnet) ...
Parse subnet object. :param global_params: :param region: :param subnet: :return:
352,503
def qualified_name(self): return .format(self.module.name, self.struct.name, self.name)
return the fully qualified name (`<module>.<struct>#<field>`)
352,504
def round_array(array_in): if isinstance(array_in, ndarray): return np.round(array_in).astype(int) else: return int(np.round(array_in))
arr_out = round_array(array_in) Rounds an array and recasts it to int. Also works on scalars.
352,505
def top_in(self, leaderboard_name, number, **options): return self.members_from_rank_range_in(leaderboard_name, 1, number, **options)
Retrieve members from the named leaderboard within a range from 1 to the number given. @param leaderboard_name [String] Name of the leaderboard. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be us...
352,506
def next_line(last_line, next_line_8bit): base_line = last_line - (last_line & 255) line = base_line + next_line_8bit lower_line = line - 256 upper_line = line + 256 if last_line - lower_line <= line - last_line: return lower_line if upper_line - last_line < last_line...
Compute the next line based on the last line and a 8bit next line. The behaviour of the function is specified in :ref:`reqline`. :param int last_line: the last line that was processed :param int next_line_8bit: the lower 8 bits of the next line :return: the next line closest to :paramref:`last_line` ...
352,507
def _gradient_descent(objective, p0, it, n_iter, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7, verbose=0, args=None, kwargs=None): if args is None: args = [] if kwa...
Batch gradient descent with momentum and individual gains. Parameters ---------- objective : function or callable Should return a tuple of cost and gradient for a given parameter vector. When expensive to compute, the cost can optionally be None and can be computed every n_iter_chec...
352,508
def ban_user(self, room_id, user_id, reason=""): body = { "user_id": user_id, "reason": reason } return self._send("POST", "/rooms/" + room_id + "/ban", body)
Perform POST /rooms/$room_id/ban Args: room_id (str): The room ID user_id (str): The user ID of the banee(sic) reason (str): The reason for this ban
352,509
def parse(self, text): root = ET.fromstring(text) for elm in root.findall(): for record in elm.findall(): for fileElm in record.findall(): if fileElm.get() == : mimeType = fileElm.text.strip() yield ...
Parse the text content
352,510
def invoke( src, event_file=, config_file=, profile_name=None, verbose=False, ): path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) if profile_name: os.environ[] = profile_name env_vars = cfg.get() if ...
Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to override which event file to use. :param bool verbose: Wheth...
352,511
def _send_file_internal(self, *args, **kwargs): super(Key, self)._send_file_internal(*args, **kwargs) mimicdb.backend.sadd(tpl.bucket % self.bucket.name, self.name) mimicdb.backend.hmset(tpl.key % (self.bucket.name, self.name), dict(size=self.size, md5=self....
Called internally for any type of upload. After upload finishes, make sure the key is in the bucket set and save the metadata.
352,512
def parseMemory(memAttribute): mem = memAttribute.replace(, ).split() if mem[1] == : return float(mem[0]) else: raise RuntimeError()
Returns EC2 'memory' string as a float. Format should always be '#' GiB (example: '244 GiB' or '1,952 GiB'). Amazon loves to put commas in their numbers, so we have to accommodate that. If the syntax ever changes, this will raise. :param memAttribute: EC2 JSON memory param string. :return: A float...
352,513
def rubricator(self, **kwargs): return self._rubricator(**kwargs)
Rubrics search http://api.2gis.ru/doc/firms/list/rubricator/
352,514
def add_aberration(position, velocity, light_time): p1mag = light_time * C_AUDAY vemag = length_of(velocity) beta = vemag / C_AUDAY dot = dots(position, velocity) cosd = dot / (p1mag * vemag) gammai = sqrt(1.0 - beta * beta) p = beta * cosd q = (1.0 + p / (1.0 + gammai)) * light_ti...
Correct a relative position vector for aberration of light. Given the relative `position` [x,y,z] of an object (AU) from a particular observer, the `velocity` [dx,dy,dz] at which the observer is traveling (AU/day), and the light propagation delay `light_time` to the object (days), this function updates...
352,515
def build_packet(packet_type, gateway, bulb, payload_fmt, *payload_args, **kwargs): protocol = kwargs.get(, COMMAND_PROTOCOL) packet_fmt = BASE_FORMAT + payload_fmt packet_size = struct.calcsize(packet_fmt) return struct.pack(packet_fmt, packet_size, ...
Constructs a Lifx packet, returning a bytestring. The arguments are as follows: - `packet_type`, an integer - `gateway`, a 6-byte string containing the mac address of the gateway bulb - `bulb`, a 6-byte string containing either the mac address of the target bulb or `ALL_BULBS` - `payload_fmt`...
352,516
def _get_theme_label(catalog, theme): try: label = catalog.get_theme(identifier=theme)[] except BaseException: try: label = catalog.get_theme(label=theme)[] except BaseException: raise ce.ThemeNonExistentError(theme) label = re.sub(r, , ...
Intenta conseguir el theme por id o por label.
352,517
def interp_data(self, latitude, longitude, utc_time, param): nctime = self.data[] ilat, ilon = self.get_nearest_indices(latitude, longitude) before = netCDF4.date2index(utc_time, nctime, select=) fbefore = self.data[param][before, ilat, ilon] fafter = self.dat...
Interpolate ``param`` values to ``utc_time`` using indices nearest to (``latitude, longitude``). Parmaeters ---------- latitude : float Latitude in degrees longitude : float Longitude in degrees utc_time : datetime.datetime or datetime.date ...
352,518
def derive_toctree_rst(self, current_file): TAB = " " * 4 lines = list() lines.append(".. toctree::") for opt in TocTree.option_spec: value = self.options.get(opt) if value is not None: lines.append(("{}:{}: {}".format(TAB, opt, value)).rs...
Generate the rst content:: .. toctree:: args ... example.rst ... :param current_file: :return:
352,519
def parse_content_stream(page_or_stream, operators=): if not isinstance(page_or_stream, Object): raise TypeError("stream must a PDF object") if ( page_or_stream._type_code != ObjectType.stream and page_or_stream.get() != ): raise TypeError("parse_content_stream called...
Parse a PDF content stream into a sequence of instructions. A PDF content stream is list of instructions that describe where to render the text and graphics in a PDF. This is the starting point for analyzing PDFs. If the input is a page and page.Contents is an array, then the content stream is aut...
352,520
def add_edge(self, u, v, **kwargs): if u in self.nodes() and v in self.nodes() and nx.has_path(self, u, v): raise ValueError( .format(u=str(u), v=str(v))) super(JunctionTree, self).add_edge(u, v, **kwargs)
Add an edge between two clique nodes. Parameters ---------- u, v: nodes Nodes can be any list or set or tuple of nodes forming a clique. Examples -------- >>> from pgmpy.models import JunctionTree >>> G = JunctionTree() >>> G.add_nodes_from([...
352,521
def lookup_symbol(self, symbol, as_of_date, fuzzy=False, country_code=None): if symbol is None: raise TypeError("Cannot lookup asset for symbol of None for " "as of date %s." ...
Lookup an equity by symbol. Parameters ---------- symbol : str The ticker symbol to resolve. as_of_date : datetime or None Look up the last owner of this symbol as of this datetime. If ``as_of_date`` is None, then this can only resolve the equity ...
352,522
def submit_post_searchquery(url, data, apikey): s API endpoints. Returns ------- (status_flag, data_dict, dataset_id) : tuple This returns a tuple containing the status of the request: (, , , etc.), a dict parsed from the JSON result of the request, and a dataset ID, which can ...
This submits a POST query to an LCC-Server search API endpoint. Handles streaming of the results, and returns the final JSON stream. Also handles results that time out. Parameters ---------- url : str The URL of the search API endpoint to hit. This is something like `https://data....
352,523
def rollback(self): LOG.debug( "OplogThread: Initiating rollback sequence to bring " "system into a consistent state." ) last_docs = [] for dm in self.doc_managers: dm.commit() last_docs.append(dm.get_last_doc()) ...
Rollback target system to consistent state. The strategy is to find the latest timestamp in the target system and the largest timestamp in the oplog less than the latest target system timestamp. This defines the rollback window and we just roll these back until the oplog and target syst...
352,524
def set_data(self, image): data = np.asarray(image) if self._data is None or self._data.shape != data.shape: self._need_vertex_update = True self._data = data self._need_texture_upload = True
Set the data Parameters ---------- image : array-like The image data.
352,525
def forwards(self, orm): "Write your forwards methods here." for c in orm["contenttypes.contenttype"].objects.all(): if c.app_label == "DublinCore": c.app_label = "dublincore" c.save()
Write your forwards methods here.
352,526
def suppress_keyboard_interrupt_message(): old_excepthook = sys.excepthook def new_hook(type, value, traceback): if type != KeyboardInterrupt: old_excepthook(type, value, traceback) else: sys.exit(130) sys.excepthook = new_hook
Register a new excepthook to suppress KeyboardInterrupt exception messages, and exit with status code 130.
352,527
def decTimeToDeg(sign_sym, deg, min, sec): if sign_sym == -1 or sign_sym == : sign = -1 else: sign = 1 return dmsToDeg(sign, deg, min, sec)
Convert dec sign, degrees, minutes, seconds into a signed angle in degrees. ``sign_sym`` may represent negative as either '-' or numeric -1.
352,528
def save_png_bytes_io(self): bytearr = QtCore.QByteArray() buf = QtCore.QBuffer(bytearr) buf.open(QtCore.QIODevice.WriteOnly) self.contents.save(buf, "PNG") bio = io.BytesIO(bytearr.data()) img = Image.open(bio) img = img.resize((self.screen_size...
Save contents as PNG format file(BytesIO object) Note: DPI is platform dependent due to QPaintDevice DPI handling. Mac -> 72dpi, Ubuntu -> 96dpi
352,529
def status(self): if in self.engine.data: if self.engine.sandbox_type == : return False return True return False
Status of sandbox on this engine :rtype: bool
352,530
def deprecated(message: str): assert isinstance(message, str), "The deprecated decorator requires a message string argument." def decorator(func): @wraps(func) def wrapper(*args, **kwargs): warnings.warn(f"`{func.__qualname__}` is deprecated. {message}", ...
A decorator for marking functions as deprecated.
352,531
def transform(self, transformer, bigdl_type="float"): self.value = callBigDlFunc(bigdl_type, "transformImageFrame", transformer, self.value) return self
transformImageFrame
352,532
def stats_set_tag(self, key, value=1): if not self._measurement: if not self.IGNORE_OOB_STATS: self.logger.warning() return self._measurement.set_tag(key, value)
Set the specified tag/value in the per-message measurements .. versionadded:: 3.13.0 .. note:: If this method is called when there is not a message being processed, a message will be logged at the ``warning`` level to indicate the value is being dropped. To suppress these warni...
352,533
def _get_token_from_cookies(self, request, refresh_token): if refresh_token: cookie_token_name_key = "cookie_refresh_token_name" else: cookie_token_name_key = "cookie_access_token_name" cookie_token_name = getattr(self.config, cookie_token_name_key) retur...
Extract the token if present inside the request cookies.
352,534
def is_multisig_address(addr, blockchain=, **blockchain_opts): if blockchain == : return btc_is_multisig_address(addr, **blockchain_opts) else: raise ValueError(.format(blockchain))
Is the given address a multisig address?
352,535
def write(self, data, debug_info=None): self.num_write_bytes += len(data) if self.debug: if not debug_info: debug_info = str(len(data)) sys.stderr.write("%s: WRITE %s:\n%s\n" % ( self.__class__.__name__, debug_info, ...
Write data to YHSM device.
352,536
def gene_variants(institute_id): page = int(request.form.get(, 1)) institute_obj = institute_and_case(store, institute_id) if(request.method == "POST"): form = GeneVariantFiltersForm(request.form) else: form = GeneVariantFiltersForm(request.args) variant_type = form....
Display a list of SNV variants.
352,537
def create(self, name_or_class, mask, filepath=None, **kwargs): if isinstance(name_or_class, type): name = name_or_class.type protocol = name_or_class else: name = name_or_class protocol = self.protocols[name] assert name in DCC_TYPES ...
Create a new DCC connection. Return an ``asyncio.Protocol``
352,538
def launch_background_job(self, job, on_error=None, on_success=None): if not self.main.mode_online: self.sortie_erreur_GUI( "Local mode activated. Can't run background task !") self.reset() return on_error = on_error or self.sortie_erreur_GUI...
Launch the callable job in background thread. Succes or failure are controlled by on_error and on_success
352,539
def base_flow_index(q, freq=): r m7 = q.rolling(time=7, center=True).mean().resample(time=freq) mq = q.resample(time=freq) m7m = m7.min(dim=) return m7m / mq.mean(dim=)
r"""Base flow index Return the base flow index, defined as the minimum 7-day average flow divided by the mean flow. Parameters ---------- q : xarray.DataArray Rate of river discharge [m³/s] freq : str, optional Resampling frequency Returns ------- xarray.DataArrray B...
352,540
def query(self, sql, **kwargs): if not in kwargs or kwargs[] == : resp = self.get(, data={: sql, : }).json() if len(resp) == 0: return pd.DataFrame() else: return pd.DataFrame.from_records(resp[1:], columns=resp[0], ...
Shortcut for GET /v1/query, except with argument format='dataframe' (the default), in which case it will simply wrap the result of the GET query to /v1/query (with format='table') in a `pandas.DataFrame`.
352,541
def reconnectUnitSignalsToModel(synthesisedUnitOrIntf, modelCls): obj = synthesisedUnitOrIntf subInterfaces = obj._interfaces if subInterfaces: for intf in subInterfaces: reconnectUnitSignalsToModel(intf, modelCls) else: s = synthesis...
Reconnect model signals to unit to run simulation with simulation model but use original unit interfaces for communication :param synthesisedUnitOrIntf: interface where should be signals replaced from signals from modelCls :param modelCls: simulation model form where signals for synthesised...
352,542
def _get_y(self, kwargs): if in kwargs: return round(float(kwargs[]), 6) elif self._element_y in kwargs: return round(float(kwargs[self._element_y]), 6) elif self._type == 3 and self._element_1my in kwargs: return round(1. - float(kwargs[self._elemen...
Returns y if it is explicitly defined in kwargs. Otherwise, raises TypeError.
352,543
def get_password(self): password = self.get_as_nullable_string("password") password = password if password != None else self.get_as_nullable_string("pass") return password
Get the user password. The value can be stored in parameters "password" or "pass". :return: the user password.
352,544
def retype_file(src, pyi_dir, targets, *, quiet=False, hg=False): with tokenize.open(src) as src_buffer: src_encoding = src_buffer.encoding src_node = lib2to3_parse(src_buffer.read()) try: with open((pyi_dir / src.name).with_suffix()) as pyi_file: pyi_txt = pyi_file.read...
Retype `src`, finding types in `pyi_dir`. Save in `targets`. The file should remain formatted exactly as it was before, save for: - annotations - additional imports needed to satisfy annotations - additional module-level names needed to satisfy annotations Type comments in sources are normalized t...
352,545
def system(**kwargs): params = [] params += [FloatParameter(qualifier=, value=kwargs.get(, 0.0), default_unit=u.d, description=)] return ParameterSet(params)
Generally, this will automatically be added to a newly initialized :class:`phoebe.frontend.bundle.Bundle` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly created :class:`phoebe.parameters.parameters.Par...
352,546
def _nargs_validator(nargs, message): if message is None: message = "Registered function must take exactly %d arguments" % nargs def f(key, value): del key spec = inspect.getfullargspec(value) if (len(spec.args) != nargs or spec.varargs is not None or spec.varkw is not None): raise...
Makes validator for function to ensure it takes nargs args.
352,547
def last_error(self): if not len(self.log): raise RuntimeError() try: errs = [l for l in self.log if l[1] != 0] return errs[-1][2] except IndexError: return
Get the output of the last command exevuted.
352,548
def _on_add_route(self, msg): if msg.is_dead: return target_id_s, _, target_name = bytes_partition(msg.data, b()) target_name = target_name.decode() target_id = int(target_id_s) self.router.context_by_id(target_id).name = target_name stream = self.ro...
Respond to :data:`mitogen.core.ADD_ROUTE` by validating the source of the message, updating the local table, and propagating the message upwards.
352,549
def increase_in_list(list_to_increase, string_to_increase): if (bool(list_to_increase)) and (bool(string_to_increase)): if CommonFunctions.in_list(list_to_increase, string_to_increase): return list_to_increase return list_to_increase + + string_to_increase ...
Increase a item in a HTML list. :param list_to_increase: The list. :type list_to_increase: str :param string_to_increase: The value of item. :type string_to_increase: str :return: The HTML list with the item added, if the item not was contained in list. ...
352,550
def task(self, queue: str = , **kwargs: Any) -> Callable: def wrapper(f: Callable) -> Task: return Task(f, self, queue, **kwargs) return wrapper
Wrap functions with this decorator to convert them to *tasks*. After wrapping, calling the function will send a message to a queue instead of running the function. :param queue: Queue name for the tasks. :param kwargs: Keyword arguments will be passed to :class:`~kuyruk.Task...
352,551
def _zscore(a): assert a.ndim > 1, zscore = scipy.stats.zscore(a, axis=0) zscore[:, np.logical_not(np.all(np.isfinite(zscore), axis=0))] = 0 return zscore
Calculating z-score of data on the first axis. If the numbers in any column are all equal, scipy.stats.zscore will return NaN for this column. We shall correct them all to be zeros. Parameters ---------- a: numpy array Returns ------- zscore: numpy array The z-s...
352,552
def entropy(self): if self.k < self.n: _, entropy = binaryEntropy(self.dutyCycle) return entropy else: return 0
Returns the current total entropy of this layer
352,553
def set_url(self, url = None): if url is None or type(url) is not str: raise KPError("Need a new image number") else: self.url = url self.last_mod = datetime.now().replace(microsecond=0) return True
This method is used to set the url. url must be a string.
352,554
def _parse_status(self, status): m = rented_regex.search(status) if m: self.status = HouseStatus.RENTED self.owner = m.group("owner") self.owner_sex = Sex.MALE if m.group("pronoun") == "He" else Sex.FEMALE self.paid_until = parse_tibia_datetime(m....
Parses the house's state description and applies the corresponding values Parameters ---------- status: :class:`str` Plain text string containing the current renting state of the house.
352,555
def discoverable(dev): * if dev not in address_(): raise CommandExecutionError( ) cmd = .format(dev) __salt__[](cmd).splitlines() cmd = .format(dev) out = __salt__[](cmd) if in out: return True return False
Enable this bluetooth device to be discoverable. CLI Example: .. code-block:: bash salt '*' bluetooth.discoverable hci0
352,556
def create_project_with_docs( client, docs, language, name, account=None, progress=False ): description = .format(time.asctime()) if account is not None: proj_record = client.post( , name=name, language=language, description=description, ...
Given an iterator of documents, upload them as a Luminoso project.
352,557
def validate(self, message, schema_name): err = None try: jsonschema.validate(message, self.schemas[schema_name]) except KeyError: msg = (f f) err = {: msg} except jsonschema.ValidationError as e: msg = (f ...
Validate a message given a schema. Args: message (dict): Loaded JSON of pulled message from Google PubSub. schema_name (str): Name of schema to validate ``message`` against. ``schema_name`` will be used to look up schema from :py:attr:`.Me...
352,558
def merge_into_profile_extension(self, profile_extension, record_data, match_column, insert_on_no_match, update_on_match): profile_extension = profile_extension.get_soap_object(self.client) record_data = record_data.get_soap_object(self.client) resul...
Responsys.mergeIntoProfileExtension call Accepts: InteractObject profile_extension RecordData record_data string match_column string insert_on_no_match string update_on_match Returns a RecipientResult
352,559
def _gitignore(root): gitignore_path = os.path.join(root, ) dir_patterns = [] file_patterns = [] if not os.path.exists(gitignore_path): return (dir_patterns, file_patterns) with open(gitignore_path, , encoding=) as f: for line in f.readlines(): line = line.strip(...
Parses a .gitignore file and returns patterns to match dirs and files. Only basic gitignore patterns are supported. Pattern negation, ** wildcards and anchored patterns are not currently implemented. :param root: A unicode string of the path to the git repository :return: A 2-element t...
352,560
def get_dict_diff_str(d1, d2, title): added, removed, changed = get_dict_diff(d1, d2) lines = [title] if added: lines.append("Added attributes: %s" % [.join(x) for x in added]) if removed: lines.append("Removed attributes: %s" % [.join(x) f...
Returns same as `get_dict_diff`, but as a readable string.
352,561
def _handle_multiple_svcallers(data, stage): svs = get_svcallers(data) if stage == "ensemble" and dd.get_svprioritize(data): svs.append("prioritize") out = [] for svcaller in svs: if svcaller in _get_callers([data], stage): base = copy.deepcopy(data) ...
Retrieve configured structural variation caller, handling multiple.
352,562
def GetFilename(multiple=False, sep=, **kwargs): args = [] if multiple: args.append() if sep != : args.append( % sep) for generic_args in kwargs_helper(kwargs): args.append( % generic_args) p = run_zenity(, *args) if p.wait() == 0: return p.stdout.rea...
Prompt the user for a filename. This will raise a Zenity File Selection Dialog. It will return a list with the selected files or None if the user hit cancel. multiple - True to allow the user to select multiple files. sep - Token to use as the path separator when parsing Zenity's return ...
352,563
def format_escape( foreground=None, background=None, bold=False, faint=False, italic=False, underline=False, blink=False, inverted=False ): fg_format = None if isinstance( foreground, int ): fg_format = ANSI_FORMAT_FOREGROUND_XTERM_CMD.format( foreground ) else: fg_rgba = colour.nor...
Returns the ANSI escape sequence to set character formatting. foreground Foreground colour to use. Accepted types: None, int (xterm palette ID), tuple (RGB, RGBA), Colour background Background colour to use. Accepted types: None, int (xterm palette ID), tuple (RGB, RGBA), Colou...
352,564
def connect(self, A, B, distance=1): self.connect1(A, B, distance) if not self.directed: self.connect1(B, A, distance)
Add a link from A and B of given distance, and also add the inverse link if the graph is undirected.
352,565
def _get(self, url, params=None): if not params: params = {} params.update({: self.login, : self.key}) response_json = requests.get(self.api_url + url, params).json() return self._process_response(response_json)
Used by every other method, it makes a GET request with the given params. Args: url (str): relative path of a specific service (account_info, ...). params (:obj:`dict`, optional): contains parameters to be sent in the GET request. Returns: dict: results of the respo...
352,566
def _on_request(self, name, args): if IS_PYTHON3: name = decode_if_bytes(name) handler = self._request_handlers.get(name, None) if not handler: msg = self._missing_handler_error(name, ) error(msg) raise ErrorResponse(msg) debug(, ...
Handle a msgpack-rpc request.
352,567
def template_subs_file(in_file, out_fobj, d): with open(in_file, ) as in_fobj: for line in in_fobj: out_fobj.write(line.format(**d))
Substitute template arguments in in_file from variables in d, write the result to out_fobj.
352,568
def step(self, count=1): return self._client.send(step=sc_pb.RequestStep(count=count))
Step the engine forward by one (or more) step.
352,569
def getOffsetFromRva(self, rva): offset = -1 s = self.getSectionByRva(rva) if s != offset: offset = (rva - self.sectionHeaders[s].virtualAddress.value) + self.sectionHeaders[s].pointerToRawData.value else: offset = rva return off...
Converts an offset to an RVA. @type rva: int @param rva: The RVA to be converted. @rtype: int @return: An integer value representing an offset in the PE file.
352,570
def DumpAsCSV (self, separator=",", file=sys.stdout): for row in range(1, self.maxRow + 1): sep = "" for column in range(1, self.maxColumn + 1): file.write("%s\"%s\"" % (sep, self.GetCellValue(column, r...
dump as a comma separated value file
352,571
def azimuth2rake(strike, dip, azimuth): plunge, bearing = plane_intersection(strike, dip, azimuth, 90) rake = project_onto_plane(strike, dip, plunge, bearing) return rake
Projects an azimuth of a linear feature onto a plane as a rake angle. Parameters ---------- strike, dip : numbers The strike and dip of the plane in degrees following the right-hand-rule. azimuth : numbers The azimuth of the linear feature in degrees clockwise from north (i.e. ...
352,572
def _load_lexers(module_name): mod = __import__(module_name, None, None, []) for lexer_name in mod.__all__: cls = getattr(mod, lexer_name) _lexer_cache[cls.name] = cls
Load a lexer (and all others in the module too).
352,573
def imshow(self, canvas, X, extent=None, label=None, vmin=None, vmax=None, **kwargs): raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")
Show the image stored in X on the canvas. The origin of the image show is (0,0), such that X[0,0] gets plotted at [0,0] of the image! the kwargs are plotting library specific kwargs!
352,574
def show_xys(self, xs, ys, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs): "Show the `xs` (inputs) and `ys`(targets) on a figure of `figsize`." axs = subplots(len(xs), 2, imgsize=imgsize, figsize=figsize) for i, (x,y) in enumerate(zip(xs,ys)): x.show(ax=axs[i,0], **...
Show the `xs` (inputs) and `ys`(targets) on a figure of `figsize`.
352,575
def get(self, channel_sid): return UserChannelContext( self._version, service_sid=self._solution[], user_sid=self._solution[], channel_sid=channel_sid, )
Constructs a UserChannelContext :param channel_sid: The SID of the Channel that has the User Channel to fetch :returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelContext
352,576
def pprint(o, stream=None, indent=1, width=80, depth=None): printer = PrettyPrinter( stream=stream, indent=indent, width=width, depth=depth) printer.pprint(o)
Pretty-print a Python o to a stream [default is sys.stdout].
352,577
def _get_covered_instructions(self) -> int: total_covered_instructions = 0 for _, cv in self.coverage.items(): total_covered_instructions += sum(cv[1]) return total_covered_instructions
Gets the total number of covered instructions for all accounts in the svm. :return:
352,578
def set_seqs(self, a, b): self.set_seq1(a) self.set_seq2(b) self._reset_object()
Specify two alternative sequences -- reset any cached values.
352,579
def create_instance(self, image_id, pem_file, group_ids, instance_type, volume_type=, ebs_optimized=False, instance_monitoring=False, iam_profile=, tag_list=None, auction_bid=0.0): title = % self.__class__.__name__ input_fields = { : image_id, : pem_file, ...
a method for starting an instance on AWS EC2 :param image_id: string with aws id of image for instance :param pem_file: string with path to pem file to access image :param group_ids: list with aws id of security group(s) to attach to instance :param instance_type: string wi...
352,580
def is_time_included(self, time): if self._timestamps_data is None: self._calculate_timestamps() return time.moy in self._timestamps_data
Check if time is included in analysis period. Return True if time is inside this analysis period, otherwise return False Args: time: A DateTime to be tested Returns: A boolean. True if time is included in analysis period
352,581
def _set_text_from_file_dialog(self, text): text = os.path.relpath(text, ".") self.edit.setText(text) self.dialog_path = text self._act_on_change()
Sets text making it a **relative path**
352,582
def remove_user_from_group(self, username, group_name): log.warning() url = params = {: group_name, : username} return self.delete(url, params=params)
Remove given user from a group :param username: str :param group_name: str :return:
352,583
def without_apps(*apps): apps_list = [a for a in settings.INSTALLED_APPS if a not in apps] return override_settings(INSTALLED_APPS=apps_list)
Class decorator that makes sure the passed apps are not present in INSTALLED_APPS.
352,584
def format_x_tick(axis, major_locator=None, major_formatter=None, minor_locator=None, minor_formatter=None): if major_locator: axis.xaxis.set_major_locator(major_locator) if major_formatter: axis.xaxis.set_major_formatt...
Set x axis's format. This method is designed for time axis. **中文文档** 设置X轴格式。
352,585
def render_syntax_error( project: , error: SyntaxError ) -> dict: return render_error( project=project, error=error, stack=[dict( filename=getattr(error, ), location=None, line_number=error.lineno, line=error.text.rstrip()...
Renders a SyntaxError, which has a shallow, custom stack trace derived from the data included in the error, instead of the standard stack trace pulled from the exception frames. :param project: Currently open project. :param error: The SyntaxError to be rendered to html and text for dis...
352,586
def max_diff(dset1,dset2): re probably the same datasetError: Could not find file: %sinfError: Could not read files %s and %sinfignoreignoreinf')
calculates maximal voxel-wise difference in datasets (in %) Useful for checking if datasets have the same data. For example, if the maximum difference is < 1.0%, they're probably the same dataset
352,587
def save(self): if len(self) == 0: return [] mdl = self.getModel() return mdl.saver.save(self)
save - Save all objects in this list
352,588
def _create_if_necessary(directory): if not os.path.isabs(directory): log.debug("Got non-absolute path: %s" % directory) directory = os.path.abspath(directory) if not os.path.isdir(directory): log.info("Creating directory: %s" % directory) try: os.makedirs(dire...
Create the specified directory, if necessary. :param str directory: The directory to use. :rtype: bool :returns: True if no errors occurred and the directory was created or existed beforehand, False otherwise.
352,589
def set_debug_level(self, level): yield from self._hypervisor.send(.format(name=self._name, level=level))
Sets the debug level for this router (default is 0). :param level: level number
352,590
def _request(self, proxy, timeout): return request.WPToolsRequest(self.flags[], self.flags[], proxy, timeout)
Returns WPToolsRequest object
352,591
def create_all(self): ret = [] for vm_name, vm_details in six.iteritems(self.opts[]): ret.append( {vm_name: self.create(vm_details)} ) return ret
Create/Verify the VMs in the VM data
352,592
def summarize_vc(items): items = [utils.to_single_data(x) for x in utils.flatten(items)] items = [_normalize_vc_input(x) for x in items] items = validate.summarize_grading(items) items = [utils.to_single_data(x) for x in items] out = {"validate": validate.combine_validations(items), ...
CWL target: summarize variant calls and validation for multiple samples.
352,593
def get_dict_repr(self): return dict( phase_name = self.phase_name, phase_type = self.phase_type, actions = self.actions )
Return a dictionary representation of this phase. This will be used for checksumming, in order to uniquely compare instance images against their requirements
352,594
def _verify_state(self, resp, state_data, state): is_known_state = "state" in resp and "state" in state_data and resp["state"] == state_data["state"] if not is_known_state: received_state = resp.get("state", "") satosa_logging(logger, logging.DEBUG, ...
Will verify the state and throw and error if the state is invalid. :type resp: AuthorizationResponse :type state_data: dict[str, str] :type state: satosa.state.State :param resp: The authorization response from the AS, created by pyoidc. :param state_data: The state data for thi...
352,595
def send(self, attachment_failure=False): if not self.config[]: self.shutit.log(,level=logging.INFO) return True msg = self.__compose() mailto = [self.config[]] smtp = self.__get_smtp() if self.config[] != : smtp.login(self.config[], self.config[]) if self.config[]: mailto.append(self.config[...
Send the email according to the configured setup attachment_failure - used to indicate a recursive call after the smtp server has refused based on file size. Should not be used externally
352,596
def cmpabs(op1, op2): op1 = BigFloat._implicit_convert(op1) op2 = BigFloat._implicit_convert(op2) if is_nan(op1) or is_nan(op2): raise ValueError("Cannot perform comparison with NaN.") return mpfr.mpfr_cmpabs(op1, op2)
Compare the absolute values of op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, and a negative value if op1 < op2. Both op1 and op2 are considered to their full own precision, which may differ. If one of the operands is NaN, raise ValueError. Note: This function may be useful ...
352,597
def _grid_col(self): tr = self._tr idx = tr.tc_lst.index(self) preceding_tcs = tr.tc_lst[:idx] return sum(tc.grid_span for tc in preceding_tcs)
The grid column at which this cell begins.
352,598
def _set_num_samples_collected(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={: []}, int_size=32), is_leaf=True, yang_name="num-samples-collected", rest_name="num-samples-collected", parent=self, ...
Setter method for num_samples_collected, mapped from YANG variable /mpls_state/lsp/auto_bandwidth/num_samples_collected (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_num_samples_collected is considered as a private method. Backends looking to populate this variabl...
352,599
def representatives(self, count=None, sorting=False): payload = {} if count is not None: payload[] = self._process_value(count, ) if sorting: payload[] = self._process_value(sorting, ) resp = self.call(, payload) representatives = resp.get() o...
Returns a list of pairs of representative and its voting weight :param count: Max amount of representatives to return :type count: int :param sorting: If true, sorts by weight :type sorting: bool :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.representatives() ...