Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
357,000
def list_affinity_groups(kwargs=None, conn=None, call=None): if call != : raise SaltCloudSystemExit( ) if not conn: conn = get_conn() data = conn.list_affinity_groups() ret = {} for item in data.affinity_groups: ret[item.name] = object_to_dict(item...
.. versionadded:: 2015.8.0 List input endpoints associated with the deployment CLI Example: .. code-block:: bash salt-cloud -f list_affinity_groups my-azure
357,001
def timedelta_to_seconds(value, with_microseconds=False): if value is None: return None if not isinstance(value, timedelta): raise TypeError() microseconds = value.microseconds / MICROSECONDS_IN_SECOND \ if with_microseconds else 0 return value.days * SECONDS_IN_DAY + val...
Convert datetime.timedelta to seconds :param value: timedelta to convert :type value: datetime.timedelta :param with_microseconds: :type with_microseconds: bool :return: seconds/seconds with microseconds or None if val is None :rtype: int/float/None :raise: TypeError when val is not timedelt...
357,002
def run(self, steps=None, ipyclient=None, force=False, quiet=False): if not ipyclient: raise IPyradWarningExit("an ipyclient object is required") if not steps: steps = [1, 2, 3, 4] if isinstance(steps, (int, str)): steps = [int(i) ...
Submits an ordered list of jobs to a load-balancer to complete the following tasks, and reports a progress bar: (1) Write nexus files for each locus (2) Run mrBayes on each locus to get a posterior of gene trees (3) Run mbsum (a bucky tool) on the posterior set of trees (4) Run ...
357,003
def get_sentences_and_token_nodes(self): token_nodes = [] if self.ignore_sentence_annotations: mp = self.mmax_project layer_dict = mp.annotations[] file_id = self.get_file_id(self.name) sentence_anno_file = os.path.join(mp.projec...
Returns a list of sentence root node IDs and a list of sentences, where each list contains the token node IDs of that sentence. Both lists will be empty if sentences were not annotated in the original MMAX2 data. TODO: Refactor this! There's code overlap with self.add_annotation...
357,004
def main(**kwargs): options = ApplicationOptions(**kwargs) Event.configure(is_logging_enabled=options.event_logging) application = Application(options) application.run(options.definition)
The Pipeline tool.
357,005
def set_visible_graphs(self, visible_graph_list=None): if visible_graph_list is None: visible_graph_list = self.visible_graph_list vline = urwid.AttrWrap(urwid.SolidFill(u), ) graph_vector_column_list = [] for state, graph, sub_title in zip(visible_graph_list, ...
Show a column of the graph selected for display
357,006
def array2ntpl(arr): cls = collections.namedtuple(arr[2], arr[1]) return cls(*tuple(arr[0]))
Convert a :class:`numpy.ndarray` object constructed by :func:`ntpl2array` back to the original :func:`collections.namedtuple` representation. Parameters ---------- arr : ndarray Array representation of named tuple constructed by :func:`ntpl2array` Returns ------- ntpl : collections.n...
357,007
def FromStream(cls, stream): if stream.system: specifier = DataStreamSelector.MatchSystemOnly else: specifier = DataStreamSelector.MatchUserOnly return DataStreamSelector(stream.stream_type, stream.stream_id, specifier)
Create a DataStreamSelector from a DataStream. Args: stream (DataStream): The data stream that we want to convert.
357,008
async def list(self) -> List[str]: LOGGER.debug() rv = [p[] for p in await pool.list_pools()] LOGGER.debug(, rv) return rv
Return list of pool names configured, empty list for none. :return: list of pool names.
357,009
def find_in_bids(filename, pattern=None, generator=False, upwards=False, wildcard=True, **kwargs): if upwards and generator: raise ValueError() if pattern is None: pattern = _generate_pattern(wildcard, kwargs) lg.debug(f) if upwards and filename == find_root(file...
Find nearest file matching some criteria. Parameters ---------- filename : instance of Path search the root for this file pattern : str glob string for search criteria of the filename of interest (remember to include '*'). The pattern is passed directly to rglob. wildcard : ...
357,010
def update_host(name, data, **api_opts): o = get_host(name=name, **api_opts) return update_object(objref=o[], data=data, **api_opts)
Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={}
357,011
def define_frequencies(Ne, explicitly_antisymmetric=False): u omega_level = [Symbol(+str(i+1), real=True) for i in range(Ne)] if Ne > 9: opening = "\\" comma = "," open_brace = "{" close_brace = "}" else: opening = r"" comma = "" open_brace = "" ...
u"""Define all frequencies omega_level, omega, gamma. >>> from sympy import pprint >>> pprint(define_frequencies(2), use_unicode=True) ⎛ ⎡ 0 ω₁₂⎤ ⎡ 0 γ₁₂⎤⎞ ⎜[ω₁, ω₂], ⎢ ⎥, ⎢ ⎥⎟ ⎝ ⎣ω₂₁ 0 ⎦ ⎣γ₂₁ 0 ⎦⎠ We can make these matrices explicitly antisymmetric. ...
357,012
def fastaSubtract(fastaFiles): reads = {} firstFile = fastaFiles.pop(0) for seq in SeqIO.parse(firstFile, ): reads[seq.id] = seq for fastaFile in fastaFiles: for seq in SeqIO.parse(fastaFile, ): if seq.id in reads: assert str(seq.seq) == str...
Given a list of open file descriptors, each with FASTA content, remove the reads found in the 2nd, 3rd, etc files from the first file in the list. @param fastaFiles: a C{list} of FASTA filenames. @raises IndexError: if passed an empty list. @return: An iterator producing C{Bio.SeqRecord} instances ...
357,013
def _checkparams(digest_size, key, salt, person): ensure(isinstance(key, bytes), , raising=exc.TypeError) ensure(isinstance(salt, bytes), , raising=exc.TypeError) ensure(isinstance(person, bytes), , raising=exc.TypeError) ensure(i...
Check hash paramters
357,014
def basic_interior_combine(intersections, max_edges=10): unused = intersections[:] result = [] while unused: start = unused.pop() curr_node = start next_node = get_next(curr_node, intersections, unused) edge_ends = [(curr_node, next_node)] while next_node is not ...
Combine intersections that don't involve tangencies. .. note:: This is a helper used only by :func:`combine_intersections`. .. note:: This helper assumes ``intersections`` isn't empty, but doesn't enforce it. Args: intersections (List[.Intersection]): Intersections from eac...
357,015
def get_resource(self, device_id, resource_path): resources = self.list_resources(device_id) for r in resources: if r.path == resource_path: return r raise CloudApiException("Resource not found")
Get a resource. :param str device_id: ID of the device (Required) :param str path: Path of the resource to get (Required) :returns: Device resource :rtype Resource
357,016
def inequalityQuery(self, constraint, count, isAscending): if self.baseConstraint is not None: if constraint is not None: constraint = AND(self.baseConstraint, constraint) else: constraint = self.baseConstraint currentSortAttribut...
Perform a query to obtain some rows from the table represented by this model, at the behest of a networked client. @param constraint: an additional constraint to apply to the query. @type constraint: L{axiom.iaxiom.IComparison}. @param count: the maximum number of rows to retur...
357,017
def weight_to_comm(self, v, comm): return _c_louvain._MutableVertexPartition_weight_to_comm(self._partition, v, comm)
The total number of edges (or sum of weights) from node ``v`` to community ``comm``. See Also -------- :func:`~VertexPartition.MutableVertexPartition.weight_from_comm`
357,018
def enforce_reversible_on_closed(P): import msmtools.analysis as msmana n = np.shape(P)[0] Prev = P.copy() sets = closed_sets(P) for s in sets: I = np.ix_(s, s) pi_s = msmana.stationary_distribution(P[I]) X_s = pi_s[:, None] * P[I] X_s = 0....
Enforces transition matrix P to be reversible on its closed sets.
357,019
def load_configs(self, conf_file): with open(conf_file) as stream: lines = itertools.chain(("[global]",), stream) self._config.read_file(lines) return self._config[]
Assumes that the config file does not have any sections, so throw it all in global
357,020
def add_layer(self, label, change_layer=True): self.layer_stack.insert(self.last_layer() + 1, label) if change_layer: self.set_current_layer(self.last_layer()) return None
Add new mesh layer to the end of the stack Args: label (str): new label for the mesh layer change_layer (bool): change to the newly created layer
357,021
def ConstructArray(self, py_arr): arr = self.NewArray(len(py_arr)) arr._init(py_arr) return arr
note py_arr elems are NOT converted to PyJs types!
357,022
def remove_coreference_layer(self): if self.coreference_layer is not None: this_node = self.coreference_layer.get_node() self.root.remove(this_node) if self.header is not None: self.header.remove_lp()
Removes the constituency layer (if exists) of the object (in memory)
357,023
def output(self, name=,dest=): "Output PDF to some destination" if(self.state<3): self.close() dest=dest.upper() if(dest==): if(name==): name= dest= else: dest= if dest==: pri...
Output PDF to some destination
357,024
def health_check(self): response = self.get() if not response: response = self.get() return response
Get health status https://confluence.atlassian.com/jirakb/how-to-retrieve-health-check-results-using-rest-api-867195158.html :return:
357,025
def add_path(self, path, pattern="*.json"): if os.path.isdir(path): configs = glob.glob(_opj(path, pattern)) else: configs = [path] for config in configs: cfg = dbconfig.DBConfig(config_file=config) cs = cfg.settings ...
Add configuration file(s) in `path`. The path can be a single file or a directory. If path is a directory, then `pattern` (Unix glob-style) will be used to get a list of all config files in the directory. The name given to each file is the database name and collection na...
357,026
def ws45(msg): d = hex2bin(data(msg)) if d[3] == : return None ws = bin2int(d[4:6]) return ws
Wind shear. Args: msg (String): 28 bytes hexadecimal message string Returns: int: Wind shear level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
357,027
def parse_text(self, text): text = text.strip() lines = text.splitlines() parsed_lines = [] encountered_date = False for (lineno, line) in enumerate(lines, 1): try: parsed_line = self.parse_line(line) if isinstance(parsed_lin...
Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`, :class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an error during parsing, a :exc:`taxi.exceptions.ParseError` will be raised.
357,028
def get_all_alarms(region=None, prefix=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) alarms = conn.describe_alarms() results = odict.OrderedDict() for alarm in alarms: alarm = _metric_alarm_to_dict(alarm...
Get all alarm details. Produces results that can be used to create an sls file. If prefix parameter is given, alarm names in the output will be prepended with the prefix; alarms that have the prefix will be skipped. This can be used to convert existing alarms to be managed by salt, as follows: ...
357,029
def add_options(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs)
Shortcut for add_route with method OPTIONS
357,030
def crossmap(fas, reads, options, no_shrink, keepDB, threads, cluster, nodes): if cluster is True: threads = btc = [] for fa in fas: btd = bowtiedb(fa, keepDB) F, R, U = reads if F is not False: if U is False: u = False for i, f i...
map all read sets against all fasta files
357,031
def responsive_sleep(self, seconds, wait_reason=): for x in xrange(int(seconds)): if (self.config.wait_log_interval and not x % self.config.wait_log_interval): self.config.logger.debug( % (wait_reason, x, seconds) ) ...
Sleep for the specified number of seconds, logging every 'wait_log_interval' seconds with progress info.
357,032
def sim_trainer(trainer, mean=0, std=1): return sim_network(network=trainer.module, ds=trainer.ds, mean=mean, std=std)
Simulate a trainer by activating its DataSet and returning DataFrame(columns=['Output','Target'])
357,033
def declarative_fields(cls_filter, meta_base=type, extra_attr_name=): def __new__(cls, name, bases, attrs): attrs[extra_attr_name] = fields = get_declared_fields(bases, attrs, cls_filter, extra_attr_name=extra_attr_name) attrs[extra_attr_name + ] = set(fields.keys()) new...
Metaclass that converts Field attributes to a dictionary called 'base_fields', taking into account parent class 'cls_filter'.
357,034
def _file_details(filename): max_head, max_foot = _max_lengths() with open(filename, "rb") as fin: head = fin.read(max_head) try: fin.seek(-max_foot, os.SEEK_END) except IOError: fin.seek(0) foot = fin.read() return head, foot
Grab the start and end of the file
357,035
def withArgs(self, *args, **kwargs): cond_args = args if len(args) > 0 else None cond_kwargs = kwargs if len(kwargs) > 0 else None return _SinonStubCondition(copy=self._copy, cond_args=cond_args, cond_kwargs=cond_kwargs, oncall=self._oncall)
Adds a condition for when the stub is called. When the condition is met, a special return value can be returned. Adds the specified argument(s) into the condition list. For example, when the stub function is called with argument 1, it will return "#": stub.withArgs(1).returns("#") ...
357,036
def ensure_workspace(self, target): gopath = self.get_gopath(target) for d in (, , ): safe_mkdir(os.path.join(gopath, d)) required_links = set() for dep in target.closure(): if not isinstance(dep, GoTarget): continue if self.is_remote_lib(dep): self._symlink_remote...
Ensures that an up-to-date Go workspace exists for the given target. Creates any necessary symlinks to source files based on the target and its transitive dependencies, and removes any symlinks which do not correspond to any needed dep.
357,037
def get(self, sid): return TerminatingSipDomainContext(self._version, trunk_sid=self._solution[], sid=sid, )
Constructs a TerminatingSipDomainContext :param sid: The unique string that identifies the resource :returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainContext :rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainContext
357,038
def to_xdr_object(self): def assert_option_array(x): if x is None: return [] if not isinstance(x, list): return [x] return x if self.inflation_dest is not None: inflation_dest = [account_xdr_object(self.inflation_...
Creates an XDR Operation object that represents this :class:`SetOptions`.
357,039
def items(self): self.__init() items = [] for item in self._items: items.append( UserItem(url="%s/items/%s" % (self.location, item[]), securityHandler=self._securityHandler, proxy_url=self._proxy_url, ...
gets the property value for items
357,040
def index_registry(args, reg, ts=None, idx=None): rargs = dict.fromkeys(args) for k, v in args.iteritems(): is_dynamic = idx and not reg.isconstant.get(v) if isinstance(v, basestring): rargs[k] = reg...
Index into a :class:`~simkit.core.Registry` to return arguments from :class:`~simkit.core.data_sources.DataRegistry` and :class:`~simkit.core.outputs.OutputRegistry` based on the calculation parameter file. :param args: Arguments field from the calculation parameter file. :param reg: Registry in wh...
357,041
def _match_transition(self, transition): return (self.names == or transition in self.names or transition.name in self.names)
Checks whether a given Transition matches self.names.
357,042
def json_compat_obj_encode(data_type, obj, caller_permissions=None, alias_validators=None, old_style=False, for_msgpack=False, should_redact=False): serializer = StoneToPythonPrimitiveSerializer( caller_permissions, alias_validators, for_msgpack, old_style, should_redact) ...
Encodes an object into a JSON-compatible dict based on its type. Args: data_type (Validator): Validator for obj. obj (object): Object to be serialized. caller_permissions (list): The list of raw-string caller permissions with which to serialize. Returns: An object t...
357,043
def connect(self, receiver, signal, function, description, sender=None): return self.__app.signals.connect(receiver, signal, function, self._plugin, description, sender)
Connect a receiver to a signal :param receiver: Name of the receiver :type receiver: str :param signal: Name of the signal. Must already be registered! :type signal: str :param function: Callable functions, which shall be executed, of signal is send. :param description: ...
357,044
def signed_in_users(session=None, today=None, full_name=True): if session is None: session = Session() else: session = session if today is None: today = date.today() else: today = today signed_in_users = ( session .query(User) .filter(E...
Return list of names of currently signed in users. :param session: SQLAlchemy session through which to access the database. :param today: (optional) The current date as a `datetime.date` object. Used for testing. :param full_name: (optional) Whether to display full user names, or just first names. :ret...
357,045
def cross(self, vec): return self.x * vec.y - vec.x * self.y
Return the 2d cross product of self with another vector. Cross product doesn't make sense in 2D, but return the Z component of the 3d result.
357,046
def from_str(cls, s): r if in s: try: tokens_and_strings = parse(s) except ValueError: return FmtStr(Chunk(remove_ansi(s))) else: chunks = [] cur_fmt = {} for x in tokens_and_st...
r""" Return a FmtStr representing input. The str() of a FmtStr is guaranteed to produced the same FmtStr. Other input with escape sequences may not be preserved. >>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue')+"|") '|'+on_blue(red('hey'))+'|' >>> fmtstr('|\x1b[31m\x1b...
357,047
def _parse_arg_list(arglist): args = [] for arg in arglist.split(): arg = arg.strip() if arg: args.append(eval(arg)) return args
Parses a list of arguments. Arguments are expected to be split by a comma, surrounded by any amount of whitespace. Arguments are then run through Python's eval() method.
357,048
def tree2commands(self, adapter, session, lastcmds, xsync): assert xsync.tag == constants.NODE_SYNCML assert len(xsync) == 2 assert xsync[0].tag == constants.CMD_SYNCHDR assert xsync[1].tag == constants.NODE_SYNCBODY version = xsync[0].findtext() if version != constants.SYNCML_...
Consumes an ET protocol tree and converts it to state.Command commands
357,049
def qualified_term(self): assert self.parent is not None or self.parent_term_lc == if self.parent: return self.parent.record_term_lc + + self.record_term_lc else: return + self.record_term_lc
Return the fully qualified term name. The parent will be 'root' if there is no parent term defined.
357,050
def write8(self, value, char_mode=False): self._delay_microseconds(1000) self._rs.set(char_mode) self._d4.set(((value >> 4) & 1) > 0) self._d5.set(((value >> 5) & 1) > 0) self._d6.set(((value >> 6) & 1) > 0) self._d7.set(((value >> 7) &...
Write 8-bit value in character or data mode. Value should be an int value from 0-255, and char_mode is True if character data or False if non-character data (default).
357,051
def save_entity_signal_handler(sender, instance, **kwargs): if instance.__class__ in entity_registry.entity_registry: sync_entities(instance) if instance.__class__ in entity_registry.entity_watching: sync_entities_watching(instance)
Defines a signal handler for saving an entity. Syncs the entity to the entity mirror table.
357,052
def render(obj, backend=None, **kwargs): backend = backend or Store.current_backend renderer_obj = renderer(backend) if kwargs: renderer_obj = renderer_obj.instance(**kwargs) plot = renderer_obj.get_plot(obj) if backend == and len(plot) > 1: return plot.anim(fps=renderer_obj.fp...
Renders the HoloViews object to the corresponding object in the specified backend, e.g. a Matplotlib or Bokeh figure. The backend defaults to the currently declared default backend. The resulting object can then be used with other objects in the specified backend. For instance, if you want to make a ...
357,053
def get_fastq_files_props(self,barcode=None): fastqs = self.get_fastq_dxfile_objects(barcode=barcode) dico = {} for f in fastqs: props = f.get_properties() dico[f] = props dico[f]["fastq_file_name"] = f.name return dico
Returns the DNAnexus file properties for all FASTQ files in the project that match the specified barcode, or all FASTQ files if not barcode is specified. Args: barcode: `str`. If set, then only FASTQ file properties for FASTQ files having the specified barcode are returned. Re...
357,054
def container(self): if self.parent is None: return None elif self.location is None: return self.parent.content else: container = getattr(self.parent, self.location) if isinstance(container, (ListContainer, DictContainer)): ...
Rarely used attribute that returns the ``ListContainer`` or ``DictContainer`` that contains the element (or returns None if no such container exist) :rtype: ``ListContainer`` | ``DictContainer`` | ``None``
357,055
def evaluate_http_conditionals(dav_res, last_modified, entitytag, environ): if not dav_res: return if "HTTP_IF_MATCH" in environ and dav_res.support_etag(): ifmatchlist = environ["HTTP_IF_MATCH"].split(",") for ifmatchtag in ifmatchlist: i...
Handle 'If-...:' headers (but not 'If:' header). If-Match @see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for methods like PUT to only update a resource ...
357,056
def keypair_setup(): os.system( + u.PRIVATE_KEY_LOCATION) keypair_name = u.get_keypair_name() keypair = u.get_keypair_dict().get(keypair_name, None) keypair_fn = u.get_keypair_fn() if keypair: print("Reusing keypair " + keypair_name) assert os.path.exists( keypair_fn), "Keypair %s exis...
Creates keypair if necessary, saves private key locally, returns contents of private key file.
357,057
def set(self, value): self._value = self._setter(self._node, value, self._value) if self._setter else value
Sets value
357,058
def StartTiming(self, profile_name): if profile_name not in self._profile_measurements: self._profile_measurements[profile_name] = CPUTimeMeasurement() self._profile_measurements[profile_name].SampleStart()
Starts timing CPU time. Args: profile_name (str): name of the profile to sample.
357,059
def unstack(self, unstacker_func, fill_value): n_rows = self.shape[-1] dummy = unstacker_func(np.empty((0, 0)), value_columns=self.items) new_columns = dummy.get_new_columns() new_index = dummy.get_new_index() new_blocks = [] columns_mask = [] for blk in...
Return a blockmanager with all blocks unstacked. Parameters ---------- unstacker_func : callable A (partially-applied) ``pd.core.reshape._Unstacker`` class. fill_value : Any fill_value for newly introduced missing values. Returns ------- ...
357,060
def _get_flat_path(path_pb): num_elts = len(path_pb.element) last_index = num_elts - 1 result = [] for index, element in enumerate(path_pb.element): result.append(element.type) _add_id_or_name(result, element, index == last_index) return tuple(result)
Convert a legacy "Path" protobuf to a flat path. For example Element { type: "parent" id: 59 } Element { type: "child" name: "naem" } would convert to ``('parent', 59, 'child', 'naem')``. :type path_pb: :class:`._app_engine_key_pb2....
357,061
def same_tech(self, other: Union[UnitTypeId, Set[UnitTypeId], List[UnitTypeId], Dict[UnitTypeId, Any]]) -> "Units": if isinstance(other, UnitTypeId): other = {other} tech_alias_types = set(other) for unitType in other: tech_alias = self.game_data.units[unitType.v...
Usage: 'self.units.same_tech(UnitTypeId.COMMANDCENTER)' or 'self.units.same_tech(UnitTypeId.ORBITALCOMMAND)' returns all CommandCenter, CommandCenterFlying, OrbitalCommand, OrbitalCommandFlying, PlanetaryFortress This also works with a set/list/dict parameter, e.g. 'self.units.same_tech({UnitTyp...
357,062
def image_to_colorlist(image, container=list): deprecated.deprecated() return container(convert_mode(image).getdata())
Given a PIL.Image, returns a ColorList of its pixels.
357,063
def remove_example(self, data, cloud=None, batch=False, api_key=None, version=None, **kwargs): batch = detect_batch(data) data = data_preprocess(data, batch=batch) url_params = {"batch": batch, "api_key": api_key, "version": version, : } return self._api_handler(data, cloud=clou...
This is an API made to remove a single instance of training data. This is useful in cases where a single instance of content has been modified, but the remaining examples remain valid. For example, if a piece of content has been retagged. Inputs data - String: The exact text you wish to...
357,064
def _from_dict(cls, _dict): args = {} if in _dict: args[] = _dict.get() else: raise ValueError( custom_language_model\ ) if in _dict: args[] = _dict.get() else: raise ValueError( ...
Initialize a SupportedFeatures object from a json dictionary.
357,065
def get_local_file_dist(self): if not os.path.isfile(self.path): return log.info( .format(self.path)) try: dist = self._do_download(find_links=[self.path]) except Exception as e: if DEBUG: raise ...
Handle importing from a source archive; this also uses setup_requires but points easy_install directly to the source archive.
357,066
def wrap(self, LayoutClass, *args, **kwargs): def wrap_object(layout_object, j): layout_object.fields[j] = self.wrapped_object( LayoutClass, layout_object.fields[j], *args, **kwargs ) self.pre_map(wrap_object)
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with `args` and `kwargs` passed.
357,067
def get_type(tokens, start_index): i = start_index tok_type = tokens[i][0] start = tokens[i][2] pos = start line_type = None while i < len(tokens) and tokens[i][2][0] == start[0]: tok_type = tokens[i][0] pos = tokens[i][3] if line_type is None: if tok_typ...
return the line type : docstring, comment, code, empty
357,068
def run(self): self.input_channel.basic_consume(self.handle_message, queue=self.INPUT_QUEUE_NAME, no_ack=True ) try: self.input_channel.start_consuming() ...
actual consuming of incoming works starts here
357,069
def on_after_transform_template(self, template): if self._wait_for_template_active_status and not self._validate_only: start_time = time() while (time() - start_time) < self.TEMPLATE_WAIT_TIMEOUT_SECONDS: temp = self._in_progress_templates self._i...
Hook method that gets called after the template is processed Go through all the stored applications and make sure they're all ACTIVE. :param dict template: Dictionary of the SAM template :return: Nothing
357,070
def detect_events(self, max_attempts=3): for _ in xrange(max_attempts): try: with KindleCloudReaderAPI\ .get_instance(self.uname, self.pword) as kcr: self.books = kcr.get_library_metadata() self.progres...
Returns a list of `Event`s detected from differences in state between the current snapshot and the Kindle Library. `books` and `progress` attributes will be set with the latest API results upon successful completion of the function. Returns: If failed to retrieve progress, ...
357,071
def mouseMoveEvent(self, event): if not self.scene: return if self.event_sel or self.deselect: return if self.sel_xy[0] is None or self.sel_xy[1] is None: return if self.idx_sel in self.scene.items(): self.scene.removeItem(self....
When normal selection, update power spectrum with current selection. Otherwise, show the range of the new marker.
357,072
def _get_weights(max_length): weights = [1] for i in range(1, max_length): weights.append(weights[i-1] * len(_ALPHABET) + 1) weights.reverse() return weights
Get weights for each offset in str of certain max length. Args: max_length: max length of the strings. Returns: A list of ints as weights. Example: If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa", "ab", "b", "ba", "bb". So the weight for the first char is 3.
357,073
def load_background_sky_map(background_sky_map_path, background_sky_map_hdu, pixel_scale): if background_sky_map_path is not None: return ScaledSquarePixelArray.from_fits_with_pixel_scale(file_path=background_sky_map_path, hdu=background_...
Factory for loading the background sky from a .fits file. Parameters ---------- background_sky_map_path : str The path to the background_sky_map .fits file containing the background sky map \ (e.g. '/path/to/background_sky_map.fits'). background_sky_map_hdu : int The hdu the bac...
357,074
def sign_item(encrypted_item, signing_key, crypto_config): signature = signing_key.sign( algorithm=signing_key.algorithm, data=_string_to_sign( item=encrypted_item, table_name=crypto_config.encryption_context.table_name, attribute_actions=crypto_config.a...
Generate the signature DynamoDB atttribute. :param dict encrypted_item: Encrypted DynamoDB item :param DelegatedKey signing_key: DelegatedKey to use to calculate the signature :param CryptoConfig crypto_config: Cryptographic configuration :returns: Item signature DynamoDB attribute value :rtype: di...
357,075
def ensure_context_attribute_exists(context, name, default_value=None): if not hasattr(context, name): setattr(context, name, default_value)
Ensure a behave resource exists as attribute in the behave context. If this is not the case, the attribute is created by using the default_value.
357,076
def plot_heterozygosity(heterozygosity, options): import matplotlib as mpl if options.format != "X11" and mpl.get_backend() != "agg": mpl.use("Agg") import matplotlib.pyplot as plt if options.format != "X11": plt.ioff() figsize = (13.5, 8) if options.boxplot: ...
Plots the heterozygosity rate distribution. :param heterozygosity: the heterozygosity data. :param options: the options. :type heterozygosity: numpy.array :type options: argparse.Namespace Plots a histogram or a boxplot of the heterozygosity distribution.
357,077
def init_logging(stream=sys.stderr, filepath=None, format=): if not (len(logger.handlers) == 1 and isinstance(logger.handlers[0], logging.NullHandler)): logger.warn() return formatter = logging.Formatter(format) if stream is not None: handler = logging.StreamHan...
Setup logging for the microcache module, but only do it once! :param stream: stream to log to (defaults to sys.stderr) :param filepath: path to a file to log to as well (defaults to None) :param format: override the default format with whatever you like
357,078
def render_GET(self, request): request.setHeader(b, b) producer = self.makeProducer(request, self.fileObject) if request.method == b: return b def done(ign): producer.stopProducing() request.notifyFinish().addCallbacks(done, done) prod...
Begin sending the contents of this L{File} (or a subset of the contents, based on the 'range' header) to the given request.
357,079
def run_cleanup(build_ext_cmd): if not build_ext_cmd.inplace: return bezier_dir = os.path.join("src", "bezier") shutil.move(os.path.join(build_ext_cmd.build_lib, LIB_DIR), bezier_dir) shutil.move(os.path.join(build_ext_cmd.build_lib, DLL_DIR), bezier_dir)
Cleanup after ``BuildFortranThenExt.run``. For in-place builds, moves the built shared library into the source directory.
357,080
def reschedule(self, date, callable_name=None, content_object=None, expires=, args=None, kwargs=None): if isinstance(date, basestring): date = parse_timedelta(date) if isinstance(date, datetime.timedelta): date = self.time_slot_start + date ...
Schedule a clone of this job.
357,081
def from_shorthand(self, shorthand): name = octave = 0 for x in shorthand: if x in [, , , , , , ]: name = str.upper(x) octave = 3 elif x in [, , , , , , ]: name = x octave = 2 elif x in ...
Convert from traditional Helmhotz pitch notation. Examples: >>> Note().from_shorthand("C,,") 'C-0' >>> Note().from_shorthand("C") 'C-2' >>> Note().from_shorthand("c'") 'C-4'
357,082
def host_config(self): if platform.system() == : default_file_dir = join(expanduser(), ) else: default_file_dir = status = self.ensure_dir(default_file_dir) if not isfile(self.cfg_file): config = Template(t...
Ensure the host configuration file exists
357,083
def _parse(self): with open(self.path, "rt") as reader: return ast.parse(reader.read(), filename=self.path)
Parses file contents :return: Tree hierarchy of file
357,084
def ensureModelData(self,obj): if not hasattr(obj,"_modeldata"): self.create(obj,cache=True) if "_modelcache" not in obj._modeldata: self.create(obj,cache=True)
Ensures that the given ``obj`` has been initialized to be used with this model. If the object is found to not be initialized, it will be initialized.
357,085
def convert(model, feature_names, target): if not(_HAS_SKLEARN): raise RuntimeError() _sklearn_util.check_expected_type(model, LogisticRegression) _sklearn_util.check_fitted(model, lambda m: hasattr(m, )) return _MLModel(_convert(model, feature_names, target))
Convert a Logistic Regression model to the protobuf spec. Parameters ---------- model: LogisticRegression A trained LogisticRegression model. feature_names: [str], optional (default=None) Name of the input columns. target: str, optional (default=None) Name of the output col...
357,086
def _simulated_mana_drain(self, mana_drain_state): mana_drain_state.player.apply_mana_drain() mana_drain_state.opponent.apply_mana_drain() mana_drain_state.actions_remaining = 0 if self.random_fill: random_start_board = mana_drain_state.boa...
Apply mana drain effects to this state, attach a mana drain EOT and return the mana drain EOT.
357,087
def name(self): if self.path: name = self.path if name[0] != : name = + name return name return None
Array name following h5py convention.
357,088
def initialize_from_string(content: str) -> : if content is None or content is "": return None lines = content.splitlines() min_x = sys.maxsize max_x = 0 min_y = sys.maxsize max_y = 0 symbol_name = lines[0] strokes = [] for...
Create and initializes a new symbol from a string :param content: The content of a symbol as read from the text-file :return: The initialized symbol :rtype: HomusSymbol
357,089
def choose_parsimonious_states(tree, ps_feature, out_feature): num_scenarios = 1 unresolved_nodes = 0 num_states = 0 for node in tree.traverse(): states = getattr(node, ps_feature) node.add_feature(out_feature, states) n = len(states) num_scenarios *= n unres...
Converts the content of the get_personalized_feature_name(feature, PARS_STATES) node feature to the predicted states and stores them in the `feature` feature to each node. The get_personalized_feature_name(feature, PARS_STATES) is deleted. :param feature: str, character for which the parsimonious states ar...
357,090
def check_colormap(cmap): names = set([, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]) if cmap not in names: raise Exception("Invalid cmap , must be one of %s" % (cmap, names)) else: return cmap
Check if cmap is one of the colorbrewer maps
357,091
def deserialize_json(stream, username): parsed_json = JSONParser().parse(stream) serializer_class = get_serializer_class(apps.get_model(parsed_json["model"])) list_serializer = serializer_class(data=parsed_json["data"], context={"changed_by_username": username}, many=True) if list_serializer.is_val...
Given a stream containing JSON, deserializers the JSON into ConfigurationModel instances. The stream is expected to be in the following format: { "model": "config_models.ExampleConfigurationModel", "data": [ { "enabled": True, "color": "black" ...
357,092
def fields_general(self, event): result = self._fields_common() basic = { "__test_html__": self.repo.testing.html(False), "__test_text__": self.repo.testing.text(False)} full = { "__test_html__": self.repo.testing.html(), "__test_text__": ...
Appends any additional fields to the common ones and returns the fields dictionary.
357,093
def get_scans(self): code, data = self.send_request(, method=) if code != 200: msg = raise APIException(msg % code) scans = data.get(, None) if scans is None: raise APIException() scan_instances = [] for scan_json in scans...
:return: A list with all the Scan instances available in the remote API
357,094
def reload_file(self, is_modified=True): if not foundations.common.path_exists(self.__file): raise foundations.exceptions.FileExistsError("{0} | file doesn{0}' file.".format(self.__file)) reader = foundations.io.File(self.__file) if reader.cache(): self.set_con...
Reloads the current editor file. :param is_modified: File modified state. :type is_modified: bool :return: Method success. :rtype: bool
357,095
def process_nxml(nxml_filename, pmid=None, extra_annotations=None, cleanup=True, add_grounding=True): if extra_annotations is None: extra_annotations = {} pp_dir = tempfile.mkdtemp() pp = IsiPreprocessor(pp_dir) extra_annotations = {} pp.preprocess_nxml_file(nxml...
Process an NXML file using the ISI reader First converts NXML to plain text and preprocesses it, then runs the ISI reader, and processes the output to extract INDRA Statements. Parameters ---------- nxml_filename : str nxml file to process pmid : Optional[str] pmid of this nxml...
357,096
def serve(self, liveport=None, host=None, restart_delay=2): host = host or logger.info( % (host, liveport)) self.application(host, liveport=liveport) try: self.watcher._changes.append((, restart_delay)) LiveReloadHandler.start_tasks() IOLoo...
Start serve the server with the given port. :param liveport: live reload on this port :param host: serve on this hostname, default is 127.0.0.1 :param open_url_delay: open webbrowser after the delay seconds
357,097
def mutation_jwt_required(fn): @wraps(fn) def wrapper(cls, *args, **kwargs): token = kwargs.pop(current_app.config[]) try: verify_jwt_in_argument(token) except Exception as e: return cls(AuthInfoField(message=str(e))) return fn(cls, *args, **kwargs) ...
A decorator to protect a mutation. If you decorate a mutation with this, it will ensure that the requester has a valid access token before allowing the mutation to be called. This does not check the freshness of the access token.
357,098
def circulation(self): L = self.angular_momentum() if L.ndim == 2: single_orbit = True L = L[...,None] else: single_orbit = False ndim,ntimes,norbits = L.shape L0 = L[:,0] circ = np.ones((ndim,nor...
Determine which axes the Orbit circulates around by checking whether there is a change of sign of the angular momentum about an axis. Returns a 2D array with ``ndim`` integers per orbit point. If a box orbit, all integers will be 0. A 1 indicates circulation about the corresponding axis....
357,099
def apply_filters(stream, filters, lexer=None): def _apply(filter_, stream): for token in filter_.filter(lexer, stream): yield token for filter_ in filters: stream = _apply(filter_, stream) return stream
Use this method to apply an iterable of filters to a stream. If lexer is given it's forwarded to the filter, otherwise the filter receives `None`.