Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
9,200
def featurecounts_stats_table(self): headers = OrderedDict() headers[] = { : , : , : 100, : 0, : , : } headers[] = { : .format(config.read_count_prefix), : .format(config.read_count...
Take the parsed stats from the featureCounts report and add them to the basic stats table at the top of the report
9,201
def argument_kind(args): kinds = set(arg.kind for arg in args) if len(kinds) != 1: return None return kinds.pop()
Return the kind of an argument, based on one or more descriptions of the argument. Return None if every item does not have the same kind.
9,202
def slackbuild(self, name, sbo_file): return URL(self.sbo_url + name + sbo_file).reading()
Read SlackBuild file
9,203
def _import_protobuf_from_file(grpc_pyfile, method_name, service_name = None): prefix = grpc_pyfile[:-12] pb2 = __import__("%s_pb2"%prefix) pb2_grpc = __import__("%s_pb2_grpc"%prefix) all_service_names = [stub_name[:-4] for stub_name in dir(pb2_grpc) if stub_name.endswith(...
helper function which try to import method from the given _pb2_grpc.py file service_name should be provided only in case of name conflict return (False, None) in case of failure return (True, (stub_class, request_class, response_class)) in case of success
9,204
def get(self, request): try: consent_record = self.get_consent_record(request) if consent_record is None: return self.get_no_record_response(request) except ConsentAPIRequestError as invalid_request: return Response({: str(invalid_request)}, s...
GET /consent/api/v1/data_sharing_consent?username=bob&course_id=id&enterprise_customer_uuid=uuid *username* The edX username from whom to get consent. *course_id* The course for which consent is granted. *enterprise_customer_uuid* The UUID of the enterprise cu...
9,205
def _parse_proc_mount(self): for line in fileops.readlines(): if not in line: continue items = line.split() path = items[1] opts = items[3].split() name = None for opt in opts: if opt i...
Parse /proc/mounts
9,206
def _is_and_or_ternary(node): return ( isinstance(node, astroid.BoolOp) and node.op == "or" and len(node.values) == 2 and isinstance(node.values[0], astroid.BoolOp) and not isinstance(node.values[1], astroid.BoolOp) and node.values...
Returns true if node is 'condition and true_value or false_value' form. All of: condition, true_value and false_value should not be a complex boolean expression
9,207
def sort_layout(thread, listfile, column=0): from jcvi.formats.base import DictFile outfile = listfile.rsplit(".", 1)[0] + ".sorted.list" threadorder = thread.order fw = open(outfile, "w") lt = DictFile(listfile, keypos=column, valuepos=None) threaded = [] imported = set() for t in...
Sort the syntelog table according to chromomomal positions. First orient the contents against threadbed, then for contents not in threadbed, insert to the nearest neighbor.
9,208
def construct_formset(self): formset_class = self.get_formset() if hasattr(self, ): klass = type(self).__name__ raise DeprecationWarning( .format(klass), ) return formset_class(**self.get_formset_kwarg...
Returns an instance of the formset
9,209
def list_patterns(refresh=False, root=None): * if refresh: refresh_db(root) return _get_patterns(root=root)
List all known patterns from available repos. refresh force a refresh if set to True. If set to False (default) it depends on zypper if a refresh is executed. root operate on a different root directory. CLI Examples: .. code-block:: bash salt '*' pkg.list_pat...
9,210
def attrs(self): ret = dict(self.__dict__) del ret["_matches"] if self.type != c.COMPUTER: del ret["difficulty"] return ret
provide a copy of this player's attributes as a dictionary
9,211
def parse(expected, query): return dict( (key, parser(query.get(key, []))) for key, parser in expected.items())
Parse query parameters. :type expected: `dict` mapping `bytes` to `callable` :param expected: Mapping of query argument names to argument parsing callables. :type query: `dict` mapping `bytes` to `list` of `bytes` :param query: Mapping of query argument names to lists of argument values, ...
9,212
def _linux_brdel(br): brctl = _tool_path() return __salt__[](.format(brctl, br), python_shell=False)
Internal, deletes the bridge
9,213
def reset(self): fetches = [] for processor in self.preprocessors: fetches.extend(processor.reset() or []) return fetches
Calls `reset` on all our Preprocessor objects. Returns: A list of tensors to be fetched.
9,214
def load_blotter_args(blotter_name=None, logger=None): if logger is None: logger = tools.createLogger(__name__, logging.WARNING) if blotter_name is not None: args_cache_file = tempfile.gettempdir() + "/" + blotter_name.lower() + ".qtpylib" if not os.path.exists(args_cache_fi...
Load running blotter's settings (used by clients) :Parameters: blotter_name : str Running Blotter's name (defaults to "auto-detect") logger : object Logger to be use (defaults to Blotter's) :Returns: args : dict Running Blotter's arguments
9,215
def nlargest(n, mapping): try: it = mapping.iteritems() except AttributeError: it = iter(mapping.items()) pq = minpq() try: for i in range(n): pq.additem(*next(it)) except StopIteration: pass try: while it: pq.pushpopitem(*next...
Takes a mapping and returns the n keys associated with the largest values in descending order. If the mapping has fewer than n items, all its keys are returned. Equivalent to: ``next(zip(*heapq.nlargest(mapping.items(), key=lambda x: x[1])))`` Returns ------- list of up to n keys from ...
9,216
def get_edge_type(self, edge_type): edges = [] for e in self.edges(): if self.adj[e[0]][e[1]].get() == edge_type: edges.append(e) return edges
Returns all edges with the specified edge type. Parameters ---------- edge_type : int An integer specifying what type of edges to return. Returns ------- out : list of 2-tuples A list of 2-tuples representing the edges in the graph wi...
9,217
def get_hdulist_idx(self, ccdnum): for (extno, hdu) in enumerate(self.hdulist): if ccdnum == int(hdu.header.get(, -1)) or str(ccdnum) in hdu.header.get(, ): return extno raise ValueError("Failed to find requested CCD Number {} in cutout {}".format(ccdnum, ...
The SourceCutout is a list of HDUs, this method returns the index of the HDU that corresponds to the given ccd number. CCDs are numbers from 0, but the first CCD (CCDNUM=0) is often in extension 1 of an MEF. @param ccdnum: the number of the CCD in the MEF that is being referenced. @return: the ...
9,218
def plot_cdf(fignum, data, xlab, sym, title, **kwargs): fig = plt.figure(num=fignum) sdata = [] for d in data: sdata.append(d) sdata.sort() X, Y = [], [] color = "" for j in range(len(sdata)): Y.append(old_div(float(j), float(len(sdata)))) X.append(s...
Makes a plot of the cumulative distribution function. Parameters __________ fignum : matplotlib figure number data : list of data to be plotted - doesn't need to be sorted sym : matplotlib symbol for plotting, e.g., 'r--' for a red dashed line **kwargs : optional dictionary with {'color': color...
9,219
def parse_django_adminopt_node(env, sig, signode): from sphinx.domains.std import option_desc_re count = 0 firstname = for m in option_desc_re.finditer(sig): optname, args = m.groups() if count: signode += addnodes.desc_addname(, ) signode += addnodes.desc_name(...
A copy of sphinx.directives.CmdoptionDesc.parse_signature()
9,220
def prime(self, key, value): cache_key = self.get_cache_key(key) if cache_key not in self._promise_cache: if isinstance(value, Exception): promise = Promise.reject(value) else: promise = Promise...
Adds the provied key and value to the cache. If the key already exists, no change is made. Returns itself for method chaining.
9,221
def content(self): answer_wrap = self.soup.find(, id=) content = answer_wrap.find(, class_=) content = answer_content_process(content) return content
以处理过的Html代码形式返回答案内容. :return: 答案内容 :rtype: str
9,222
def enable(self): logger.debug() self.options.enabled = True logger.info()
(Re)enable the cache
9,223
def fail(message, exception_data=None): print(message, file=sys.stderr) if exception_data: print(repr(exception_data)) sys.exit(1)
Print a failure message and exit nonzero
9,224
def get_installed_distributions(local_only=True, skip=stdlib_pkgs, include_editables=True, editables_only=False, user_only=False): if local_only: local_test = dist_is_loc...
Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``include_editables`` is False, d...
9,225
def _fill_empty_sessions(self, fill_subjects, fill_visits): if fill_subjects is None: fill_subjects = [s.id for s in self.subjects] if fill_visits is None: fill_visits = [v.id for v in self.complete_visits] for subject_id in fill_subjects: try: ...
Fill in tree with additional empty subjects and/or visits to allow the study to pull its inputs from external repositories
9,226
def _build_response(self): responses = [] self.event_urls = [] for index, event in enumerate(self.events): self.py3.threshold_get_color(index + 1, "event") self.py3.threshold_get_color(index + 1, "time") event_dict = {} event_dict["summ...
Builds the composite reponse to be output by the module by looping through all events and formatting the necessary strings. Returns: A composite containing the individual response for each event.
9,227
def _source_info(): ofi = inspect.getouterframes(inspect.currentframe())[2] try: calling_class = ofi[0].f_locals[].__class__ except KeyError: calling_class = None return ofi[1], ofi[2], calling_class, ofi[3]
Get information from the user's code (two frames up) to leave breadcrumbs for file, line, class and function.
9,228
def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), ), **kwargs): r predefined_args = {: 400, : 1150, : , : 3, : True, ...
r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'wikitex...
9,229
def workflow_script_reject(self): if skip(self, "reject"): return workflow = self.portal_workflow def copy_src_fields_to_dst(src, dst): ignore_fields = [ , , , , , ...
Copy real analyses to RejectAnalysis, with link to real create a new worksheet, with the original analyses, and new duplicates and references to match the rejected worksheet.
9,230
def multiglob_compile(globs, prefix=False): if not globs: return re.compile() elif prefix: globs = [x + for x in globs] return re.compile(.join(fnmatch.translate(x) for x in globs))
Generate a single "A or B or C" regex from a list of shell globs. :param globs: Patterns to be processed by :mod:`fnmatch`. :type globs: iterable of :class:`~__builtins__.str` :param prefix: If ``True``, then :meth:`~re.RegexObject.match` will perform prefix matching rather than exact string match...
9,231
def _compute_mean(self, C, mag, r): mean = (C[] + self._compute_term1(C, mag) + self._compute_term2(C, mag, r)) return mean
Compute mean value according to equation 30, page 1021.
9,232
def updateUserTone(conversationPayload, toneAnalyzerPayload, maintainHistory): emotionTone = None writingTone = None socialTone = None if not in conversationPayload: conversationPayload[] = {} if not in conversationPayload[]: conversationPayload[] = initUser() ...
updateUserTone processes the Tone Analyzer payload to pull out the emotion, writing and social tones, and identify the meaningful tones (i.e., those tones that meet the specified thresholds). The conversationPayload json object is updated to include these tones. @param conversationPayload json object re...
9,233
def set_rich_menu_image(self, rich_menu_id, content_type, content, timeout=None): self._post( .format(rich_menu_id=rich_menu_id), data=content, headers={: content_type}, timeout=timeout )
Call upload rich menu image API. https://developers.line.me/en/docs/messaging-api/reference/#upload-rich-menu-image Uploads and attaches an image to a rich menu. :param str rich_menu_id: IDs of the richmenu :param str content_type: image/jpeg or image/png :param content: image...
9,234
def setRelay(self, seconds, relay, status, password="00000000"): result = False self.setContext("setRelay") try: self.clearCmdMsg() if len(password) != 8: self.writeCmdMsg("Invalid password length.") self.setContext("") ...
Serial call to set relay. Args: seconds (int): Seconds to hold, ero is hold forever. See :class:`~ekmmeters.RelayInterval`. relay (int): Selected relay, see :class:`~ekmmeters.Relay`. status (int): Status to set, see :class:`~ekmmeters.RelayState` password (str):...
9,235
def resolve_remote(self, uri): try: return super(LocalRefResolver, self).resolve_remote(uri) except ValueError: return super(LocalRefResolver, self).resolve_remote( + get_schema_path(uri.rsplit(, 1)[0]) )
Resolve a uri or relative path to a schema.
9,236
def _upload(param_dict, timeout, data): param_dict[] = param_dict[] = param_dict[] = result = util.callm(, param_dict, POST = True, socket_timeout = 300, data = data) return _track_from_response(result, timeout)
Calls upload either with a local audio file, or a url. Returns a track object.
9,237
def blame_incremental(self, rev, file, **kwargs): data = self.git.blame(rev, , file, p=True, incremental=True, stdout_as_string=False, **kwargs) commits = {} stream = (line for line in data.split(b) if line) while True: try: line = next(stream) ...
Iterator for blame information for the given file at the given revision. Unlike .blame(), this does not return the actual file's contents, only a stream of BlameEntry tuples. :param rev: revision specifier, see git-rev-parse for viable options. :return: lazy iterator of BlameEntry tupl...
9,238
def gen_image(img, width, height, outfile, img_type=): assert len(img) == width * height or len(img) == width * height * 3 if img_type == : misc.imsave(outfile, img.reshape(width, height)) elif img_type == : misc.imsave(outfile, img.reshape(3, width, height))
Save an image with the given parameters.
9,239
def sign(self, storepass=None, keypass=None, keystore=None, apk=None, alias=None, name=): target = self.get_target() build_tool = android_helper.get_highest_build_tool(target.split()[1]) if keystore is None: (keystore, storepass, keypass, alias) = android_helper.get_default_keystore() dist = ...
Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default. :param storepass(str): keystore file storepass :param keypass(str): keystore file keypass :param keystore(str): keystore file path :param apk(str): apk file path to be signed :...
9,240
def validate(tool_class, model_class): if not hasattr(tool_class, ): raise ImproperlyConfigured("No attribute found for tool %s." % ( tool_class.__name__ )) if not hasattr(tool_class, ): raise ImproperlyConfigured("No attribute found for tool %s." % ( tool...
Does basic ObjectTool option validation.
9,241
def run(self): try: language = self.arguments[0] except IndexError: language = code = .join(self.content) literal = docutils.nodes.literal_block(code, code) literal[].append() literal[] = language return [literal]
Run directive.
9,242
def _setup_metric_group_definitions(self): metric_group_definitions = dict() for mg_info in self.properties[]: mg_name = mg_info[] mg_def = MetricGroupDefinition( name=mg_name, resource_class=_resource_class_from_group(mg_name), ...
Return the dict of MetricGroupDefinition objects for this metrics context, by processing its 'metric-group-infos' property.
9,243
def register(device, data, facet): if isinstance(data, string_types): data = json.loads(data) if data[] != VERSION: raise ValueError( % data[]) app_id = data.get(, facet) verify_facet(app_id, facet) app_param = sha256(app_id.encode()).digest() client_data = { : ,...
Register a U2F device data = { "version": "U2F_V2", "challenge": string, //b64 encoded challenge "appId": string, //app_id }
9,244
def convert_uen(pinyin): return UN_RE.sub(lambda m: m.group(1) + UN_MAP[m.group(2)], pinyin)
uen 转换,还原原始的韵母 iou,uei,uen前面加声母的时候,写成iu,ui,un。 例如niu(牛),gui(归),lun(论)。
9,245
def _buffer_decode(self, input, errors, final): decoded_segments = [] position = 0 while True: decoded, consumed = self._buffer_decode_step( input[position:], errors, final ...
Decode bytes that may be arriving in a stream, following the Codecs API. `input` is the incoming sequence of bytes. `errors` tells us how to handle errors, though we delegate all error-handling cases to the real UTF-8 decoder to ensure correct behavior. `final` indicates whether ...
9,246
def staticproperty(func): doc = func.__doc__ if not isinstance(func, staticmethod): func = staticmethod(func) return ClassPropertyDescriptor(func, doc)
Use as a decorator on a method definition to make it a class-level attribute (without binding). This decorator can be applied to a method or a staticmethod. This decorator does not bind any arguments. Usage: >>> other_x = 'value' >>> class Foo(object): ... @staticproperty ... def x(): ... retu...
9,247
def get(company=, company_uri=): if not company and not company_uri: raise Exception("glassdoor.gd.get(company=, company_uri=): "\ " company or company_uri required") payload = {} if not company_uri: payload.update({: , : company ...
Performs a HTTP GET for a glassdoor page and returns json
9,248
def from_df(cls, ratings:DataFrame, valid_pct:float=0.2, user_name:Optional[str]=None, item_name:Optional[str]=None, rating_name:Optional[str]=None, test:DataFrame=None, seed:int=None, path:PathOrStr=, bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collectio...
Create a `DataBunch` suitable for collaborative filtering from `ratings`.
9,249
def query_subdevice2index(self, ncfile) -> Subdevice2Index: subdevices = self.query_subdevices(ncfile) self._test_duplicate_exists(ncfile, subdevices) subdev2index = {subdev: idx for (idx, subdev) in enumerate(subdevices)} return Subdevice2Index(subdev2index, self.name, get_file...
Return a |Subdevice2Index| that maps the (sub)device names to their position within the given NetCDF file. Method |NetCDFVariableBase.query_subdevice2index| is based on |NetCDFVariableBase.query_subdevices|. The returned |Subdevice2Index| object remembers the NetCDF file the (s...
9,250
def set_levels(self, levels): assert_is_type(levels, [str]) return H2OFrame._expr(expr=ExprNode("setDomain", self, False, levels), cache=self._ex._cache)
Replace the levels of a categorical column. New levels must be aligned with the old domain. This call has copy-on-write semantics. :param List[str] levels: A list of strings specifying the new levels. The number of new levels must match the number of old levels. :returns: A single-...
9,251
def _to_power_basis_degree8(nodes1, nodes2): r evaluated = [ eval_intersection_polynomial(nodes1, nodes2, t_val) for t_val in _CHEB9 ] return polynomial.polyfit(_CHEB9, evaluated, 8)
r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that B |eacute| zout's `theorem`_ tells us the **intersection polynomial** is degree :math:`8`. This happens if the two curves have degrees one and eight or have degrees two and four. .. n...
9,252
def _raise_error_routes(iface, option, expected): msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg)
Log and raise an error with a logical formatted message.
9,253
def convert_coordinates(coords, origin, wgs84, wrapped): if isinstance(coords, list) or isinstance(coords, tuple): try: if isinstance(coords[0], list) or isinstance(coords[0], tuple): return [convert_coordinates(list(c), origin, wgs84, wrapped) for c in coords] e...
Convert coordinates from one crs to another
9,254
def stringify_summary(summary): for index, suite_summary in enumerate(summary["details"]): if not suite_summary.get("name"): suite_summary["name"] = "testcase {}".format(index) for record in suite_summary.get("records"): meta_datas = record[] __stringify_me...
stringify summary, in order to dump json file and generate html report.
9,255
def __rst2graph(self, rs3_xml_tree): doc_root = rs3_xml_tree.getroot() for segment in doc_root.iter(): self.__add_segment(segment) for group in doc_root.iter(): self.__add_group(group)
Reads an RST tree (from an ElementTree representation of an RS3 XML file) and adds all segments (nodes representing text) and groups (nonterminal nodes in an RST tree) as well as the relationships that hold between them (typed edges) to this RSTGraph. Parameters --------...
9,256
def _merge_meta(self, encoded_meta, meta): new_meta = None if meta: _meta = self._decode_meta(encoded_meta) for key, value in six.iteritems(meta): if value is None: _meta.pop(key, None) else: _meta[...
Merge new meta dict into encoded meta. Returns new encoded meta.
9,257
def modify(self, modification, parameters): for src in self: src.modify(modification, parameters)
Apply a modification to the underlying point sources, with the same parameters for all sources
9,258
def insert(self, table, columns, values, execute=True): cols, vals = get_col_val_str(columns) statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(wrap(table), cols, vals) if execute: self._cursor.execute(statement, values) self._co...
Insert a single row into a table.
9,259
def get_random_user(self): from provider.models import User u = User.objects.order_by()[0] return {"username": u.username, "password": u.password, "fullname": u.fullname}
Gets a random user from the provider :returns: Dictionary
9,260
def pre_save(self, model_instance, add): value = super(UserField, self).pre_save(model_instance, add) if not value and not add: value = self.get_os_username() setattr(model_instance, self.attname, value) return value return v...
Updates username created on ADD only.
9,261
def ci(data, statfunction=None, alpha=0.05, n_samples=10000, method=, output=, epsilon=0.001, multi=None, _iter=True): if np.iterable(alpha): alphas = np.array(alpha) else: alphas = np.array([alpha/2, 1-alpha/2]) if multi is None: if isinstance(data, tuple):...
Given a set of data ``data``, and a statistics function ``statfunction`` that applies to that data, computes the bootstrap confidence interval for ``statfunction`` on that data. Data points are assumed to be delineated by axis 0. Parameters ---------- data: array_like, shape (N, ...) OR tuple of array_like all with sh...
9,262
def show(self): off = 0 for n, i in enumerate(self.get_instructions()): print("{:8d} (0x{:08x}) {:04x} {:30} {}".format(n, off, i.get_op_value(), i.get_name(), i.get_output(self.idx))) off += i.get_length()
Display (with a pretty print) this object
9,263
def get_worksheet(self, index): sheet_data = self.fetch_sheet_metadata() try: properties = sheet_data[][index][] return Worksheet(self, properties) except (KeyError, IndexError): return None
Returns a worksheet with specified `index`. :param index: An index of a worksheet. Indexes start from zero. :type index: int :returns: an instance of :class:`gsperad.models.Worksheet` or `None` if the worksheet is not found. Example. To get first worksheet of a sprea...
9,264
def as_params(self): params = {} if self.has_filters: params[] = self.get_filters() if self.has_order: params[] = self.get_order() if self.has_selects: params[] = self.get_selects() if self.has_expands: params[] = self.get_...
Returns the filters, orders, select, expands and search as query parameters :rtype: dict
9,265
def convert_sed_cols(tab): for colname in list(tab.columns.keys()): newname = colname.lower() newname = newname.replace(, ) if tab.columns[colname].name == newname: continue tab.columns[colname].name = newname return tab
Cast SED column names to lowercase.
9,266
def add(self, search): ms = self._clone() ms._searches.append(search) return ms
Adds a new :class:`~elasticsearch_dsl.Search` object to the request:: ms = MultiSearch(index='my-index') ms = ms.add(Search(doc_type=Category).filter('term', category='python')) ms = ms.add(Search(doc_type=Blog))
9,267
def _get_goid2dbids(associations): go2ids = cx.defaultdict(set) for ntd in associations: go2ids[ntd.GO_ID].add(ntd.DB_ID) return dict(go2ids)
Return gene2go data for user-specified taxids.
9,268
def _close_prepared_statement(self): self.prepared_sql = None self.flush_to_query_ready() self.connection.write(messages.Close(, self.prepared_name)) self.connection.write(messages.Flush()) self._message = self.connection.read_expected_message(messages.CloseComplete) ...
Close the prepared statement on the server.
9,269
def delete_managed_disk(call=None, kwargs=None): compconn = get_conn(client_type=) try: compconn.disks.delete(kwargs[], kwargs[]) except Exception as exc: log.error(, kwargs.get(), six.text_type(exc)) return False return True
Delete a managed disk from a resource group.
9,270
def distVersion(): from pkg_resources import parse_version build_number = buildNumber() parsedBaseVersion = parse_version(baseVersion) if isinstance(parsedBaseVersion, tuple): raise RuntimeError("Setuptools version 8.0 or newer required. Update by running " "") ...
The distribution version identifying a published release on PyPI.
9,271
def region_size(im): r if im.dtype == bool: im = spim.label(im)[0] counts = sp.bincount(im.flatten()) counts[0] = 0 chords = counts[im] return chords
r""" Replace each voxel with size of region to which it belongs Parameters ---------- im : ND-array Either a boolean image wtih ``True`` indicating the features of interest, in which case ``scipy.ndimage.label`` will be applied to find regions, or a greyscale image with integer ...
9,272
def normalize_curves_eb(curves): non_zero_curves = [(losses, poes) for losses, poes in curves if losses[-1] > 0] if not non_zero_curves: return curves[0][0], numpy.array([poes for _losses, poes in curves]) else: max_losses = [losses[-1] for losses, _poes ...
A more sophisticated version of normalize_curves, used in the event based calculator. :param curves: a list of pairs (losses, poes) :returns: first losses, all_poes
9,273
def remote_mgmt_addr_uneq_store(self, remote_mgmt_addr): if remote_mgmt_addr != self.remote_mgmt_addr: self.remote_mgmt_addr = remote_mgmt_addr return True return False
This function saves the MGMT address, if different from stored.
9,274
def run(*steps): if not steps: return task = None run._sigint = False loop = asyncio.get_event_loop() def abort(): task.cancel() run._sigint = True added = False try: loop.add_signal_handler(signal.SIGINT, abort) added = True except (Valu...
Helper to run one or more async functions synchronously, with graceful handling of SIGINT / Ctrl-C. Returns the return value of the last function.
9,275
def NewOutputModule(cls, name, output_mediator): output_class = cls.GetOutputClass(name) return output_class(output_mediator)
Creates a new output module object for the specified output format. Args: name (str): name of the output module. output_mediator (OutputMediator): output mediator. Returns: OutputModule: output module. Raises: KeyError: if there is no output class found with the supplied name. ...
9,276
def meth_set_acl(args): acl_updates = [{"user": user, "role": args.role} \ for user in set(expand_fc_groups(args.users)) \ if user != fapi.whoami()] id = args.snapshot_id if not id: r = fapi.list_repository_methods(namespace=args.namespace, ...
Assign an ACL role to a list of users for a workflow.
9,277
def p_example_multiline(self, p): p[0] = AstExampleField( self.path, p.lineno(1), p.lexpos(1), p[1], p[5])
example_field : ID EQ NL INDENT ex_map NL DEDENT
9,278
def _CSI(self, cmd): sys.stdout.write() sys.stdout.write(cmd)
Control sequence introducer
9,279
def get_args_parser(): parser = argparse.ArgumentParser( description=) parser.add_argument(, , action=EnvDefault, envvar=, required=True, help=) parser.add_argument(, , action...
Return a parser for command line options.
9,280
def find_near_matches_no_deletions_ngrams(subsequence, sequence, search_params): if not subsequence: raise ValueError() max_substitutions, max_insertions, max_deletions, max_l_dist = search_params.unpacked max_substitutions = min(max_substitutions, max_l_dist) max_insertions = min(max_ins...
search for near-matches of subsequence in sequence This searches for near-matches, where the nearly-matching parts of the sequence must meet the following limitations (relative to the subsequence): * the maximum allowed number of character substitutions * the maximum allowed number of new characters i...
9,281
def taskGroupCreationRequested(self, *args, **kwargs): ref = { : , : , : [ { : , : False, : , }, { : False, : , ...
tc-gh requested the Queue service to create all the tasks in a group supposed to signal that taskCreate API has been called for every task in the task group for this particular repo and this particular organization currently used for creating initial status indicators in GitHub UI using Statuse...
9,282
def pretty_print(self): print colored.blue("-" * 40) print colored.red("datacats: problem was encountered:") print self.message print colored.blue("-" * 40)
Print the error message to stdout with colors and borders
9,283
def unix_time(self, dt): epoch = datetime.utcfromtimestamp(0) delta = dt - epoch return int(delta.total_seconds())
Returns the number of seconds since the UNIX epoch for the given datetime (dt). PARAMETERS: dt -- datetime
9,284
def ipv6_link_local(self, **kwargs): int_type = kwargs.pop().lower() ve_name = kwargs.pop() rbridge_id = kwargs.pop(, ) callback = kwargs.pop(, self._callback) valid_int_types = [, ] if int_type not in valid_int_types: raise ValueError( % ...
Configure ipv6 link local address on interfaces on vdx switches Args: int_type: Interface type on which the ipv6 link local needs to be configured. name: 'Ve' or 'loopback' interface name. rbridge_id (str): rbridge-id for device. get (bool): Get conf...
9,285
def getIdent(self, node): ident = self.getRawIdent(node) if ident is not None: return ident node = self.findNode(node) if node is None: return None return node.graphident
Get the graph identifier for a node
9,286
def bbox_to_resolution(bbox, width, height): utm_bbox = to_utm_bbox(bbox) east1, north1 = utm_bbox.lower_left east2, north2 = utm_bbox.upper_right return abs(east2 - east1) / width, abs(north2 - north1) / height
Calculates pixel resolution in meters for a given bbox of a given width and height. :param bbox: bounding box :type bbox: geometry.BBox :param width: width of bounding box in pixels :type width: int :param height: height of bounding box in pixels :type height: int :return: resolution east-w...
9,287
def mark_offer_as_lose(self, offer_id): return self._create_put_request( resource=OFFERS, billomat_id=offer_id, command=LOSE, )
Mark offer as lose :param offer_id: the offer id :return Response
9,288
def run(self): logger.debug("Starting execution of {0}{1}".format(self, " (backwards)" if self.backward_execution else "")) self.setup_run() try: concurrency_history_item = self.setup_forward_or_backward_execution() concurrency_queue = self.start_child_states(co...
This defines the sequence of actions that are taken when the preemptive concurrency state is executed :return:
9,289
def taskdir(self): return os.path.join(self.BASE, self.TAG, self.task_family)
Return the directory under which all artefacts are stored.
9,290
def get_required(self, name): locator = self._locate(name) if locator == None: raise ReferenceException(None, name) return self._references.get_required(locator)
Gets all required dependencies by their name. At least one dependency must be present. If no dependencies was found it throws a [[ReferenceException]] :param name: the dependency name to locate. :return: a list with found dependencies.
9,291
def get_grouped_opcodes(self, n=3): codes = self.get_opcodes() if not codes: codes = [("equal", 0, 1, 0, 1)] if codes[0][0] == : tag, i1, i2, j1, j2 = codes[0] codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2 if codes[-1][0] == :...
Isolate change clusters by eliminating ranges with no changes. Return a generator of groups with up to n lines of context. Each group is in the same format as returned by get_opcodes(). >>> from pprint import pprint >>> a = map(str, range(1,40)) >>> b = a[:] >>> b[8:8] ...
9,292
def get_managed( name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, **kwargs): *{hash_type: , : <md5sum>}755 sfn = ...
Return the managed file data for file.managed name location where the file lives on the server template template format source managed source file source_hash hash of the source file source_hash_name When ``source_hash`` refers to a remote file, this spec...
9,293
def load(self, name): if self.reload: self._maybe_purge_cache() template = self.cache.get(name) if template: return template path = self.resolve(name) if not path: raise OSError(errno.ENOENT, "File not found: %s" % name) wi...
If not yet in the cache, load the named template and compiles it, placing it into the cache. If in cache, return the cached template.
9,294
def rst2md(text): top_heading = re.compile(r, flags=re.M) text = re.sub(top_heading, r, text) math_eq = re.compile(r, flags=re.M) text = re.sub(math_eq, lambda match: r.format(match.group(1).strip()), text) inline_math = re.compile(r) text = re.sub(inli...
Converts the RST text from the examples docstrigs and comments into markdown text for the IPython notebooks
9,295
def field2choices(self, field, **kwargs): attributes = {} comparable = [ validator.comparable for validator in field.validators if hasattr(validator, "comparable") ] if comparable: attributes["enum"] = comparable else: ...
Return the dictionary of OpenAPI field attributes for valid choices definition :param Field field: A marshmallow field. :rtype: dict
9,296
def md5sum(filename, blocksize=8192): with open(filename, ) as fh: m = hashlib.md5() while True: data = fh.read(blocksize) if not data: break m.update(data) return m.hexdigest()
Get the MD5 checksum of a file.
9,297
def init_default_config(self, path): if not (os.path.exists(path) and os.path.isfile(path)): raise AppConfigValueException( .format(path)) cfl = open(path, ) data = json.load(cfl) cfl.close() for key in data.keys(): if == key:...
Initialize the config object and load the default configuration. The path to the config file must be provided. The name of the application is read from the config file. The config file stores the description and the default values for all configurations including the appl...
9,298
def check(text): err = "airlinese.misc" msg = u" is airlinese." airlinese = [ "enplan(?:e|ed|ing|ement)", "deplan(?:e|ed|ing|ement)", "taking off momentarily", ] return existence_check(text, airlinese, err, msg)
Check the text.
9,299
def create_sqlite_backup_db(audit_tables): try: Popen("rm %s"%(config.get(, )), shell=True) logging.warn("Old sqlite backup DB removed") except Exception as e: logging.warn(e) try: aux_dir = config.get(, ) os.mkdir(aux_dir) logging.warn("%s cre...
return an inspector object