Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
343,100
def fetch_order_book(self) -> OrderBook: return self._fetch(, self.market.code)(self._order_book)()
Fetch the order book.
343,101
def ingest_flash(self): self.flash = extract_flash(self.hdulist[0].header, self.hdulist[1]) if self.flash is None: self.flash = np.zeros_like(self.science) return if self.flshcorr != : self.science = self.science - self.f...
Process post-flash.
343,102
def read_scoring_scheme( f, gap_open, gap_extend, gap1="-", gap2=None, **kwargs ): close_it = False if (type(f) == str): f = file(f,"rt") close_it = True ss = build_scoring_scheme("".join([line for line in f]),gap_open, gap_extend, gap1=gap1, gap2=gap2, **kwargs) if (close_it): ...
Initialize scoring scheme from a file containint a blastz style text blob. f can be either a file or the name of a file.
343,103
def commit(self): if self._fetched is None: raise RuntimeError() self._cache = self._cache[self._fetched:] self._fetched = None
Actually remove data returned by fetch() from the cache.
343,104
def export_to_tf_tensor(self, x, laid_out_x): return self.combine_slices(laid_out_x.all_slices, x.shape)
Turn a Tensor into a tf.Tensor. Args: x: a Tensor laid_out_x: a LaidOutTensor Returns: a tf.Tensor
343,105
def add_listener(self, include_value=False, item_added_func=None, item_removed_func=None): request = queue_add_listener_codec.encode_request(self.name, include_value, False) def handle_event_item(item, uuid, event_type): item = item if include_value else None member = s...
Adds an item listener for this queue. Listener will be notified for all queue add/remove events. :param include_value: (bool), whether received events include the updated item or not (optional). :param item_added_func: Function to be called when an item is added to this set (optional). :param i...
343,106
def renamed(self, source, dest): filename = osp.abspath(to_text_string(source)) index = self.editorstacks[0].has_filename(filename) if index is not None: for editorstack in self.editorstacks: editorstack.rename_in_data(filename, ...
File was renamed in file explorer widget or in project explorer
343,107
def _rm_mods(pre_mods, post_mods): pre = set() post = set() for mod in pre_mods: pre.add(mod[]) for mod in post_mods: post.add(mod[]) return pre - post
Return a list of the new modules, pass an lsmod dict before running modprobe and one after modprobe has run
343,108
def forward(self, observations): input_data = self.input_block(observations) base_output = self.backbone(input_data) policy_params = self.action_head(base_output) q = self.q_head(base_output) return policy_params, q
Calculate model outputs
343,109
def start_thread(self, target, args=(), kwargs=None, priority=0): return self.add_task(target, args, kwargs, priority)
To make sure applications work with the old name
343,110
def numericshape(self): try: numericshape = [self.subseqs.seqs.model.numconsts.nmb_stages] except AttributeError: objecttools.augment_excmessage( % (self.name, objecttools.devicename(self...
Shape of the array of temporary values required for the numerical solver actually being selected.
343,111
def dataset_list(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, mine=False, ...
return a list of datasets! Parameters ========== sort_by: how to sort the result, see valid_sort_bys for options size: the size of the dataset, see valid_sizes for string options file_type: the format, see valid_file_types for string options licen...
343,112
def generate_airflow_spec(name, pipeline_spec): task_definitions = up_steam_statements = parameters = pipeline_spec.get() for (task_id, task_details) in sorted(pipeline_spec[].items()): task_def = PipelineGenerator._get_operator_definition(task_id, task_details, parameters) task_defin...
Gets the airflow python spec for the Pipeline object.
343,113
def _handle_dl_term(self): self._context ^= contexts.DL_TERM if self._read() == ":": self._handle_list_marker() else: self._emit_text("\n")
Handle the term in a description list (``foo`` in ``;foo:bar``).
343,114
def setup(title, output=, timezone=None): timezone = timezone or dna.time_utils._detect_timezone() broker_url = .format( os.environ.get(, ), os.environ.get(, 6379), 0 ) app = Celery(title, broker=broker_url) app.conf.update( CELERY_TASK_SERIALIZER=output, ...
Implement celery workers using json and redis
343,115
def load_common(model_cls, data): obj = model_cls(**data) db.session.add(obj) db.session.commit()
Helper function for loading JSON data verbatim into model.
343,116
def parse_script(output_script): script_iterator = output_script.raw_iter() try: first_opcode, _, _ = next(script_iterator, (None, None, None)) _, data, _ = next(script_iterator, (None, None, None)) remainder = next(script_iterator, None) except bitc...
Parses an output and returns the payload if the output matches the right pattern for a marker output, or None otherwise. :param CScript output_script: The output script to be parsed. :return: The marker output payload if the output fits the pattern, None otherwise. :rtype: bytes
343,117
def server_group_list(request): try: return api.nova.server_group_list(request) except Exception: exceptions.handle(request, _()) return []
Utility method to retrieve a list of server groups.
343,118
def createMask(input=None, static_sig=4.0, group=None, editpars=False, configObj=None, **inputDict): if input is not None: inputDict["static_sig"]=static_sig inputDict["group"]=group inputDict["updatewcs"]=False inputDict["input"]=input else: print >> sys.stderr, "P...
The user can input a list of images if they like to create static masks as well as optional values for static_sig and inputDict. The configObj.cfg file will set the defaults and then override them with the user options.
343,119
def rho_block_D_inv_A(A, Dinv): if not hasattr(A, ): from scipy.sparse.linalg import LinearOperator blocksize = Dinv.shape[1] if Dinv.shape[1] != Dinv.shape[2]: raise ValueError() elif Dinv.shape[0] != int(A.shape[0]/blocksize): raise ValueError() ...
Return the (approx.) spectral radius of block D^-1 * A. Parameters ---------- A : sparse-matrix size NxN Dinv : array Inverse of diagonal blocks of A size (N/blocksize, blocksize, blocksize) Returns ------- approximate spectral radius of (Dinv A) Examples -...
343,120
def make_camera(cam_type, *args, **kwargs): cam_types = {None: BaseCamera} for camType in (BaseCamera, PanZoomCamera, PerspectiveCamera, TurntableCamera, FlyCamera, ArcballCamera): cam_types[camType.__name__[:-6].lower()] = camType try: return cam_types[cam_type](*a...
Factory function for creating new cameras using a string name. Parameters ---------- cam_type : str May be one of: * 'panzoom' : Creates :class:`PanZoomCamera` * 'turntable' : Creates :class:`TurntableCamera` * None : Creates :class:`Camera` Notes -----...
343,121
def _convert_date_time_string(dt_string): dt_string = dt_string.split()[0] dt_obj = datetime.strptime(dt_string, ) return dt_obj.strftime()
convert string to date time object
343,122
def repoItemChanged(self, rti): check_class(rti, (BaseRti, int), allow_none=True) assert type(rti) != int, "rti: {}".format(rti) try: self._drawContents(rti) self.setCurrentIndex(self.CONTENTS_PAGE_IDX) except Exception as ex: if DEBUGGING: ...
Updates the content when the current repo tree item changes. The rti parameter can be None when no RTI is selected in the repository tree.
343,123
def com_google_fonts_check_xavgcharwidth(ttFont): current_value = ttFont[].xAvgCharWidth ACCEPTABLE_ERROR = 10 if ttFont[].version >= 3: calculation_rule = "the average of the widths of all glyphs in the font" if not ttFont[].metrics: yield FAIL, Message("missing-glyphs", ...
Check if OS/2 xAvgCharWidth is correct.
343,124
def _Open(self, path_spec=None, mode=): if not path_spec: raise ValueError() if not path_spec.HasParent(): raise errors.PathSpecError( ) self._file_system = resolver.Resolver.OpenFileSystem( path_spec, resolver_context=self._resolver_context) tsk_volume = self._file_...
Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like object could not be opened. OSError: if the ...
343,125
def popup_js(self, callback_name=None, indent=None, custom=None, stay_open=False): custom_callback = .format(cb=callback_name) if callback_name else return .format(result=self.to_json(indent), custom=json.dumps(custom), custom_c...
Returns JavaScript that: #. Triggers the ``options.onLoginComplete(result, closer)`` handler set with the :ref:`authomatic.setup() <js_setup>` function of :ref:`javascript.js <js>`. #. Calls the JavasScript callback specified by :data:`callback_name` on the opener ...
343,126
def reset(self): status = (True, None) error_message = try: c_list = set(self.d_client.containers.list( filters={: }, all=True)) for c in c_list: c.remove(force=True) except Exception as e: error_me...
Factory reset all of Vent's user data, containers, and images
343,127
def update_entry_line(self, key=None): if key is None: key = self.actions.cursor cell_code = self.GetTable().GetValue(*key) post_command_event(self, self.EntryLineMsg, text=cell_code)
Updates the entry line Parameters ---------- key: 3-tuple of Integer, defaults to current cell \tCell to which code the entry line is updated
343,128
def redirect(self, id, name, **options): self._steps.append(Redirect(id, name, **options).obj)
Forwards an incoming call to another destination / phone number before answering it. Argument: id is a String Argument: name is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/redirect
343,129
def fastq_iter(handle, header=None): append = list.append join = str.join strip = str.strip next_line = next if header is None: header = next(handle) if (isinstance(header, bytes)): def next_line(i): return next(i).decode() header = strip...
Iterate over FASTQ file and return FASTQ entries Args: handle (file): FASTQ file handle, can be any iterator so long as it it returns subsequent "lines" of a FASTQ entry header (str): Header line of next FASTQ entry, if 'handle' has been partially read and you want to start...
343,130
def fetch_from_pgdb(self, tables, cxn, limit=None, force=False): con = None try: con = psycopg2.connect( host=cxn[], database=cxn[], port=cxn[], user=cxn[], password=cxn[]) cur = con.cursor() for tab in tables: ...
Will fetch all Postgres tables from the specified database in the cxn connection parameters. This will save them to a local file named the same as the table, in tab-delimited format, including a header. :param tables: Names of tables to fetch :param cxn: database connecti...
343,131
def extend_primary_key(self, new_attributes): try: raise DataJointError( % next(a for a in new_attributes if a not in self.names)) except StopIteration: return Heading(dict(v.todict(), in_key=v.in_key or v.name in new_attributes) for v in sel...
Create a new heading in which the primary key also includes new_attributes. :param new_attributes: new attributes to be added to the primary key.
343,132
def tag_start(self, tag, attrs=None): r return % (tag, self.build_attr(attrs)) if attrs else % tag
r"""Build started tag info. :param tag: tag name :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str
343,133
def create_patches(destination, root, settings=None, traverse_bases=True, filter=default_filter, recursive=True, use_decorators=True): if filter is None: filter = _true out = [] root_patch = Patch(destination, , root, settings=settings) stack = collections.deque((root_pa...
Create a patch for each member of a module or a class. Parameters ---------- destination : object Patch destination. root : object Root object, either a module or a class. settings : gorilla.Settings Settings. traverse_bases : bool If the object is a class, the b...
343,134
def get_args(cls, dist, header=None): if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in , : group = type_ + for name, ep in dist.get_entry_map(group).items(): cls._ensure_safe_name(name) ...
Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points.
343,135
def _vector(x, type=): if isinstance(x, (list, tuple)): x = np.array(x, dtype=np.float32) elif not isinstance(x, np.ndarray): x = np.array([x], dtype=np.float32) assert x.ndim == 1 if type == : x = x[:, None] return x
Convert an object to a row or column vector.
343,136
def _set_field_on_message(msg, key, value): if isinstance(value, (collections_abc.MutableSequence, tuple)): while getattr(msg, key): getattr(msg, key).pop() for item in value: if isinstance(item, collections_abc.Mapping): ...
Set helper for protobuf Messages.
343,137
def connect(self): if self.is_connected() or self.is_connecting(): raise tornado.gen.Return(True) if self.unix_domain_socket is None: self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.tcp_nodelay: self.__socket.setsocko...
Connects the object to the host:port. Returns: Future: a Future object with True as result if the connection process was ok.
343,138
def from_page_xml(cls, page_xml): header = footer = "</mediawiki>" return cls.from_file(mwtypes.files.concat(header, page_xml, footer))
Constructs a :class:`~mwxml.iteration.dump.Dump` from a <page> block. :Parameters: page_xml : `str` | `file` Either a plain string or a file containing <page> block XML to process
343,139
def enforce_bounds(self): too_big = self.parameter_data.loc[:,"parval1"] > \ self.parameter_data.loc[:,"parubnd"] self.parameter_data.loc[too_big,"parval1"] = \ self.parameter_data.loc[too_big,"parubnd"] too_small = self.parameter_data.loc[:,"parval1"] < \ ...
enforce bounds violation resulting from the parameter pertubation calculations
343,140
def dispatch(self, request, *args, **kwargs): self._add_next_and_user(request) return super(UpdateImageView, self).dispatch(request, *args, **kwargs)
Adds useful objects to the class.
343,141
def _esfilter2sqlwhere(db, esfilter): esfilter = wrap(esfilter) if esfilter is True: return SQL_TRUE elif esfilter["and"]: return sql_iso(SQL_AND.join([esfilter2sqlwhere(db, a) for a in esfilter["and"]])) elif esfilter["or"]: return sql_iso(SQL_OR.join([esfilter2sqlwhere(db...
CONVERT ElassticSearch FILTER TO SQL FILTER db - REQUIRED TO PROPERLY QUOTE VALUES AND COLUMN NAMES
343,142
def _backup_file(path): backup_base = backup_path = .join([backup_base,path]) if not exists(backup_path): directory = .join([backup_base,os.path.split(path)[0]]) sudo(% directory) sudo(% (path,backup_path))
Backup a file but never overwrite an existing backup file
343,143
def call_fn(fn, args): if expand_as_args(args): return fn(*args) elif _expand_as_kwargs(args): return fn(**args) else: return fn(args)
Calls `fn` with `args`, possibly expanding `args`. Use this function when calling a user-provided callable using user-provided arguments. The expansion rules are as follows: `fn(*args)` if `args` is a `list` or a `tuple`, but not a `namedtuple`. `fn(**args)` if `args` is a `dict`. `fn(args)` otherwise. ...
343,144
def delete(filething): try: t = APEv2(filething) except APENoHeaderError: return filething.fileobj.seek(0) t.delete(filething)
delete(filething) Arguments: filething (filething) Raises: mutagen.MutagenError Remove tags from a file.
343,145
def _handle_update_msg(self, update_msg): assert self.state.bgp_state == const.BGP_FSM_ESTABLISHED self.state.incr(PeerCounterNames.RECV_UPDATES) if not self._validate_update_msg(update_msg): LOG.error() return ...
Extracts and processes new paths or withdrawals in given `update_msg`. Parameter: - `update_msg`: update message to process. - `valid_rts`: current valid/interesting rts to the application according to configuration of all VRFs. Assumes Multiprotocol Extensi...
343,146
def add_triangle(self, neighbors, color, center=None, opacity=0.4, draw_edges=False, edges_color=[0.0, 0.0, 0.0], edges_linewidth=2): points = vtk.vtkPoints() triangle = vtk.vtkTriangle() for ii in range(3): points.InsertNextPoint(ne...
Adds a triangular surface between three atoms. Args: atoms: Atoms between which a triangle will be drawn. color: Color for triangle as RGB. center: The "central atom" of the triangle opacity: opacity of the triangle draw_edges: If set to True, the a l...
343,147
def local_error(self, originalValue, calculatedValue): originalValue = originalValue[0] calculatedValue = calculatedValue[0] if not originalValue and not calculatedValue: return 0.0 return abs(calculatedValue - originalValue)/ ((abs(originalValue) + abs(ca...
Calculates the error between the two given values. :param list originalValue: List containing the values of the original data. :param list calculatedValue: List containing the values of the calculated TimeSeries that corresponds to originalValue. :return: Returns the error...
343,148
def add_slave(self, slave, container_name="widget"): cont = getattr(self, container_name, None) if cont is None: raise AttributeError( ) cont.add(slave.widget) self.slaves.append(slave) return slave
Add a slave delegate
343,149
def get_lower_supported(cls, previous_version): try: version = next(v for v in sorted(ProtocolVersion.SUPPORTED_VERSIONS, reverse=True) if v not in ProtocolVersion.BETA_VERSIONS and v < previous_version) except StopIteration: version = 0 ...
Return the lower supported protocol version. Beta versions are omitted.
343,150
def remote_asset(class_obj: type) -> type: assert isinstance(class_obj, type), "class_obj is not a Class" global _remote_asset_resource_type _remote_asset_resource_type = class_obj return class_obj
Decorator to annotate the RemoteAsset class. Registers the decorated class as the RemoteAsset known type.
343,151
def send(self, sender: PytgbotApiBot): return sender.send_media_group( media=self.media, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
343,152
def synthesizeProperty(propertyName, default = None, contract = None, readOnly = False, privateMemberName = None): return SyntheticDecoratorFactory().syntheticMemberDecorator(memberName = propertyName, ...
When applied to a class, this decorator adds a property to it and overrides the constructor in order to set\ the default value of the property. :IMPORTANT: In order for this to work on python 2, you must use new objects that is to say that the class must inherit from object. By default, the private attrib...
343,153
def image_box(center, shape, box): return tuple(slice_create(c, b, stop=s) for c, s, b in zip(center, shape, box))
Create a region of size box, around a center in a image of shape.
343,154
def IterEnumerateInstancePaths(self, ClassName, namespace=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=DEFAULT_ITER_MAXOBJECTCOUNT, ...
Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace, using the Python :term:`py:generator` idiom to return the result. *New in pywbem 0.10 as experimental and finalized in 0.12.* This method uses the corresponding pull operations ...
343,155
def get_screen(): img_title = + g.client_id + image_path = STATIC_FILES_PATH + img_title if g.driver_status != WhatsAPIDriverStatus.LoggedIn: try: g.driver.get_qr(image_path) return send_file(image_path, mimetype=) except Exception as err: pass ...
Capture chrome screen image and send it back. If the screen is currently at qr scanning phase, return the image of qr only, else return image of full screen
343,156
def get_open_trackers_from_remote(): url_base = url = % (url_base, OPEN_TRACKERS_FILENAME) try: import requests response = requests.get(url, timeout=REMOTE_TIMEOUT) response.raise_for_status() open_trackers = response.text.splitlines() except (ImportError, req...
Returns open trackers announce URLs list from remote repo.
343,157
def get_port_def(port_num, proto=): udpport_num/udp2222-2223/udp try: port_num, _, port_num_proto = port_num.partition() except AttributeError: pass else: if port_num_proto: proto = port_num_proto try: if proto.lower() == : return int(port_num)...
Given a port number and protocol, returns the port definition expected by docker-py. For TCP ports this is simply an integer, for UDP ports this is (port_num, 'udp'). port_num can also be a string in the format 'port_num/udp'. If so, the "proto" argument will be ignored. The reason we need to be able t...
343,158
def unstack(self, dimensions=None, **dimensions_kwargs): dimensions = either_dict_or_kwargs(dimensions, dimensions_kwargs, ) result = self for old_dim, dims in dimensions.items(): result = result._unstack_once(dims, old_dim) ...
Unstack an existing dimension into multiple new dimensions. New dimensions will be added at the end, and the order of the data along each new dimension will be in contiguous (C) order. Parameters ---------- dimensions : mapping of the form old_dim={dim1: size1, ...} ...
343,159
def convert_to_py_error(error_message): message = error_message.lower() for err_msg, err_type in ERR_MSGS: if err_msg in message: return err_type(error_message) else: return IndicoError(error_message)
Raise specific exceptions for ease of error handling
343,160
def configure(self, width, height): self._imgwin_set = True self.set_window_size(width, height)
See :meth:`set_window_size`.
343,161
def remove_alert(thing_name, key, session=None): return _request(, .format(thing_name), params={: key}, session=session)
Remove an alert for the given thing
343,162
def _M2(Xvar, Yvar, mask_X=None, mask_Y=None, xsum=0, xconst=0, ysum=0, yconst=0, weights=None, diag_only=False): if mask_X is None and mask_Y is None: return _M2_dense(Xvar, Yvar, weights=weights, diag_only=diag_only) else: if mask_X is None: mask_X = np.ones(Xvar.shap...
direct (nonsymmetric) second moment matrix. Decide if we need dense, sparse, const
343,163
def lldp(device=None, interface=None, title=None, pattern=None, chassis=None, display=_DEFAULT_DISPLAY): all_lldp = _get_mine() labels = { : , : , : , : , : , : , : , : } rows = [] if...
Search in the LLDP neighbors, using the following mine functions: - net.lldp Optional arguments: device Return interface data from a certain device only. interface Return data selecting by interface name. pattern Return LLDP neighbors that have contain this pattern in on...
343,164
def onExpandKeyEvent(self, keyEvent): if self._start is None: currentBlockText = self._qpart.textCursor().block().text() line = self._qpart.cursorPosition[0] visibleColumn = self._realToVisibleColumn(currentBlockText, self._qpart.cursorPosition[1]) self._...
One of expand selection key events
343,165
def pair_has_contradiction(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> bool: relations = {data[RELATION] for data in graph[u][v].values()} return relation_set_has_contradictions(relations)
Check if a pair of nodes has any contradictions in their causal relationships. Assumes both nodes are in the graph.
343,166
def get_avatar(self, mxit_id, output_file_path=None, scope=): data = _get( token=self.oauth.get_app_token(scope), uri= + urllib.quote(mxit_id) ) if output_file_path: with open(output_file_path, ) as f: f.write(data) else: ...
Retrieve the Mxit user's avatar No user authentication required
343,167
def time_boxed(func, iterable, time_budget, *args): time_budget = time_budget / 1000 start = time.time() for thing in iterable: yield func(thing, *args) end = time.time() - start if end > time_budget: return
Apply a function to the items of an iterable within a given time budget. Loop the given iterable, calling the given function on each item. The expended time is compared to the given time budget after each iteration.
343,168
def run(self): self.old_dir = [] if self.opt.clean: self.old_dir = os.listdir() cite_counter, toc_file, gloss_files = self._read_latex_files() self.latex_run() self.read_glossaries() gloss_changed = self.makeindex_runs(gloss_files) ...
Run the LaTeX compilation.
343,169
def DOM_setFileInputFiles(self, files, **kwargs): assert isinstance(files, (list, tuple) ), "Argument must be of type listtuple. Received type: " % type( files) expected = [, , ] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ...
Function path: DOM.setFileInputFiles Domain: DOM Method name: setFileInputFiles WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'files' (type: array) -> Array of file paths to set. Optional arguments: 'nodeId' (type: NodeId) -> Identifier of the node....
343,170
def manage_work_queue(queue_name): modify_form = forms.ModifyWorkQueueTaskForm() if modify_form.validate_on_submit(): primary_key = (modify_form.task_id.data, queue_name) task = work_queue.WorkQueue.query.get(primary_key) if task: logging.info(, ...
Page for viewing the contents of a work queue.
343,171
def extract_scheduler_location(self, topology): schedulerLocation = { "name": None, "http_endpoint": None, "job_page_link": None, } if topology.scheduler_location: schedulerLocation["name"] = topology.scheduler_location.topology_name schedulerLocation["http_endpoint...
Returns the representation of scheduler location that will be returned from Tracker.
343,172
def genargs() -> ArgumentParser: parser = ArgumentParser() parser.add_argument("infile", help="Input JSG specification") parser.add_argument("-o", "--outfile", help="Output python file (Default: {infile}.py)") parser.add_argument("-e", "--evaluate", help="Evaluate resulting python file as a test", ...
Create a command line parser :return: parser
343,173
def _find_usage_gateways(self): gws = self.conn.describe_internet_gateways() self.limits[]._add_current_usage( len(gws[]), aws_type=, )
find usage for Internet Gateways
343,174
def get_table_keys_name(self, table_name, keys): table = self.tables.get(table_name) if not table: return None, None else: if len(keys) == 1: for key in keys: if key in table.hash_key_names: return key, ...
Given a set of keys, extracts the key and range key
343,175
def end_binary_container(self): binary_container = self._message_stack.pop() binary_container.verify() self._add_field(binary_container)
End binary container. See `New Binary Container`.
343,176
def nga_west2_epistemic_adjustment(magnitude, distance): if magnitude < 6.0: adjustment = 0.22 * np.ones_like(distance) adjustment[distance < 10.0] = 0.37 elif magnitude >= 7.0: adjustment = 0.36 * np.ones_like(distance) adjustment[distance < 10.0] = 0.40 adjustment[...
Applies the "average" adjustment factor for epistemic uncertainty as defined in Table 17 of Petersen et al., (2014):: | R < 10. | 10.0 <= R < 30.0 | R >= 30.0 ----------------------------------------------------------- M < 6.0 | 0.37 | 0.22 | 0.22 6...
343,177
def layer_iter(layers, layer_names): if use_caffe: for layer_idx, layer in enumerate(layers): layer_name = re.sub(, , layer_names[layer_idx]) layer_type = layer.type layer_blobs = layer.blobs yield (layer_name, layer_type, layer_blobs) else: f...
Iterate over all layers
343,178
def p_elseif_elseiflist(p): label_, cond_ = p[1] then_ = p[2] else_ = p[3] p[0] = make_block(label_, make_sentence(, cond_, then_, else_, lineno=p.lineno(1)))
elseiflist : elseif_expr program_co elseiflist
343,179
def build_hugo_md(filename, tag, bump): header = [ , .format(date.today().isoformat()), .format(tag), , .format(bump), , ] with open(filename, "r") as file_h: content = insert_break(file_h.readlines()) header.extend(content) with ...
Build the markdown release notes for Hugo. Inserts the required TOML header with specific values and adds a break for long release notes. Parameters ---------- filename : str, path The release notes file. tag : str The tag, following semantic versioning, of the current release....
343,180
def confidence_intervals(self, X, width=.95, quantiles=None): if not self._is_fitted: raise AttributeError() X = check_X(X, n_feats=self.statistics_[], edge_knots=self.edge_knots_, dtypes=self.dtype, features=self.feature, verbose=self.verbos...
estimate confidence intervals for the model. Parameters ---------- X : array-like of shape (n_samples, m_features) Input data matrix width : float on [0,1], optional quantiles : array-like of floats in (0, 1), optional Instead of specifying the prediciton...
343,181
def do_clearaccess(self, line): self._split_args(line, 0, 0) self._command_processor.get_session().get_access_control().clear() self._print_info_if_verbose("Removed all subjects from access policy")
clearaccess Remove all subjects from access policy Only the submitter will have access to the object.
343,182
def as_int(self, method): (new_radix, relation) = self.rounded(0, method) value = Nats.convert_to_int(new_radix.integer_part, new_radix.base) return (value * self.sign, relation)
This value as an int, rounded according to ``method``. :param method: rounding method :raises BasesValueError: on bad parameters :returns: corresponding int value :rtype: int
343,183
async def subscribe(self, topic: str): req_msg = { : , : topic, : True } await self._conn.send_message(req_msg)
Subscribe to a channel :param topic: required :returns: None Sample ws response .. code-block:: python { "type":"message", "topic":"/market/ticker:BTC-USDT", "subject":"trade.ticker", "data":{ ...
343,184
def generate_thumbnail_in_stream( self, width, height, image, smart_cropping=False, custom_headers=None, raw=False, callback=None, **operation_config): url = self.generate_thumbnail_in_stream.metadata[] path_format_arguments = { : self._serialize.url("self.confi...
This operation generates a thumbnail image with the user-specified width and height. By default, the service analyzes the image, identifies the region of interest (ROI), and generates smart cropping coordinates based on the ROI. Smart cropping helps when you specify an aspect ratio that ...
343,185
def check_down_connections(self): now = time.time() for db_num, marked_down_at in self._down_connections.items(): if marked_down_at + self.retry_timeout <= now: self.mark_connection_up(db_num)
Iterates through all connections which were previously listed as unavailable and marks any that have expired their retry_timeout as being up.
343,186
def comment(name, regex, char=, backup=): name = os.path.expanduser(name) ret = {: name, : {}, : False, : } if not name: return _error(ret, ) check_res, check_msg = _check_file(name) if not check_res: return _error(ret, check_msg) una...
Comment out specified lines in a file. name The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the p...
343,187
def add_example(self, word_id, original, translation, url=): data = { : word_id, : original, : translation } return self._request(url, method=, data=data).json()
创建例句
343,188
def N(self, ID, asp=0): obj = self.chart.get(ID).copy() obj.relocate(obj.lon + asp) ID = % (ID, asp) return self.G(ID, obj.lat, obj.lon)
Returns the conjunction or opposition aspect of an object.
343,189
def hmtk_histogram_2D(xvalues, yvalues, bins, x_offset=1.0E-10, y_offset=1.0E-10): xbins, ybins = (bins[0] - x_offset, bins[1] - y_offset) n_x = len(xbins) - 1 n_y = len(ybins) - 1 counter = np.zeros([n_y, n_x], dtype=float) for j in range(n_y): y_idx = np.logical_...
See the explanation for the 1D case - now applied to 2D. :param numpy.ndarray xvalues: Values of x-data :param numpy.ndarray yvalues: Values of y-data :param tuple bins: Tuple containing bin intervals for x-data and y-data (as numpy arrays) :param float x_offset: Small a...
343,190
def pack(name, root, path=None, pack_format=, compress=): tar if pack_format == : _tar(name, root, path, compress)
Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar'
343,191
def uvindex_history_around_coords(self, lat, lon, start, end=None): geo.assert_is_lon(lon) geo.assert_is_lat(lat) assert start is not None start = timeformatutils.timeformat(start, ) if end is None: end = timeutils.now(timeformat=) else: e...
Queries the OWM Weather API for UV index historical values in the surroundings of the provided geocoordinates and in the specified time frame. If the end of the time frame is not provided, that is intended to be the current datetime. :param lat: the location's latitude, must be between ...
343,192
async def receive_messages_async(self, on_message_received): await self.open_async() self._message_received_callback = on_message_received receiving = True try: while receiving: receiving = await self.do_work_async() except: receiv...
Receive messages asynchronously. This function will run indefinitely, until the client closes either via timeout, error or forced interruption (e.g. keyboard interrupt). If the receive client is configured with `auto_complete=True` then the messages that have not been settled on complet...
343,193
def lastElementChild(self): ret = libxml2mod.xmlLastElementChild(self._o) if ret is None:return None __tmp = xmlNode(_obj=ret) return __tmp
Finds the last child node of that element which is a Element node Note the handling of entities references is different than in the W3C DOM element traversal spec since we don't have back reference from entities content to entities references.
343,194
def getEvents(self, repo_user, repo_name, until_id=None): done = False page = 0 events = [] while not done: new_events = yield self.api.makeRequest( [, repo_user, repo_name, ], page) if new_events: ...
Get all repository events, following paging, until the end or until UNTIL_ID is seen. Returns a Deferred.
343,195
def data(self, data): self._data = {det: d.copy() for (det, d) in data.items()}
Store a copy of the data.
343,196
def run(*args): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) if "--check" in args: check_migrations() else: django.core.management.call_command("makemigrations", APP_NAME, *args)
Check and/or create Django migrations. If --check is present in the arguments then migrations are checked only.
343,197
def start_webhook(dispatcher, webhook_path, *, loop=None, skip_updates=None, on_startup=None, on_shutdown=None, check_ip=False, retry_after=None, route_name=DEFAULT_ROUTE_NAME, **kwargs): executor = set_webhook(dispatcher=dispatcher, webhook_path=w...
Start bot in webhook mode :param dispatcher: :param webhook_path: :param loop: :param skip_updates: :param on_startup: :param on_shutdown: :param check_ip: :param route_name: :param kwargs: :return:
343,198
def create_view(self, request): try: if request.user.is_authenticated(): return redirect("organization_add") except TypeError: if request.user.is_authenticated: return redirect("organization_add") form = org_registration_form(self....
Initiates the organization and user account creation process
343,199
def determine_position(position, img, mark): left = top = 0 max_left = max(img.size[0] - mark.size[0], 0) max_top = max(img.size[1] - mark.size[1], 0) margin = 10 if not position: position = if isinstance(position, tuple): left, top = position elif isinstance(p...
Options: TL: top-left TR: top-right BR: bottom-right BL: bottom-left C: centered R: random X%xY%: relative positioning on both the X and Y axes X%xY: relative positioning on the X axis and absolute positioning on the Y axis XxY%: abso...