Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
5,300
def main(): desc = parser = argparse.ArgumentParser(description=desc, prog=) parser.add_argument(, metavar=, choices=[, , , ], help=) parser.add_argument(, metavar=, choices=[, , , ], help=) desc ...
Entry point for the script
5,301
def get_and_alter(self, function): check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_get_and_alter_codec, function=self._to_data(function))
Alters the currently stored reference by applying a function on it on and gets the old value. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server...
5,302
def from_weight_map(cls, pixel_scale, weight_map): np.seterr(divide=) noise_map = 1.0 / np.sqrt(weight_map) noise_map[noise_map == np.inf] = 1.0e8 return NoiseMap(array=noise_map, pixel_scale=pixel_scale)
Setup the noise-map from a weight map, which is a form of noise-map that comes via HST image-reduction and \ the software package MultiDrizzle. The variance in each pixel is computed as: Variance = 1.0 / sqrt(weight_map). The weight map may contain zeros, in which cause the variances ...
5,303
def validate(self): if self.job_record is None: self.tree.timetable.assign_job_record(self) next_timeperiod = time_helper.increment_timeperiod(self.time_qualifier, self.timeperiod) has_younger_sibling = next_timeperiod in self.parent.children ...
method traverse tree and performs following activities: * requests a job record in STATE_EMBRYO if no job record is currently assigned to the node * requests nodes for reprocessing, if STATE_PROCESSED node relies on unfinalized nodes * requests node for skipping if it is daily node and all 24 of...
5,304
def find(self, resource, req, sub_resource_lookup): args = getattr(req, , request.args if request else {}) or {} source_config = config.SOURCES[resource] if args.get(): query = json.loads(args.get()) if not in query.get(, {}): _query = query.get...
Find documents for resource.
5,305
def solveConsAggShock(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,PermGroFac, PermGroFacAgg,aXtraGrid,BoroCnstArt,Mgrid,AFunc,Rfunc,wFunc,DeprFac): t handle cubic splines, nor can it calculate a value function. Parameters ---------- solution_next : ConsumerSolution The so...
Solve one period of a consumption-saving problem with idiosyncratic and aggregate shocks (transitory and permanent). This is a basic solver that can't handle cubic splines, nor can it calculate a value function. Parameters ---------- solution_next : ConsumerSolution The solution to the suc...
5,306
def get_position_d(self): data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(POSITION_KD_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) re...
Get the D value of the current PID for position
5,307
def discardID(self, idVal): for i in self: if i.id == idVal: self._collection.discard(i) return
Checks if the collected items contains the give _idVal_ and discards it if it is found, will not raise an exception if item is not found # Parameters _idVal_ : `str` > The discarded id string
5,308
def get_alignment_df(a_aln_seq, b_aln_seq, a_seq_id=None, b_seq_id=None): if len(a_aln_seq) != len(b_aln_seq): raise ValueError() if not a_seq_id: a_seq_id = if not b_seq_id: b_seq_id = a_aln_seq = ssbio.protein.sequence.utils.cast_to_str(a_aln_seq) b_aln_seq = ssbio...
Summarize two alignment strings in a dataframe. Args: a_aln_seq (str): Aligned sequence string b_aln_seq (str): Aligned sequence string a_seq_id (str): Optional ID of a_seq b_seq_id (str): Optional ID of b_aln_seq Returns: DataFrame: a per-residue level annotation of th...
5,309
def _load_values(self, db_key: str) -> dict: if self._db.type(db_key) == : db_values = self._db.lrange(db_key, 0, -1) for i, value in enumerate(db_values): try: db_values[i] = ast.literal_eval(value) except SyntaxError: ...
Load values from the db at the specified key, db_key. FIXME(BMo): Could also be extended to load scalar types (instead of just list and hash)
5,310
def addCases(self, tupesValStmnts): s = self for val, statements in tupesValStmnts: s = s.Case(val, statements) return s
Add multiple case statements from iterable of tuleles (caseVal, statements)
5,311
def search_playlist(self, playlist_name, quiet=False, limit=9): result = self.search(playlist_name, search_type=1000, limit=limit) if result[][] <= 0: LOG.warning(, playlist_name) raise SearchNotFound(.format(playlist_name)) else: playlists = result...
Search playlist by playlist name. :params playlist_name: playlist name. :params quiet: automatically select the best one. :params limit: playlist count returned by weapi. :return: a Playlist object.
5,312
def groupby(self, dimensions=None, container_type=None, group_type=None, **kwargs): if dimensions is None: dimensions = self.kdims if not isinstance(dimensions, (list, tuple)): dimensions = [dimensions] container_type = container_type if container_type else type...
Groups DynamicMap by one or more dimensions Applies groupby operation over the specified dimensions returning an object of type container_type (expected to be dictionary-like) containing the groups. Args: dimensions: Dimension(s) to group by container_type: Type...
5,313
def trigger(self, event, filter=None, update=None, documents=None, ids=None, replacements=None): if not self.has_trigger(event): return if documents is not None: pass elif ids is not None: documents = self.find_by_ids(ids, read_use="primary") ...
Trigger the after_save hook on documents, if present.
5,314
def Process(self, path): path = re.sub(self.SYSTEMROOT_RE, r"%systemroot%", path, count=1) path = re.sub(self.SYSTEM32_RE, r"%systemroot%\\system32", path, count=1) matches_iter = self.WIN_ENVIRON_REGEX.finditer(path) var_names = set(m.group(1).lower() for m in matches_iter) results = [path] ...
Processes a given path. Args: path: Path (as a string) to post-process. Returns: A list of paths with environment variables replaced with their values. If the mapping had a list of values for a particular variable, instead of just one value, then all possible replacements will be ...
5,315
def _set_af_vrf(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("af_vrf_name",af_vrf.af_vrf, yang_name="af-vrf", rest_name="vrf", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u: {u...
Setter method for af_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf (list) If this variable is read-only (config: false) in the source YANG file, then _set_af_vrf is considered as a private method. Backends looking to populate this variable should do...
5,316
def create_filename_parser(self, base_dir): if base_dir and self.file_pattern: file_pattern = os.path.join(base_dir, self.file_pattern) else: file_pattern = self.file_pattern return parser.Parser(file_pattern) if file_pattern else None
Create a :class:`trollsift.parser.Parser` object for later use.
5,317
def formatTextException(*args): format = lambda x: re.sub(r"^(\s+)", lambda y: "{0} ".format("." * len(y.group(0))), x.rstrip().expandtabs(4)) verbose = 10 cls, instance, trcback = args stack = foundations.exceptions.extract_stack(foundations.exceptions.get_inner_most_frame(tr...
Formats given exception as a text. :param \*args: Arguments. :type \*args: \* :return: Exception text. :rtype: unicode
5,318
def get_vlan_brief_output_vlan_vlan_name(self, **kwargs): config = ET.Element("config") get_vlan_brief = ET.Element("get_vlan_brief") config = get_vlan_brief output = ET.SubElement(get_vlan_brief, "output") vlan = ET.SubElement(output, "vlan") vlan_id_key = ET.Su...
Auto Generated Code
5,319
def _get_ip_address(self, request): ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None) if ipaddr: return ipaddr.split(",")[0].strip() return request.META.get("REMOTE_ADDR", "")
Get the remote ip address the request was generated from.
5,320
def init_logging(config): verbose = config.get("verbose", 3) enable_loggers = config.get("enable_loggers", []) if enable_loggers is None: enable_loggers = [] logger_date_format = config.get("logger_date_format", "%Y-%m-%d %H:%M:%S") logger_format = config.get( "logger_format",...
Initialize base logger named 'wsgidav'. The base logger is filtered by the `verbose` configuration option. Log entries will have a time stamp and thread id. :Parameters: verbose : int Verbosity configuration (0..5) enable_loggers : string list List of module logger ...
5,321
def delete_insight(self, project_key, insight_id): projectOwner, projectId = parse_dataset_key(project_key) try: self._insights_api.delete_insight(projectOwner, projectId, insight_id) ...
Delete an existing insight. :params project_key: Project identifier, in the form of projectOwner/projectId :type project_key: str :params insight_id: Insight unique id :type insight_id: str :raises RestApiException: If a server error occurs Examples ----...
5,322
def reset(self): self.clear() self._initialise() self.configspec = None self._original_configspec = None
Clear ConfigObj instance and restore to 'freshly created' state.
5,323
def to_bytes(string): assert isinstance(string, basestring) if sys.version_info[0] >= 3: if isinstance(string, str): return string.encode() else: return string else: if isinstance(string, unicode): return string.encode() else: ...
Convert a string (bytes, str or unicode) to bytes.
5,324
def get_list(self, size=100, startIndex=0, searchText="", sortProperty="", sortOrder=, status=): url = urljoin(BASEURL, "sites", "list") params = { : self.token, : size, : startIndex, : sortOrder, : status } if searc...
Request service locations Returns ------- dict
5,325
def on_module(self, node): out = None for tnode in node.body: out = self.run(tnode) return out
Module def.
5,326
def overlap(self, spectrum): swave = self.wave[np.where(self.throughput != 0)] s1, s2 = swave.min(), swave.max() owave = spectrum[0] o1, o2 = owave.min(), owave.max() if (s1 >= o1 and s2 <= o2): ans = elif (s2 < o1) or (o2 < s1): ans =...
Tests for overlap of this filter with a spectrum Example of full overlap: |---------- spectrum ----------| |------ self ------| Examples of partial overlap: : |---------- self ----------| |------ spectrum ------| |---- spectrum ----|...
5,327
def addTab(self, widget, *args): widget.dirty_changed.connect(self._on_dirty_changed) super(CodeEditTabWidget, self).addTab(widget, *args)
Re-implements addTab to connect to the dirty changed signal and setup some helper attributes. :param widget: widget to add :param args: optional addtional arguments (name and/or icon).
5,328
def get_value(self, key): try: return self.idb.get_value(key) except (KeyError, EnvironmentError): pass try: return self.directory.get_value(key) except (KeyError, EnvironmentError): pass try: return self.user.g...
Fetch the settings value with the highest precedence for the given key, or raise KeyError. Precedence: - IDB scope - directory scope - user scope - system scope type key: basestring rtype value: Union[basestring, int, float, List, Dict]
5,329
def pixel_width(self): return self.zoom_factor * ((self._finish - self._start) / self._resolution)
Width of the whole TimeLine in pixels :rtype: int
5,330
def as_dict(self): drepr = super(PlayMeta, self).as_dict() drepr["details"] = [meta.as_dict() for meta in self._metas] return drepr
Pre-serialisation of the meta data
5,331
def list_runner_book(self, market_id, selection_id, handicap=None, price_projection=None, order_projection=None, match_projection=None, include_overall_position=None, partition_matched_by_strategy_ref=None, customer_strategy_refs=None, currency_code=None, matched_since=...
Returns a list of dynamic data about a market and a specified runner. Dynamic data includes prices, the status of the market, the status of selections, the traded volume, and the status of any orders you have placed in the market :param unicode market_id: The unique id for the market ...
5,332
def increase_writes_in_units( current_provisioning, units, max_provisioned_writes, consumed_write_units_percent, log_tag): units = int(units) current_provisioning = float(current_provisioning) consumed_write_units_percent = float(consumed_write_units_percent) consumption_based_curre...
Increase the current_provisioning with units units :type current_provisioning: int :param current_provisioning: The current provisioning :type units: int :param units: How many units should we increase with :returns: int -- New provisioning value :type max_provisioned_writes: int :param max...
5,333
def write(self): return \ \ .format(self.qname, str(self.flag), self.rname, str(self.pos), str(self.mapq), ...
Return SAM formatted string Returns: str: SAM formatted string containing entire SAM entry
5,334
def tune(runner, kernel_options, device_options, tuning_options): results = [] cache = {} tuning_options["scaling"] = False bounds = get_bounds(tuning_options.tune_params) args = (kernel_options, tuning_options, runner, results, cache) opt_result = differential_evolution(_cost...
Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: kernel_tuner.interface.Options :param device_options...
5,335
def decode_event(self, log_topics, log_data): if not len(log_topics) or log_topics[0] not in self.event_data: raise ValueError() event_id_ = log_topics[0] event = self.event_data[event_id_] unindexed_...
Return a dictionary representation the log. Note: This function won't work with anonymous events. Args: log_topics (List[bin]): The log's indexed arguments. log_data (bin): The encoded non-indexed arguments.
5,336
def _get_uploaded_file(session, file_info, fragment_count=0): try: return session.query(UploadedFile).filter(UploadedFile.sha1 == file_info.sha1).one() except NoResultFound: new_instance = UploadedFile( sha1=file_info.sha1, file_name=file_...
:param session: locked session (with self._session_resource as >> session <<) :param file_info: contains file information to save or query :param fragment_count: amount of fragments associated to the file :return: an UploadedFile associated to the file_info
5,337
def entry_line_to_text(self, entry): line = [] if not entry._text: flags_text = self.flags_to_text(entry.flags) duration_text = self.duration_to_text(entry.duration) return .join( (flags_text, if flags_text else , entry.al...
Return the textual representation of an :class:`~taxi.timesheet.lines.Entry` instance. This method is a bit convoluted since we don't want to completely mess up the original formatting of the entry.
5,338
def from_bytes(cls, bitstream): packet = cls() if not isinstance(bitstream, ConstBitStream): if isinstance(bitstream, Bits): bitstream = ConstBitStream(auto=bitstream) else: bitstream = ConstBitStream(bytes=bitstream) ...
Parse the given packet and update properties accordingly
5,339
def _dens(self,R,z,phi=0.,t=0.): r2= R**2+z**2 if r2 != self.a2: return 0. else: return nu.infty
NAME: _dens PURPOSE: evaluate the density for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the surface density HISTORY: 2018-08-19 - W...
5,340
def create_async_sns_topic(self, lambda_name, lambda_arn): topic_name = get_topic_name(lambda_name) topic_arn = self.sns_client.create_topic( Name=topic_name)[] self.sns_client.subscribe( TopicArn=topic_arn, Protocol=, En...
Create the SNS-based async topic.
5,341
def problem_with_codon(codon_index, codon_list, bad_seqs): base_1 = 3 * codon_index base_3 = 3 * codon_index + 2 gene_seq = .join(codon_list) for bad_seq in bad_seqs: problem = bad_seq.search(gene_seq) if problem and problem.start() < base_3 and problem.end() > base_1: ...
Return true if the given codon overlaps with a bad sequence.
5,342
def thin_sum(cachedir, form=): thintar = gen_thin(cachedir) code_checksum_path = os.path.join(cachedir, , ) if os.path.isfile(code_checksum_path): with salt.utils.files.fopen(code_checksum_path, ) as fh: code_checksum = "".format(fh.read().strip()) else: code_checksum = ...
Return the checksum of the current thin tarball
5,343
def rate_limit_status(self): return bind_api( api=self, path=, payload_type=, allowed_param=[], use_cache=False )
:reference: https://developer.twitter.com/en/docs/developer-utilities/rate-limit-status/api-reference/get-application-rate_limit_status :allowed_param:'resources'
5,344
def get_views(self, item=None, key=None, option=None): if item is None: item_views = self.views else: item_views = self.views[item] if key is None: return item_views else: if option is None: return item_views[key] ...
Return the views object. If key is None, return all the view for the current plugin else if option is None return the view for the specific key (all option) else return the view fo the specific key/option Specify item if the stats are stored in a dict of dict (ex: NETWORK, FS...)
5,345
def push(self, cf): cf.next = self if self.state is not None: self.state.register_plugin(, cf) self.state.history.recent_stack_actions.append(CallStackAction( hash(cf), len(cf), , callframe=cf.copy({}, with_tail=False) )) return cf
Push the frame cf onto the stack. Return the new stack.
5,346
def infer_x(self, y): OptimizedInverseModel.infer_x(self, y) if self.fmodel.size() == 0: return self._random_x() x_guesses = [self._guess_x_simple(y)[0]] result = [] for xg in x_guesses: res = cma.fmin(self._error, xg, self.cmaes_sigma, ...
Infer probable x from input y @param y the desired output for infered x. @return a list of probable x
5,347
def _from_json_array_nested(cls, response_raw): json = response_raw.body_bytes.decode() obj = converter.json_to_class(dict, json) value = converter.deserialize(cls, obj[cls._FIELD_RESPONSE]) return client.BunqResponse(value, response_raw.headers)
:type response_raw: client.BunqResponseRaw :rtype: bunq.sdk.client.BunqResponse[cls]
5,348
def do_help(self, arg): if not arg: Cmd.do_help(self, arg) elif arg in (, ): print(" Help! I need somebody...") print(" Help! Not just anybody...") print(" Help! You know, I need someone...") print(" Heeelp!") ...
? - show the list of available commands ? * - show help for all commands ? <command> [command...] - show help for the given command(s) help - show the list of available commands help * - show help for all commands help <command> [command...] - show help for the given command(s)
5,349
def add_tracked_motors(self, tracked_motors): new_mockup_motors = map(self.get_mockup_motor, tracked_motors) self.tracked_motors = list(set(self.tracked_motors + new_mockup_motors))
Add new motors to the recording
5,350
def state(anon, obj, field, val): return anon.faker.state(field=field)
Returns a randomly selected US state code
5,351
def within_n_mads(n, series): mad_score = (series - series.mean()) / series.mad() return (mad_score.abs() <= n).all()
Return true if all values in sequence are within n MADs
5,352
def refresh(self, force_cache=False): if self.check_if_ok_to_update() or force_cache: for sync_name, sync_module in self.sync.items(): _LOGGER.debug("Attempting refresh of sync %s", sync_name) sync_module.refresh(force_cache=force_cache) if not fo...
Perform a system refresh. :param force_cache: Force an update of the camera cache
5,353
def _dataframe_fields(self): fields_to_include = { : self.assist_percentage, : self.assists, : self.block_percentage, : self.blocks, : self.box_plus_minus, : self.conference, : self.defensive_box_plus_minus, ...
Creates a dictionary of all fields to include with DataFrame. With the result of the calls to class properties changing based on the class index value, the dictionary should be regenerated every time the index is changed when the dataframe property is requested. Returns -------...
5,354
def words(content, filter=True, predicate=None): def accept_word(word): return len(word) > 2 \ and word.lower() not in stop_words \ and not _UNWANTED_WORDS_PATTERN.match(word) words = _tokenize(content) if filter or predicate: if not predicate: ...
\ Returns an iterable of words from the provided text. `content` A text. `filter` Indicates if stop words and garbage like "xxxxxx" should be removed from the word list. `predicate` An alternative word filter. If it is ``None`` "xxxx", "---", default stop wor...
5,355
def add_github_hook_options(parser): cookbook = parser.add_parser(, help= ) cookbook.add_argument(, action=, help=) cookbook.add_argument(, action=, help=) domain = socket.gethostname() example =...
Add the github jenkins hook command and arguments. :rtype: argparse.ArgumentParser
5,356
def fit_first_and_second_harmonics(phi, intensities): a1 = b1 = a2 = b2 = 1. def optimize_func(x): return first_and_second_harmonic_function( phi, np.array([x[0], x[1], x[2], x[3], x[4]])) - intensities return _least_squares_fit(optimize_func, [np.mean(intensities), a1, b1, ...
Fit the first and second harmonic function values to a set of (angle, intensity) pairs. This function is used to compute corrections for ellipse fitting: .. math:: f(phi) = y0 + a1*\\sin(phi) + b1*\\cos(phi) + a2*\\sin(2*phi) + b2*\\cos(2*phi) Parameters ---------- p...
5,357
def Update(self, menu=None, tooltip=None,filename=None, data=None, data_base64=None,): if menu is not None: self.Menu = menu qmenu = QMenu() qmenu.setTitle(self.Menu[0]) AddTrayMenuItem(qmenu, self.Menu[1], self) self.TrayIcon.setCont...
Updates the menu, tooltip or icon :param menu: menu defintion :param tooltip: string representing tooltip :param filename: icon filename :param data: icon raw image :param data_base64: icon base 64 image :return:
5,358
def normalize_enum_constant(s): if s.islower(): return s if s.isupper(): return s.lower() return "".join(ch if ch.islower() else "_" + ch.lower() for ch in s).strip("_")
Return enum constant `s` converted to a canonical snake-case.
5,359
def check_valid_cpc_status(method, uri, cpc): status = cpc.properties.get(, None) if status is None: return valid_statuses = [, , , ] if status not in valid_statuses: if uri.startswith(cpc.uri): raise ConflictError(method, uri, reason=1...
Check that the CPC is in a valid status, as indicated by its 'status' property. If the Cpc object does not have a 'status' property set, this function does nothing (in order to make the mock support easy to use). Raises: ConflictError with reason 1: The CPC itself has been targeted by the ...
5,360
def pretty_print_json(self, json_string): return json.dumps(self.string_to_json(json_string), indent=2, ensure_ascii=False)
Return formatted JSON string _json_string_.\n Using method json.dumps with settings: _indent=2, ensure_ascii=False_. *Args:*\n _json_string_ - JSON string. *Returns:*\n Formatted JSON string. *Example:*\n | *Settings* | *Value* | | Library | JsonVali...
5,361
def exclude_by_ends(in_file, exclude_file, data, in_params=None): params = {"end_buffer": 50, "rpt_pct": 0.9, "total_rpt_pct": 0.2, "sv_pct": 0.5} if in_params: params.update(in_params) assert in_file.endswith(".bed") out_file = "%s-norepeats%s" % u...
Exclude calls based on overlap of the ends with exclusion regions. Removes structural variants with either end being in a repeat: a large source of false positives. Parameters tuned based on removal of LCR overlapping false positives in DREAM synthetic 3 data.
5,362
def copy_and_disconnect_tree(root, machine): new_root = None new_lookup = {} broken_links = set() to_visit = deque([(None, None, root)]) while to_visit: new_parent, direction, old_node = to_visit.popleft() if old_node.chip in machine: ...
Copy a RoutingTree (containing nothing but RoutingTrees), disconnecting nodes which are not connected in the machine. Note that if a dead chip is part of the input RoutingTree, no corresponding node will be included in the copy. The assumption behind this is that the only reason a tree would visit a de...
5,363
def is_binary(path): if not os.path.isfile(path): return False try: with fopen(path, ) as fp_: try: data = fp_.read(2048) if six.PY3: data = data.decode(__salt_system_encoding__) return salt.utils.stringutils.is...
Detects if the file is a binary, returns bool. Returns True if the file is a bin, False if the file is not and None if the file is not available.
5,364
def format_item(x, timedelta_format=None, quote_strings=True): if isinstance(x, (np.datetime64, datetime)): return format_timestamp(x) if isinstance(x, (np.timedelta64, timedelta)): return format_timedelta(x, timedelta_format=timedelta_format) elif isinstance(x, (str, bytes)): r...
Returns a succinct summary of an object as a string
5,365
def close(self): try: try: self.connection.quit() except socket.sslerror: self.connection.close() except Exception as e: logger.error( "Error trying to clos...
Close the connection to the email server.
5,366
def metadata_path(self, m_path): if not m_path: self.metadata_dir = None self.metadata_file = None else: if not op.exists(m_path): raise OSError(.format(m_path)) if not op.dirname(m_path): self.metadata_dir = ...
Provide pointers to the paths of the metadata file Args: m_path: Path to metadata file
5,367
def structured_partlist(input, timeout=20, showgui=False): partvaluepartC1value1n s = raw_partlist(input=input, timeout=timeout, showgui=showgui) return parse_partlist(s)
export partlist by eagle, then parse it :param input: .sch or .brd file name :param timeout: int :param showgui: Bool, True -> do not hide eagle GUI :rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value':'1n'}, ..])
5,368
def parse_universe_description(self, description): sid1,sid2,sid2,...exchangeexchange,ntype:index:submarket self.raw_description = description description = description.split() self.exchange = description[0] n = int(description[1]) if len(description) == 2 else -1 self.s...
Semantic - 'sid1,sid2,sid2,...' - 'exchange' : every sids of the exchange - 'exchange,n' : n random sids of the exchange where exchange is a combination of 'type:index:submarket'
5,369
def find_matching_bracket_position(self, start_pos=None, end_pos=None): for A, B in , , , : if self.current_char == A: return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0 elif self.current_char == B: return self.find_enc...
Return relative cursor position of matching [, (, { or < bracket. When `start_pos` or `end_pos` are given. Don't look past the positions.
5,370
def get_data_record(self, brain, field_names): record = {} model = None for field_name in field_names: value = getattr(brain, field_name, None) if value is None: logger.warn("Not a metadata field: {}".format(field_name)...
Returns a dict with the column values for the given brain
5,371
def get_node_label(self, model): if model.is_proxy: label = "(P) %s" % (model.name.title()) else: label = "%s" % (model.name.title()) line = "" new_label = [] for w in label.split(" "): if len(line + w) > 15: new_label...
Defines how labels are constructed from models. Default - uses verbose name, lines breaks where sensible
5,372
def recreate_article_body(self): for foreign_id, body in iteritems(self.record_keeper.article_bodies): try: local_page_id = self.record_keeper.get_local_page(foreign_id) page = Page.objects.get(id=local_page_id).specific new_...
Handles case where article body contained page or image. Assumes all articles and images have been created.
5,373
def get_perceel_by_capakey(self, capakey): def creator(): url = self.base_url + % capakey h = self.base_headers p = { : , : , : } res = capakey_rest_gateway_request(url, h, p).json() ...
Get a `perceel`. :param capakey: An capakey for a `perceel`. :rtype: :class:`Perceel`
5,374
def safe_size(source): if source is None: return None total_bytes = 0 bytes = [] b = source.read(MIN_READ_SIZE) while b: total_bytes += len(b) bytes.append(b) if total_bytes > MAX_STRING_SIZE: try: data = FileString(TemporaryFile()) ...
READ THE source UP TO SOME LIMIT, THEN COPY TO A FILE IF TOO BIG RETURN A str() OR A FileString()
5,375
def get_config(): * profiles = {} curr = None cmd = [, , , ] ret = __salt__[](cmd, python_shell=False, ignore_retcode=True) if ret[] != 0: raise CommandExecutionError(ret[]) curr = None return profiles
Get the status of all the firewall profiles Returns: dict: A dictionary of all profiles on the system Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.get_config
5,376
def get_git_postversion(addon_dir): addon_dir = os.path.realpath(addon_dir) last_version = read_manifest(addon_dir).get(, ) last_version_parsed = parse_version(last_version) if not is_git_controlled(addon_dir): return last_version if get_git_uncommitted(addon_dir): uncommitted =...
return the addon version number, with a developmental version increment if there were git commits in the addon_dir after the last version change. If the last change to the addon correspond to the version number in the manifest it is used as is for the python package version. Otherwise a counter is incr...
5,377
def callback(self, timestamp, event_type, payload): try: data = (event_type, payload) LOG.debug( , ( {: event_type, : payload})) if in event_type: pri = self._create_pri elif in event_type:...
Callback method for processing events in notification queue. :param timestamp: time the message is received. :param event_type: event type in the notification queue such as identity.project.created, identity.project.deleted. :param payload: Contains information of an ...
5,378
def open_like(a, path, **kwargs): _like_args(a, kwargs) if isinstance(a, Array): kwargs.setdefault(, a.fill_value) return open_array(path, **kwargs)
Open a persistent array like `a`.
5,379
def get_additional_properties(self, _type, *args, **kwargs): if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) body = [] for sch in schema.nested_schemas: nested_schema = SchemaObjects.get(sch) if not (nest...
Make head and table with additional properties by schema_id :param str _type: :rtype: str
5,380
def detail_search(self, params, standardize=False): response = self._request(ENDPOINTS[], params) result_data = [] for person in response[]: try: detail = self.person_details(person[], standardize=standardize) ...
Get a detailed list of person objects for the given search params. :param params: Dictionary specifying the query parameters >>> people_detailed = d.detail_search({'first_name': 'tobias', 'last_name': 'funke'})
5,381
def dehydrate(self): result = {} for attr in self.attrs: result[attr] = getattr(self, attr) return result
Return a dict representing this bucket.
5,382
def heartbeat(request): all_checks = checks.registry.registry.get_checks( include_deployment_checks=not settings.DEBUG, ) details = {} statuses = {} level = 0 for check in all_checks: detail = heartbeat_check_detail(check) statuses[check.__name__] = detail[] ...
Runs all the Django checks and returns a JsonResponse with either a status code of 200 or 500 depending on the results of the checks. Any check that returns a warning or worse (error, critical) will return a 500 response.
5,383
def lbol_from_spt_dist_mag (sptnum, dist_pc, jmag, kmag, format=): bcj = bcj_from_spt (sptnum) bck = bck_from_spt (sptnum) n = np.zeros (sptnum.shape, dtype=np.int) app_mbol = np.zeros (sptnum.shape) w = np.isfinite (bcj) & np.isfinite (jmag) app_mbol[w] += jmag[w] + bcj[w] n[w] += 1 ...
Estimate a UCD's bolometric luminosity given some basic parameters. sptnum: the spectral type as a number; 8 -> M8; 10 -> L0 ; 20 -> T0 Valid values range between 0 and 30, ie M0 to Y0. dist_pc: distance to the object in parsecs jmag: object's J-band magnitude or NaN (*not* None) if unavailable k...
5,384
def template_from_file(basedir, path, vars): from cirruscluster.ext.ansible import utils realpath = utils.path_dwim(basedir, path) loader=jinja2.FileSystemLoader([basedir,os.path.dirname(realpath)]) environment = jinja2.Environment(loader=loader, trim_blocks=True) for filter_plugin in utils.pl...
run a file through the templating engine
5,385
def join(self, fm_new, minimal_subset=True): orig_fields = self._fields[:] for field in orig_fields: if not field in fm_new._fields: if minimal_subset: self.rm_field(field) else: ...
Adds content of a new Datamat to this Datamat. If a parameter of the Datamats is not equal or does not exist in one, it is promoted to a field. If the two Datamats have different fields then the elements for the Datamats that did not have the field will be NaN, unless 'minimal_...
5,386
def fetch_guilds(self, *, limit=100, before=None, after=None): return GuildIterator(self, limit=limit, before=before, after=after)
|coro| Retrieves an :class:`.AsyncIterator` that enables receiving your guilds. .. note:: Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. .. note:: This method is...
5,387
def emflx(self, area, wavelengths=None): t_lambda = self.tlambda(wavelengths=wavelengths) if t_lambda == 0: em_flux = 0.0 * units.FLAM else: uresp = self.unit_response(area, wavelengths=wavelengths) equvw = self.equivwidth(wavelengths=wavelengths)....
Calculate :ref:`equivalent monochromatic flux <synphot-formula-emflx>`. Parameters ---------- area, wavelengths See :func:`unit_response`. Returns ------- em_flux : `~astropy.units.quantity.Quantity` Equivalent monochromatic flux.
5,388
def parse(self, line=None): args = self.parser.parse_args(args=line) return args.func(args)
parses the line provided, if None then uses sys.argv
5,389
def _gatk_extract_reads_cl(data, region, prep_params, tmp_dir): args = ["PrintReads", "-L", region_to_gatk(region), "-R", dd.get_ref_file(data), "-I", data["work_bam"]] if "gatk4" in dd.get_tools_off(data): args = ["--analysis_type"] + args runner = broa...
Use GATK to extract reads from full BAM file.
5,390
def dataset_merge_method(dataset, other, overwrite_vars, compat, join): if isinstance(overwrite_vars, str): overwrite_vars = set([overwrite_vars]) overwrite_vars = set(overwrite_vars) if not overwrite_vars: objs = [dataset, other] priority_arg = None elif o...
Guts of the Dataset.merge method.
5,391
def get_section_key_line(self, data, key, opt_extension=): return super(GoogledocTools, self).get_section_key_line(data, key, opt_extension)
Get the next section line for a given key. :param data: the data to proceed :param key: the key :param opt_extension: an optional extension to delimit the opt value
5,392
def set_blink_rate(self, b): if b > 3: b = 0 self.firmata.i2c_write(self.board_address, (self.HT16K33_BLINK_CMD | self.HT16K33_BLINK_DISPLAYON | (b << 1)))
Set the user's desired blink rate (0 - 3) @param b: blink rate
5,393
def git_env(self): env = dict(os.environ) for var in ["HOME", "XDG_CONFIG_HOME"]: env.pop(var, None) env["GIT_CONFIG_NOSYSTEM"] = "true" env["GIT_INDEX_FILE"] = os.path.abspath(self.index_file) return env
Set the index file and prevent git from reading global configs.
5,394
def _ParseAndValidateRecord(self, parser_mediator, text_file_object): try: title = text_file_object.readline(size=self._MAXIMUM_LINE_SIZE) url = text_file_object.readline(size=self._MAXIMUM_LINE_SIZE) timestamp = text_file_object.readline(size=self._MAXIMUM_LINE_SIZE) popularity_index =...
Parses and validates an Opera global history record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. text_file_object (dfvfs.TextFile): text file. Returns: bool: True if the record was successfully parse...
5,395
def open(self, callback, instance=None, processor=None): assert not self._closed ws_url = self._client.ws_root if instance: ws_url += + instance if processor: ws_url += + processor self._callback = callback self._websocket = we...
Begin consuming messages. :param string instance: (Optional) instance to use in the WebSocket URL :param string processor: (Optional) processor to use in the WebSocket URL
5,396
def get_cache(self, decorated_function, *args, **kwargs): self.__check(decorated_function, *args, **kwargs) if decorated_function in self._storage: for i in self._storage[decorated_function]: if i[]() == args[0]: result = i[].cache_entry(*args, **kwargs) if self.__statistic is True: if res...
:meth:`WCacheStorage.get_cache` method implementation
5,397
def _unique_class_name(namespace: Dict[str, Any], uuid: uuid.UUID) -> str: count = 0 name = original_name = + uuid.hex while name in namespace: count += 1 name = original_name + + str(count) return name
Generate unique to namespace name for a class using uuid. **Parameters** :``namespace``: the namespace to verify uniqueness against :``uuid``: the "unique" portion of the name **Return Value(s)** A unique string (in namespace) using uuid.
5,398
def __get_git_bin(): git = alternatives = [ ] for alt in alternatives: if os.path.exists(alt): git = alt break return git
Get git binary location. :return: Check git location
5,399
def repr_setup(self, name=None, col_names=None, col_types=None): self._name = name or self._name self._col_types = col_types or self._col_types
This wasn't safe to pass into init because of the inheritance