Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
9,800
def pair(args): p = OptionParser(pair.__doc__) p.set_sep(sep=None, help="Separator in name to reduce to clone id" +\ "e.g. GFNQ33242/1 use /, BOT01-2453H.b1 use .") p.add_option("-m", dest="matepairs", default=False, action="store_true", help="generate .matepairs file [ofte...
%prog pair fastafile Generate .pairs.fasta and .fragments.fasta by matching records into the pairs and the rest go to fragments.
9,801
def char_range(starting_char, ending_char): assert isinstance(starting_char, str), assert isinstance(ending_char, str), for char in range(ord(starting_char), ord(ending_char) + 1): yield chr(char)
Create a range generator for chars
9,802
def _cleanup(self): for channel in self._open_channels: try: self.disconnect_channel(channel) except Exception: pass for handler in self._handlers.values(): try: handler.tear_down() except Excepti...
Cleanup open channels and handlers
9,803
def trimSegments(self, minPermanence=None, minNumSyns=None): if minPermanence is None: minPermanence = self.connectedPerm if minNumSyns is None: minNumSyns = self.activationThreshold totalSegsRemoved, totalSynsRemoved = 0, 0 for c,i in product(xrange(self.numberOfCols), xran...
This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining. Parameters: -------------------------------------------------------------- minPermanence: Any syn whose permamence is 0 or < minPermanence wi...
9,804
def map_pixel(self, point_x, point_y): row, col = map_pixel(point_x, point_y, self.x_cell_size, self.y_cell_size, self.xmin, self.ymax) try: return self.raster[row, col] except: raise RasterGeoError()
geo.map_pixel(point_x, point_y) Return value of raster in location Note: (point_x, point_y) must belong to the geographic coordinate system and the coverage of the raster
9,805
def sizeClassifier(path, min_size=DEFAULTS[]): filestat = _stat(path) if stat.S_ISLNK(filestat.st_mode): return if filestat.st_size < min_size: return return filestat.st_size
Sort a file into a group based on on-disk size. :param paths: See :func:`fastdupes.groupify` :param min_size: Files smaller than this size (in bytes) will be ignored. :type min_size: :class:`__builtins__.int` :returns: See :func:`fastdupes.groupify` .. todo:: Rework the calling of :func:`~os.sta...
9,806
def to_dict(mapreduce_yaml): all_configs = [] for config in mapreduce_yaml.mapreduce: out = { "name": config.name, "mapper_input_reader": config.mapper.input_reader, "mapper_handler": config.mapper.handler, } if config.mapper.params_validator: out["ma...
Converts a MapReduceYaml file into a JSON-encodable dictionary. For use in user-visible UI and internal methods for interfacing with user code (like param validation). as a list Args: mapreduce_yaml: The Pyton representation of the mapreduce.yaml document. Returns: A list of configuration...
9,807
def xml_to_metrics(xmlstr, object_type): listeners.active\2014-10-02T00:00:00Z\ xmldoc = minidom.parseString(xmlstr) return_obj = object_type() members = dict(vars(return_obj)) for xml_entry in _MinidomXmlToObject.get_children_from_path(xmldoc, ...
Converts xml response to service bus metrics objects The xml format for MetricProperties <entry> <id>https://sbgm.windows.net/Metrics(\'listeners.active\')</id> <title/> <updated>2014-10-09T11:56:50Z</updated> <author> <name/> </author> <content type="application/xml"> <...
9,808
def create(self, alert_config, occurrence_frequency_count=None, occurrence_frequency_unit=None, alert_frequency_count=None, alert_frequency_unit=None): data = { : occurrence_frequency_count or 1, : occurr...
Create a new alert :param alert_config: A list of AlertConfig classes (Ex: ``[EmailAlertConfig('me@mydomain.com')]``) :type alert_config: list of :class:`PagerDutyAlertConfig<logentries_api.alerts.PagerDutyAlertConfig>`, :class:`WebHookAlertConfig<logentries_api.aler...
9,809
def save(): from .models import ModuleInfo logger = logging.getLogger(__name__) logger.info("Saving changes") for module in modules(): if module.enabled: if module.changed: module.save() module.restart() module.commit() ...
Apply configuration changes on all the modules
9,810
def work(self): import time for val in range(200): time.sleep(0.1) self.sigUpdate.emit(val + 1)
Use a blocking <sleep> call to periodically trigger a signal.
9,811
def transform(self, data): out=[] keys = sorted(data.keys()) for k in keys: out.append("%s=%s" % (k, data[k])) return "\n".join(out)
:param data: :type data: dict :return: :rtype:
9,812
def next(self, fetch: bool = False, next_symbol: _NextSymbol = DEFAULT_NEXT_SYMBOL) -> _Next: def get_next(): candidates = self.find(, containing=next_symbol) for candidate in candidates: if candidate.attrs.get(): if in...
Attempts to find the next page, if there is one. If ``fetch`` is ``True`` (default), returns :class:`HTML <HTML>` object of next page. If ``fetch`` is ``False``, simply returns the next URL.
9,813
def run(self, *args): params = self.parser.parse_args(args) with params.outfile as outfile: if params.identities: code = self.export_identities(outfile, params.source) elif params.orgs: code = self.export_organizations(outfile) ...
Export data from the registry. By default, it writes the data to the standard output. If a positional argument is given, it will write the data on that file.
9,814
def forward_remote( self, remote_port, local_port=None, remote_host="127.0.0.1", local_host="localhost", ): if not local_port: local_port = remote_port tunnels = [] def callbac...
Open a tunnel connecting ``remote_port`` to the local environment. For example, say you're running a daemon in development mode on your workstation at port 8080, and want to funnel traffic to it from a production or staging environment. In most situations this isn't possible as your of...
9,815
def _version_string(): platform_system = platform.system() if platform_system == : os_name, os_version, _ = platform.dist() else: os_name = platform_system os_version = platform.version() python_version = platform.python_version() return % (__version__, ...
Gets the output for `trytravis --version`.
9,816
def select_eep(self, rorg_func, rorg_type, direction=None, command=None): self.rorg_func = rorg_func self.rorg_type = rorg_type self._profile = self.eep.find_profile(self._bit_data, self.rorg, rorg_func, rorg_type, direction, command) return self._profile is not None
Set EEP based on FUNC and TYPE
9,817
def project_invite(object_id, input_params={}, always_retry=False, **kwargs): return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /project-xxxx/invite API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2Finvite
9,818
def update_many(self, **kwargs): db_objects = self.get_dbcollection_with_es(**kwargs) return self.Model._update_many( db_objects, self._json_params, self.request)
Update multiple objects from collection. First ES is queried, then the results are used to query DB. This is done to make sure updated objects are those filtered by ES in the 'index' method (so user updates what he saw).
9,819
def from_triple(cls, triple): with ffi.OutputString() as outerr: target = ffi.lib.LLVMPY_GetTargetFromTriple(triple.encode(), outerr) if not target: raise RuntimeError(str(outerr)) target = cls(t...
Create a Target instance for the given triple (a string).
9,820
def table_exists(self, table): if not self.dataset_exists(table.dataset): return False try: self.client.tables().get(projectId=table.project_id, datasetId=table.dataset_id, tableId=table.table_id)...
Returns whether the given table exists. :param table: :type table: BQTable
9,821
def read_probes(self, key = None): print((, key, self._PROBES())) if key is None: d = {} for k in list(self._PROBES.keys()): d[k] = self.read_probes(k) return d else: assert key in list(self._PRO...
function is overloaded: - read_probes() - read_probes(key) Args: key: name of requested value Returns: - if called without argument: returns the values of all probes in dictionary form - if called with argument: returns the value the requeste...
9,822
def _check_restart_params(self, restart_strategy, min_beta, s_greedy, xi_restart): r if restart_strategy is None: return True if self.mode != : raise ValueError( ) greedy_params_check = (min_beta is Non...
r""" Check restarting parameters This method checks that the restarting parameters are set and satisfy the correct assumptions. It also checks that the current mode is regular (as opposed to CD for now). Parameters ---------- restart_strategy: str or None na...
9,823
def _noneload(l: Loader, value, type_) -> None: if value is None: return None raise TypedloadValueError(, value=value, type_=type_)
Loads a value that can only be None, so it fails if it isn't
9,824
async def close_async(self, context, reason): logger.info("Connection closed (reason {}, id {}, offset {}, sq_number {})".format( reason, context.partition_id, context.offset, context.sequence_number))
Called by processor host to indicate that the event processor is being stopped. :param context: Information about the partition :type context: ~azure.eventprocessorhost.PartitionContext
9,825
def attributes(self) -> Sequence[bytes]: ret: List[bytes] = [] if not self.exists: ret.append(b) if self.has_children: ret.append(b) else: ret.append(b) if self.marked is True: ret.append(b) elif self.marked is Fals...
The mailbox attributes that should be returned with the mailbox in a ``LIST`` response, e.g. ``\\Noselect``. See Also: `RFC 3348 <https://tools.ietf.org/html/rfc3348>`_
9,826
def activate(self, *, filter_func=None): if self.active: raise RuntimeError("Type safety check already active") self.__module_finder = ModuleFinder(Validator.decorate) if filter_func is not None: self.__module_finder.set_filter(filter_func) self.__modul...
Activate the type safety checker. After the call all functions that need to be checked will be.
9,827
def __init(self): params = { "f" : "json" } json_dict = self._get(url=self._url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port...
initializes all the properties
9,828
def is_reached(self, uid=None): if self.reached_limit: return True if uid: if uid in self.seen: return False self.count += 1 self.seen.add(uid) else: self.count += 1 if self.count > self.limit: ...
is_reached is to be called for every object that counts towards the limit. - When called with no uid, the Limiter assumes this is a new object and unconditionally increments the counter (less CPU and memory usage). - When a given object can be passed multiple times, a uid must be provided to ...
9,829
def PhenomModel(self, r): if r <= 0: raise ValueError field = self.B0 + self.B1 * G4.m / r + self.B2 * math.exp(-1 * self.H * r / G4.m) return field
Fit to field map A phenomenological fit by Ryan Bayes (Glasgow) to a field map generated by Bob Wands (FNAL). It assumes a 1 cm plate. This is dated January 30th, 2012. Not defined for r <= 0
9,830
def plot(x, fmt=, marker=None, markers=None, linestyle=None, linestyles=None, color=None, colors=None, palette=, group=None, hue=None, labels=None, legend=None, title=None, size=None, elev=10, azim=-60, ndims=3, model=None, model_params=None, reduce=, cluster=None, align=None, normal...
Plots dimensionality reduced data and parses plot arguments Parameters ---------- x : Numpy array, DataFrame, String, Geo or mixed list Data for the plot. The form should be samples (rows) by features (cols). fmt : str or list of strings A list of format strings. All matplotlib format...
9,831
def delete_group(self, group_id): url = self.TEAM_GROUPS_ID_URL % group_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
Remove a group from your team :param group_id: Id of group
9,832
def ensure_chosen_alternatives_are_in_user_alt_ids(choice_col, wide_data, availability_vars): if not wide_data[choice_col].isin(availability_vars.keys()).all(): msg = "One or more values in wide_data[c...
Ensures that all chosen alternatives in `wide_df` are present in the `availability_vars` dict. Raises a helpful ValueError if not. Parameters ---------- choice_col : str. Denotes the column in `wide_data` that contains a one if the alternative pertaining to the given row was the observe...
9,833
def labels(self): return tuple(_Label(label.get(), label.get(), label.text) for label in self.root.iter())
Tuple of labels.
9,834
def show(self): textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) text = f + self.comment print(.join( textwrap.wrap( text, width=textWidth, initial_indent=, subsequent_indent= * 24))) loca...
Output for command sos show
9,835
def get(key, default=-1): if isinstance(key, int): return NotifyMessage(key) if key not in NotifyMessage._member_map_: extend_enum(NotifyMessage, key, default) return NotifyMessage[key]
Backport support for original codes.
9,836
def evaluate(self, node: InstanceNode) -> XPathValue: return self._eval(XPathContext(node, node, 1, 1))
Evaluate the receiver and return the result. Args: node: Context node for XPath evaluation. Raises: XPathTypeError: If a subexpression of the receiver is of a wrong type.
9,837
def xor(key, data): if type(key) is int: key = six.int2byte(key) key_len = len(key) return b.join( six.int2byte(c ^ six.indexbytes(key, i % key_len)) for i, c in enumerate(six.iterbytes(data)) )
Perform cyclical exclusive or operations on ``data``. The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If the key is smaller than the provided ``data``, the ``key`` will be repeated. Args: key(int or bytes): The key to xor ``data`` with. data(bytes): The data to p...
9,838
def _setattr_url_map(self): if self.apiopts.get(, True) is False: url_blacklist = [, , , ] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: ...
Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs.
9,839
def macro_network(): tpm = np.array([[0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 1.0, 1.0], [0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 0.3, 0.3], ...
A network of micro elements which has greater integrated information after coarse graining to a macro scale.
9,840
def screen_resolution(): w = 0 h = 0 try: import ctypes user32 = ctypes.windll.user32 w, h = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1) except AttributeError: try: import AppKit size = AppKit.NSScreen.screens(...
Returns the current screen's resolution. Should be multi-platform. :return: A tuple containing the width and height of the screen.
9,841
def add(self, source, email=None, name=None, username=None, uuid=None, matching=None, interactive=False): matcher = None if matching: try: blacklist = api.blacklist(self.db) matcher = create_identity_matcher(matching, blacklist) ...
Add an identity to the registry. This method adds a new identity to the registry. By default, a new unique identity will be also added an associated to the new identity. When <uuid> parameter is set, it only creates a new identity that will be associated to a unique identity defined by ...
9,842
def q(self, x, q0): y1_0 = q0 y0_0 = 0 y0 = [y0_0, y1_0] y = _sp.integrate.odeint(self._func, y0, x, Dfun=self._gradient, rtol=self.rtol, atol=self.atol) return y[:, 1]
Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`.
9,843
def has_perm(self, user, perm, obj=None, *args, **kwargs): try: if not self._obj_ok(obj): if hasattr(obj, ): obj = obj.get_permissions_object(perm) else: raise InvalidPermissionObjectException return user.pe...
Test user permissions for a single action and object. :param user: The user to test. :type user: ``User`` :param perm: The action to test. :type perm: ``str`` :param obj: The object path to test. :type obj: ``tutelary.engine.Object`` :returns: ``bool`` -- is the ...
9,844
def authenticate(self, name, password, mechanism="DEFAULT"): if not isinstance(name, (bytes, unicode)): raise TypeError("TxMongo: name must be an instance of basestring.") if not isinstance(password, (bytes, unicode)): raise TypeError("TxMongo: password must be an instan...
Send an authentication command for this database. mostly stolen from pymongo
9,845
def p_new_expr(self, p): if len(p) == 2: p[0] = p[1] else: p[0] = ast.NewExpr(p[2])
new_expr : member_expr | NEW new_expr
9,846
def parse(query_string, unquote=True, normalized=False, encoding=DEFAULT_ENCODING): mydict = {} plist = [] if query_string == "": return mydict if type(query_string) == bytes: query_string = query_string.decode() for element in query_string.split("&"): ...
Main parse function @param query_string: @param unquote: unquote html query string ? @param encoding: An optional encoding used to decode the keys and values. Defaults to utf-8, which the W3C declares as a defaul in the W3C algorithm for encoding. @see http://www.w3.org/TR/html5/forms.html#applicati...
9,847
def tuple_search(t, i, v): for e in t: if e[i] == v: return e return None
Search tuple array by index and value :param t: tuple array :param i: index of the value in each tuple :param v: value :return: the first tuple in the array with the specific index / value
9,848
def sites(c): docs_c["run"].hide = True www_c["run"].hide = True docs["build"](docs_c) www["build"](www_c) docs_c["run"].hide = False www_c["run"].hide = False docs["build"](docs_c, nitpick=True) www["build"](www_c, nitpick=True)
Build both doc sites w/ maxed nitpicking.
9,849
def reads(err_log): num_reads = 0 paired_reads = 0 with open(err_log, ) as error_log: for line in error_log: if in line: num_reads = line.split()[-1].rstrip() elif in line: ...
Parse the outputs from bbmerge to extract the total number of reads, as well as the number of reads that could be paired :param err_log: bbmerge outputs the stats in the error file :return: num_reads, the total number of reads, paired_reads, number of paired readds
9,850
def extract_to(self, *, stream=None, fileprefix=): if bool(stream) == bool(fileprefix): raise ValueError("Cannot set both stream and fileprefix") if stream: return self._extract_to_stream(stream=stream) bio = BytesIO() extension = self._extract_to_strea...
Attempt to extract the image directly to a usable image file If possible, the compressed data is extracted and inserted into a compressed image file format without transcoding the compressed content. If this is not possible, the data will be decompressed and extracted to an appropriate ...
9,851
def DoubleClick(cls): element = cls._element() action = ActionChains(Web.driver) action.double_click(element) action.perform()
左键点击2次
9,852
def add_pr_curve(self, tag, labels, predictions, num_thresholds, global_step=None, weights=None): if num_thresholds < 2: raise ValueError() labels = _make_numpy_array(labels) predictions = _make_numpy_array(predictions) self._file_writer.add_summ...
Adds precision-recall curve. Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs. Since `asnumpy()` is a blocking function call, this function would block the main thread till it returns. It may consequently affect the performance of async execution of the MXNet ...
9,853
def delete(self): if self.exists(): try: self._api.buckets_delete(self._name) except Exception as e: raise e
Deletes the bucket. Raises: Exception if there was an error deleting the bucket.
9,854
def connections_from_object(self, from_obj): self._validate_ctypes(from_obj, None) return self.connections.filter(from_pk=from_obj.pk)
Returns a ``Connection`` query set matching all connections with the given object as a source.
9,855
def throw(self, method, args={}, nowait=False, **kwargs): r = self.call_or_cast(method, args, type=ACTOR_TYPE.RR, nowait=nowait, **kwargs) if not nowait: return r
Call method on one of the agents in round robin. See :meth:`call_or_cast` for a full list of supported arguments. If the keyword argument `nowait` is false (default) it will block and return the reply.
9,856
def clear_mask(self): if self.masktag: try: self.canvas.delete_object_by_tag(self.masktag, redraw=False) except Exception: pass if self.maskhltag: try: self.canvas.delete_object_by_tag(self.maskhltag, redraw=Fa...
Clear mask from image. This does not clear loaded masks from memory.
9,857
def results_tc(self, key, value): if os.access(self.default_args.tc_out_path, os.W_OK): results_file = .format(self.default_args.tc_out_path) else: results_file = new = True open(results_file, ).close() with open(results_file, ) as fh: ...
Write data to results_tc file in TcEX specified directory. The TcEx platform support persistent values between executions of the App. This method will store the values for TC to read and put into the Database. Args: key (string): The data key to be stored. value (strin...
9,858
def __get_average_intra_cluster_distance(self, entry): linear_part_first = list_math_addition(self.linear_sum, entry.linear_sum); linear_part_second = linear_part_first; linear_part_distance = sum(list_math_multiplication(linear_part_first, linear_part_second)); ...
! @brief Calculates average intra cluster distance between current and specified clusters. @param[in] entry (cfentry): Clustering feature to which distance should be obtained. @return (double) Average intra cluster distance.
9,859
def read_from_file(self, filename): if not exists(filename): return -1 with open(filename) as fd: needs_json = fd.read() try: minimum_needs = json.loads(needs_json) except (TypeError, ValueError): minimum_needs = No...
Read from an existing json file. :param filename: The file to be written to. :type filename: basestring, str :returns: Success status. -1 for unsuccessful 0 for success :rtype: int
9,860
def Parse(self): (start_line, lang) = self.ParseDesc() if start_line < 0: return if == lang: self.ParsePythonFlags(start_line) elif == lang: self.ParseCFlags(start_line) elif == lang: self.ParseJavaFlags(start_line)
Parse program output.
9,861
def addFeatureToGraph( self, add_region=True, region_id=None, feature_as_class=False): if feature_as_class: self.model.addClassToGraph( self.fid, self.label, self.ftype, self.description) else: self.model.addIndividualToGraph( ...
We make the assumption here that all features are instances. The features are located on a region, which begins and ends with faldo:Position The feature locations leverage the Faldo model, which has a general structure like: Triples: feature_id a feature_type (individual)...
9,862
def getMibSymbol(self): if self._state & self.ST_CLEAN: return self._modName, self._symName, self._indices else: raise SmiError( % self.__class__.__name__)
Returns MIB variable symbolic identification. Returns ------- str MIB module name str MIB variable symbolic name : :py:class:`~pysnmp.proto.rfc1902.ObjectName` class instance representing MIB variable instance index. Raises ...
9,863
def verify_system_status(self): if not sys.platform.startswith(): raise InstallError() if self.python.is_system_python(): if self.python.is_python_binding_installed(): message = Log.info(message) raise InstallSkipError(me...
Verify system status.
9,864
def subnet_range(ip_net, cidr): subnets_dict = dict() subnet = whole_subnet_maker(ip_net, cidr) subnets_dict[] = ip_net subnets_dict[] = subnet subnets_dict[] = % (whole_subnet_maker(ip_net, cidr), cidr) if int(cidr) >= 24: subnet_split = subnet.split() first_ip = int(subne...
Function to return a subnet range value from a IP address and CIDR pair Args: ip_net: Unicast or Multicast IP address or subnet in the following format 192.168.1.1, 239.1.1.1 cidr: CIDR value of 1 to 32 Returns: returns a dictionary of info
9,865
def parse_name(cls, name: str, default: T = None) -> T: if not name: return default name = name.lower() return next((item for item in cls if name == item.name.lower()), default)
Parse specified name for IntEnum; return default if not found.
9,866
def m2i(self, pkt, s): diff_tag, s = BER_tagging_dec(s, hidden_tag=self.ASN1_tag, implicit_tag=self.implicit_tag, explicit_tag=self.explicit_tag, safe=self.flexible_tag) if diff_tag...
The good thing about safedec is that it may still decode ASN1 even if there is a mismatch between the expected tag (self.ASN1_tag) and the actual tag; the decoded ASN1 object will simply be put into an ASN1_BADTAG object. However, safedec prevents the raising of exceptions needed for ASN...
9,867
def ProfileRunValidationOutputFromOptions(feed, options): import cProfile import pstats locals_for_exec = locals() cProfile.runctx(, globals(), locals_for_exec, ) import resource print("Time: %d seconds" % ( resource.getrusage(resource.RUSAGE_SELF).ru_utime + resource...
Run RunValidationOutputFromOptions, print profile and return exit code.
9,868
def set_bind(self): RangedInt.set_bind(self) self.unbind() self.unbind() self.bind(, lambda e: self.set(self._min())) self.bind(, lambda e: self.set(self._max()))
Sets key bindings -- we need this more than once
9,869
def GET(self, courseid, taskid, path): try: course = self.course_factory.get_course(courseid) if not self.user_manager.course_is_open_to_user(course): return self.template_helper.get_renderer().course_unavailable() path_norm = posixpath.normpath(ur...
GET request
9,870
def parser(self): module = self.module subcommands = self.subcommands if subcommands: module_desc = inspect.getdoc(module) parser = Parser(description=module_desc, module=module) subparsers = parser.add_subparsers() for sc_name, callback...
return the parser for the current name
9,871
def flock(path): with open(path, "w+") as lf: try: fcntl.flock(lf, fcntl.LOCK_EX | fcntl.LOCK_NB) acquired = True yield acquired except OSError: acquired = False yield acquired finally: if acquired: ...
Attempt to acquire a POSIX file lock.
9,872
def assets(self, asset_code=None, asset_issuer=None, cursor=None, order=, limit=10): endpoint = params = self.__query_params(asset_code=asset_code, asset_issuer=asset_issuer, cursor=cursor, order=order, limit=limit) return self.query(endpoint, param...
This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are available. `GET /assets{?asset_code,asset_issuer,cursor,limit,order} <https://www.st...
9,873
def update(self): if not self.showing: return d = self.declaration self.set_show(d.show)
Update the PopupWindow if it is currently showing. This avoids calling update during initialization.
9,874
def read_excel(file_name, offset=1, sheet_index=0): try: workbook = xlrd.open_workbook(file_name) except Exception as e: return None if len(workbook.sheets()) <= 0: return [] sh = workbook.sheets()[sheet_index] raw_data = [] n_rows = sh.nrows row = sh.row_valu...
读取 Excel :param sheet_index: :param file_name: :param offset: 偏移,一般第一行是表头,不需要读取数据 :return:
9,875
def main(): rc_settings = read_rcfile() parser = ArgumentParser(description=) parser.add_argument(, , type=int, nargs="?", help=) parser.add_argument(, , type=str, help=) pars...
Entry point
9,876
def get_requests(self): safe = self.get_safe_struct() self.download_list = [] self.structure_recursion(safe, self.parent_folder) self.sort_download_list() return self.download_list, self.folder_list
Creates product structure and returns list of files for download :return: list of download requests :rtype: list(download.DownloadRequest)
9,877
def text(self): params = .join(x.text for x in self.params) return .format(self.proto_text, params)
Formatted Command declaration. This is the C declaration for the command.
9,878
def _combine_out_files(chr_files, work_dir, data): out_file = "%s.bed" % sshared.outname_from_inputs(chr_files) if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: for chr_file in chr_files:...
Concatenate all CNV calls into a single file.
9,879
def status_unreblog(self, id): id = self.__unpack_id(id) url = .format(str(id)) return self.__api_request(, url)
Un-reblog a status. Returns a `toot dict`_ with the status that used to be reblogged.
9,880
def create(sub_array_id): config = request.data config[] = .format(sub_array_id) return add_scheduling_block(config)
Create / register a Scheduling Block instance with SDP.
9,881
def depends_on_helper(obj): if isinstance(obj, AWSObject): return obj.title elif isinstance(obj, list): return list(map(depends_on_helper, obj)) return obj
Handles using .title if the given object is a troposphere resource. If the given object is a troposphere resource, use the `.title` attribute of that resource. If it's a string, just use the string. This should allow more pythonic use of DependsOn.
9,882
def p_contextualize_item(self, t): if len(t) == 5: t[0] = contextualize_item(t[2], t[4], line=t.lineno(1)) elif t[5] == "with": t[0] = contextualize_item(t[2], t[4], ctxt_tool=t[6], line=t.lineno(1)) else: t[0] = contextualize_item(t[2], t[4], num=t[...
contextualize_item : SYSTEM VAR CONFIGURE VAR | SYSTEM VAR CONFIGURE VAR STEP NUMBER | SYSTEM VAR CONFIGURE VAR WITH VAR
9,883
def main(http_port, peer_name, node_name, app_id): framework = pelix.framework.create_framework( (, , , , , , , , , , , , , , , , ...
Runs the framework :param http_port: HTTP port to listen to :param peer_name: Name of the peer :param node_name: Name (also, UID) of the node hosting the peer :param app_id: Application ID
9,884
def gen(self, text, start=0): for cc in self.chunkComment(text, start): c = self.extractChunkContent(cc) cc = .join(cc) m = self.matchComment(c) idx = text.index(cc, start) e = idx + len(cc) if m: assert text[idx:e...
Return the source code in text, filled with autogenerated code starting at start.
9,885
def patch_ast(node, source, sorted_children=False): if hasattr(node, ): return node walker = _PatchingASTWalker(source, children=sorted_children) ast.call_for_nodes(node, walker) return node
Patches the given node After calling, each node in `node` will have a new field named `region` that is a tuple containing the start and end offsets of the code that generated it. If `sorted_children` is true, a `sorted_children` field will be created for each node, too. It is a list containing ch...
9,886
def set(self, x): for name, value in iter(x.items()): if hasattr(value, "ndim"): if self[name].value.ndim < value.ndim: self[name].value.itemset(value.squeeze()) else: self[name].value = value else: ...
Set variable values via a dictionary mapping name to value.
9,887
def set_decade_lims(axis=None,direction=None): rxy if axis is None: axis = plt.gca() if direction is None or direction == : MIN,MAX = axis.get_xlim() MIN = 10 ** ( np.floor(np.log10(MIN)) ) MAX = 10 ** ( np.ceil (np.log10(MAX)) ) axis.set_xlim([MIN,MAX]) if directi...
r''' Set limits the the floor/ceil values in terms of decades. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. **direction** ([``None``] | ``'x'`` | ``'y'``) Limit the application to a certain direction (default: both).
9,888
def best_match(desired_language: {str, Language}, supported_languages: list, min_score: int=75) -> (str, int): if desired_language in supported_languages: return desired_language, 100 desired_language = standardize_tag(desired_language) if desired_language in supported...
You have software that supports any of the `supported_languages`. You want to use `desired_language`. This function lets you choose the right language, even if there isn't an exact match. Returns: - The best-matching language code, which will be one of the `supported_languages` or 'und' - Th...
9,889
def loads(cls, json_data): try: return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data)) except marshmallow.exceptions.ValidationError as exc: raise ValidationError("Failed to load message", extra=exc.args[0])
description of load
9,890
def join(*args, **kwargs): import os.path if _is_list(args[0]): return os.path.join(*args[0]) return os.path.join(*args, **kwargs)
Join parts of a path together
9,891
def send(data, channels=None, push_time=None, expiration_time=None, expiration_interval=None, where=None, cql=None): if expiration_interval and expiration_time: raise TypeError(t be setdata0proddevchannelspush_timeutcYYYY-MM-DDTHH:mm:ss.SSSZexpiration_timeexpiration_intervalwherewherecql/pushobjectId']...
发送推送消息。返回结果为此条推送对应的 _Notification 表中的对象,但是如果需要使用其中的数据,需要调用 fetch() 方法将数据同步至本地。 :param channels: 需要推送的频道 :type channels: list or tuple :param push_time: 推送的时间 :type push_time: datetime :param expiration_time: 消息过期的绝对日期时间 :type expiration_time: datetime :param expiration_interval: 消息过期的相对时间,从...
9,892
def markup_description(description): if apply_markdown: description = apply_markdown(description) else: description = escape(description).replace(, ) description = + description + return mark_safe(description)
Apply HTML markup to the given description.
9,893
def _augment_file(self, f): def get_url(target): if target.file_size is None: return None if target.file_name is not None: return self.base_url + .format(target.file_id.hex, target.file_name) else: return self.base_url...
Augment a FileRecord with methods to get the data URL and to download, returning the updated file for use in generator functions :internal:
9,894
def add_state_errors(self, errors): if not self.errors: self.errors = dict() if not in self.errors: self.errors[] = [] if type(errors) is not list: errors = [errors] for error in errors: if not isinstance(error, Error): ...
Add state errors Accepts a list of errors (or a single Error) coming from validators applied to entity as whole that are used for entity state validation The errors will exist on a __state__ property of the errors object. :param errors: list or Error, list of entity state validation er...
9,895
def to_serializable_dict(self, attrs_to_serialize=None, rels_to_expand=None, rels_to_serialize=None, key_modifications=None): return self.todict( attrs_to_serialize=attrs_to_serialize, rels_to...
An alias for `todict`
9,896
def render_mail_template(subject_template, body_template, context): try: subject = strip_spaces(render_to_string(subject_template, context)) body = render_to_string(body_template, context) finally: pass return subject, body
Renders both the subject and body templates in the given context. Returns a tuple (subject, body) of the result.
9,897
def tplot_save(names, filename=None): if isinstance(names,int): names = list(data_quants.keys())[names-1] if not isinstance(names, list): names = [names] for name in names: if isinstance(data_quants[name].data, list): for data_name in data_quants[name].dat...
This function will save tplot variables into a single file by using the python "pickle" function. This file can then be "restored" using tplot_restore. This is useful if you want to end the pytplot session, but save all of your data/options. All variables and plot options can be read back into tplot with the ...
9,898
def send_select_and_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(), config=opendnp3.TaskConfig().Default()): self.master.SelectAndOperate(command_set, callback, config)
Select and operate a set of commands :param command_set: set of command headers :param callback: callback that will be invoked upon completion or failure :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA
9,899
def get_ref_dict(self, schema): schema_key = make_schema_key(schema) ref_schema = build_reference( "schema", self.openapi_version.major, self.refs[schema_key] ) if getattr(schema, "many", False): return {"type": "array", "items": ref_schema} retur...
Method to create a dictionary containing a JSON reference to the schema in the spec