Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
380,100
def get_labels(self, depth=None): if not isinstance(self.ref_cell, Cell): return [] if self.rotation is not None: ct = numpy.cos(self.rotation * numpy.pi / 180.0) st = numpy.sin(self.rotation * numpy.pi / 180.0) st = numpy.array([-st, st]) ...
Returns a list of labels created by this reference. Parameters ---------- depth : integer or ``None`` If not ``None``, defines from how many reference levels to retrieve labels from. Returns ------- out : list of ``Label`` List contai...
380,101
def show_compatibility_message(self, message): messageBox = QMessageBox(self) messageBox.setWindowModality(Qt.NonModal) messageBox.setAttribute(Qt.WA_DeleteOnClose) messageBox.setWindowTitle() messageBox.setText(message) messageBox.setStandardButtons(QMessageBox....
Show compatibility message.
380,102
def pop_configuration(self): if len(self.__configurations) == 1: raise IndexError( ) self.__configurations.pop() self.__mapped_attr_cache.clear()
Pushes the currently active configuration from the stack of configurations managed by this mapping. :raises IndexError: If there is only one configuration in the stack.
380,103
def get_plaintext_document_body(fpath, keep_layout=False): textbody = [] mime_type = magic.from_file(fpath, mime=True) if mime_type == "text/plain": with open(fpath, "r") as f: textbody = [line.decode("utf-8") for line in f.readlines()] elif mime_type == "application/pdf": ...
Given a file-path to a full-text, return a list of unicode strings whereby each string is a line of the fulltext. In the case of a plain-text document, this simply means reading the contents in from the file. In the case of a PDF however, this means converting the document to plaintext. ...
380,104
def unsubscribe_from_candles(self, pair, timeframe=None, **kwargs): valid_tfs = [, , , , , , , , , , , ] if timeframe: if timeframe not in valid_tfs: raise ValueError("timeframe must be any of %s" % valid_tfs) else: timeframe...
Unsubscribe to the passed pair's OHLC data channel. :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :return:
380,105
def _invert(self): result = defaultdict(dict) for test_context, src_context in six.iteritems(self.data): for src, lines in six.iteritems(src_context): result[src][test_context] = lines return result
Invert coverage data from {test_context: {file: line}} to {file: {test_context: line}}
380,106
def decompress(databasepath, database_name, compression, compressed_file): if os.path.isfile(compressed_file): if compression == : logging.info(.format(dbname=database_name)) with tarfile.open(compressed_file, ) as tar: ...
Decompress the provided file using the appropriate library :param databasepath: Name and path of where the database files are to be downloaded :param database_name: Name of the database e.g. sipprverse :param compression: STR MOB-suite databases are .zip files, while OLC databases are .tar.gz ...
380,107
def annual_heating_design_day_990(self): if bool(self._winter_des_day_dict) is True: return DesignDay.from_ashrae_dict_heating( self._winter_des_day_dict, self.location, True, self._stand_press_at_elev) else: return None
A design day object representing the annual 99.0% heating design day.
380,108
def delete_namespaced_limit_range(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_namespaced_limit_range_with_http_info(name, namespace, **kwargs) else: (data) = self.delete_namespaced_limit_range_with_http_info(name, namespa...
delete a LimitRange This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_limit_range(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :...
380,109
def get_mockup_motor(self, motor): return next((m for m in self.robot.motors if m.name == motor.name), None)
Gets the equivalent :class:`~pypot.primitive.primitive.MockupMotor`.
380,110
def run_container(image, name=None, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, client_timeout=salt.utils.docker.CLIENT_TIMEOUT, bg=False, replace=False, ...
.. versionadded:: 2018.3.0 Equivalent to ``docker run`` on the Docker CLI. Runs the container, waits for it to exit, and returns the container's logs when complete. .. note:: Not to be confused with :py:func:`docker.run <salt.modules.dockermod.run>`, which provides a :py:func:`cmd.run ...
380,111
def _dict_subset(keys, master_dict): return dict([(k, v) for k, v in six.iteritems(master_dict) if k in keys])
Return a dictionary of only the subset of keys/values specified in keys
380,112
def commit_transaction(self): self._check_ended() retry = False state = self._transaction.state if state is _TxnState.NONE: raise InvalidOperation("No transaction started") elif state in (_TxnState.STARTING, _TxnState.COMMITTED_EMPTY): ...
Commit a multi-statement transaction. .. versionadded:: 3.7
380,113
def next(self): x, y = next(self.scan) xr = -x if self.rx else x yr = -y if self.ry else y return xr, yr
Next point in iteration
380,114
def hostinterface_update(interfaceid, **kwargs): s docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see modules docstring) :return: ID of the updated host interface, False on failure. CLI Example: .. code-block:: bash salt zabbix.hos...
.. versionadded:: 2016.3.0 Update host interface .. note:: This function accepts all standard hostinterface: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.4/manual/api/reference/hostinterface/object#host_inter...
380,115
def masks(list_of_index_lists, n): for il,l in enumerate(list_of_index_lists): mask = np.zeros(n,dtype=bool) mask[l] = True list_of_index_lists[il] = mask masks = np.array(list_of_index_lists) return masks
Make an array in which rows store 1d mask arrays from list of index lists. Parameters ---------- n : int Maximal index / number of samples.
380,116
def list_open_buffers(self): active_eb = self.active_editor_buffer visible_ebs = self.active_tab.visible_editor_buffers() def make_info(i, eb): return OpenBufferInfo( index=i, editor_buffer=eb, is_active=(eb == active_eb), ...
Return a `OpenBufferInfo` list that gives information about the open buffers.
380,117
async def create_new_pump_async(self, partition_id, lease): loop = asyncio.get_event_loop() partition_pump = EventHubPartitionPump(self.host, lease) loop.create_task(partition_pump.open_async()) self.partition_pumps[partition_id] = partition_pump _logger.info("C...
Create a new pump thread with a given lease. :param partition_id: The partition ID. :type partition_id: str :param lease: The lease to be used. :type lease: ~azure.eventprocessorhost.lease.Lease
380,118
def main(): parser = argparse.ArgumentParser(description=) parser.add_argument(, type=str, metavar=, help=, nargs=) parser.add_argument(, type=str, help=) args = parser.parse_args() output_path = os.path.abspath(args.output_filename) if args.output_filename else None ...
Generate a TPIP report.
380,119
def _get_user_class(self, name): self._user_classes.setdefault(name, _make_user_class(self, name)) return self._user_classes[name]
Get or create a user class of the given type.
380,120
def get_coordination_symmetry_measures_optim(self, only_minimum=True, all_csms=True, nb_set=None, optimization=None): cn = len(self.local_geometry.coords) test_geometries = self.allcg.get_implemented_geometries(cn) if all([cg.algorithms[0...
Returns the continuous symmetry measures of the current local geometry in a dictionary. :return: the continuous symmetry measures of the current local geometry in a dictionary.
380,121
def check_exports(mod, specs, renamings): functions = {renamings.get(k, k): v for k, v in specs.functions.items()} mod_functions = {node.name: node for node in mod.body if isinstance(node, ast.FunctionDef)} for fname, signatures in functions.items(): try: fnod...
Does nothing but raising PythranSyntaxError if specs references an undefined global
380,122
def seek(self, rev): if not self: return if type(rev) is not int: raise TypeError("rev must be int") past = self._past future = self._future if future: appender = past.append popper = future.pop ...
Arrange the caches to help look up the given revision.
380,123
def deleteFeatures(self, objectIds="", where="", geometryFilter=None, gdbVersion=None, rollbackOnFailure=True ): dURL = self._url + "/deleteFeatures" params ...
removes 1:n features based on a sql statement Input: objectIds - The object IDs of this layer/table to be deleted where - A where clause for the query filter. Any legal SQL where clause operating on the fields in the layer is allowed. F...
380,124
def add_user( self, user, first_name=None, last_name=None, email=None, password=None ): self.project_service.set_auth(self._token_project) self.project_service.add_user( user, first_name, last_name, email, password)
Add a new user. Args: user (string): User name. first_name (optional[string]): User's first name. Defaults to None. last_name (optional[string]): User's last name. Defaults to None. email: (optional[string]): User's email address. Defaults to None. ...
380,125
def get_coordinate_systems( self, token: dict = None, srs_code: str = None, prot: str = "https" ) -> dict: if isinstance(srs_code, str): specific_srs = "/{}".format(srs_code) else: specific_srs = "" req_url = "{}://v1.{}.isogeo.com/...
Get available coordinate systems in Isogeo API. :param str token: API auth token :param str srs_code: code of a specific coordinate system :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs).
380,126
def _autoinsert_quotes(self, key): char = {Qt.Key_QuoteDbl: , Qt.Key_Apostrophe: soleolsolcursorsolcursorsolcursorcursoreol,:;)]}')): self.editor.insert_text(char) elif (unmatched_quotes_in_line(line_text) and (not last_three == 3*char)): self.editor.inse...
Control how to automatically insert quotes in various situations.
380,127
def run_model(self, op_list, num_steps, feed_vars=(), feed_data=None, print_every=100, allow_initialize=True): feed_data = feed_data or itertools.repeat(()) ops = [bookkeeper.global_step()] ops.extend(op_li...
Runs `op_list` for `num_steps`. Args: op_list: A list of ops to run. num_steps: Number of steps to run this for. If feeds are used, this is a maximum. `None` can be used to signal "forever". feed_vars: The variables to feed. feed_data: An iterator that feeds data tuples. prin...
380,128
def set_cmap(self, cmap, callback=True): self.cmap = cmap with self.suppress_changed: self.calc_cmap() self.t_.set(color_map=cmap.name, callback=False)
Set the color map used by this RGBMapper. `cmap` specifies a ColorMap object. If `callback` is True, then any callbacks associated with this change will be invoked.
380,129
def countthai(text: str, ignore_chars: str = _DEFAULT_IGNORE_CHARS) -> float: if not text or not isinstance(text, str): return 0 if not ignore_chars: ignore_chars = "" num_thai = 0 num_ignore = 0 for ch in text: if ch in ignore_chars: num_ignore += 1 ...
:param str text: input text :return: float, proportion of characters in the text that is Thai character
380,130
def string2identifier(s): if len(s) == 0: return "_" if s[0] not in string.ascii_letters: s = "_" + s valids = string.ascii_letters + string.digits + "_" out = "" for i, char in enumerate(s): if char in valids: out += char else: ...
Turn a string into a valid python identifier. Currently only allows ASCII letters and underscore. Illegal characters are replaced with underscore. This is slightly more opinionated than python 3 itself, and may be refactored in future (see PEP 3131). Parameters ---------- s : string st...
380,131
def quantile(data, num_breaks): def scipy_mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()): def _quantiles1D(data,m,p): x = numpy.sort(data.compressed()) n = len(x) if n == 0: return numpy.ma.array(numpy.empt...
Calculate quantile breaks. Arguments: data -- Array of values to classify. num_breaks -- Number of breaks to perform.
380,132
def visit_AugAssign(self, node): args = (self.naming[get_variable(node.target).id], self.visit(node.value)) merge_dep = list({frozenset.union(*x) for x in itertools.product(*args)}) self.naming[get_variable(node.target).id] = merge_dep
AugAssigned value depend on r-value type dependencies. It is valid for subscript, `a[i] += foo()` means `a` type depend on `foo` return type and previous a types too.
380,133
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_vlan_disc_req(self, **kwargs): config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "output") fcoe_intf_list = ...
Auto Generated Code
380,134
def readFLOAT16(self): self.reset_bits_pending() word = self.readUI16() sign = -1 if ((word & 0x8000) != 0) else 1 exponent = (word >> 10) & 0x1f significand = word & 0x3ff if exponent == 0: if significand == 0: return 0.0 ...
Read a 2 byte float
380,135
def _configure_io_handler(self, handler): if self.check_events(): return if handler in self._unprepared_handlers: old_fileno = self._unprepared_handlers[handler] prepared = self._prepare_io_handler(handler) else: old_fileno = None ...
Register an io-handler at the polling object.
380,136
def search(self, pattern, minAddr = None, maxAddr = None): if isinstance(pattern, str): return self.search_bytes(pattern, minAddr, maxAddr) if isinstance(pattern, compat.unicode): return self.search_bytes(pattern.encode("utf-16le"), m...
Search for the given pattern within the process memory. @type pattern: str, compat.unicode or L{Pattern} @param pattern: Pattern to search for. It may be a byte string, a Unicode string, or an instance of L{Pattern}. The following L{Pattern} subclasses are provided...
380,137
def url2domain(url): parsed_uri = urlparse.urlparse(url) domain = .format(uri=parsed_uri) domain = re.sub("^.+@", "", domain) domain = re.sub(":.+$", "", domain) return domain
extract domain from url
380,138
def _detect_xerial_stream(payload): if len(payload) > 16: header = struct.unpack( + _XERIAL_V1_FORMAT, bytes(payload)[:16]) return header == _XERIAL_V1_HEADER return False
Detects if the data given might have been encoded with the blocking mode of the xerial snappy library. This mode writes a magic header of the format: +--------+--------------+------------+---------+--------+ | Marker | Magic String | Null / Pad | Version | Compat | +...
380,139
def queries(self, request): queries = self.get_queries(request) worlds = [] with self.mapper.begin() as session: for _ in range(queries): world = session.query(World).get(randint(1, MAXINT)) worlds.append(self.get_json(world)) return J...
Multiple Database Queries
380,140
def read(self, auth, resource, options, defer=False): return self._call(, auth, [resource, options], defer)
Read value(s) from a dataport. Calls a function that builds a request to read the dataport specified by an alias or rid and returns timeseries data as defined by the options. Args: auth: Takes the device cik resource: Takes the dataport alias or rid. options...
380,141
def get_pic(self, playingsong, tempfile_path): url = playingsong[].replace(, ) for _ in range(3): try: urllib.urlretrieve(url, tempfile_path) logger.debug() return True except (IOError, urllib.ContentTooShortError): ...
获取专辑封面
380,142
def get_balance(self): xml_root = self.__init_xml() response = clockwork_http.request(BALANCE_URL, etree.tostring(xml_root, encoding=)) data_etree = etree.fromstring(response[]) err_desc = data_etree.find() if err_desc is not None: raise clockwork_exceptio...
Check the balance fot this account. Returns a dictionary containing: account_type: The account type balance: The balance remaining on the account currency: The currency used for the account balance. Assume GBP in not set
380,143
def _get_padded(data, start, end): if start < 0 and end > data.shape[0]: raise RuntimeError() if start < 0: start_zeros = np.zeros((-start, data.shape[1]), dtype=data.dtype) return np.vstack((start_zeros, data[:end])) elif end > data.shape[0]: ...
Return `data[start:end]` filling in with zeros outside array bounds Assumes that either `start<0` or `end>len(data)` but not both.
380,144
def _resolve_paths(self, *paths): result = set() for path in paths: if os.path.isdir(path): for dirpath, _, filenames in os.walk(path): for filename in filenames: path = os.path.join(dirpath, filename) ...
Resolve paths into a set of filenames (no directories) to check. External tools will handle directories as arguments differently, so for consistency we just want to pass them filenames. This method will recursively walk all directories and filter out any paths that match self.options.i...
380,145
def init(cls, path=None, mkdir=True, odbt=GitCmdObjectDB, expand_vars=True, **kwargs): if path: path = expand_path(path, expand_vars) if mkdir and path and not osp.exists(path): os.makedirs(path, 0o755) git = Git(path) git.init(**kwargs) ...
Initialize a git repository at the given path if specified :param path: is the full path to the repo (traditionally ends with /<name>.git) or None in which case the repository will be created in the current working directory :param mkdir: if specified wi...
380,146
def exists(config): exists = ( pathlib.Path(config.cache_path).exists() and pathlib.Path(config.cache_path).is_dir() ) if not exists: return False index_path = pathlib.Path(config.cache_path) / "index.json" if index_path.exists(): with open(index_path, "r") as ou...
Check whether the .wily/ directory exists. :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: Whether the .wily directory exists :rtype: ``boolean``
380,147
def DynamicCmd(name, plugins): exec( % name) plugin_objects = [] for plugin in plugins: classprefix = plugin[] plugin_list = plugin[] plugin_objects = plugin_objects + \ load_plugins(classprefix, plugin_list) exec_command = make_cmd_class(name, *plugin_objects)(...
Returns a cmd with the added plugins, :param name: TODO: :param plugins: list of plugins
380,148
def get_hubs(self): output = helm( , ) if output.returncode != 0: print("Something went wrong!") print(output.stderr) else: hubs = output.stdout.split() return hubs
Get a list of hubs names. Returns ------- hubs : list List of hub names
380,149
def insert_file(self, file): if type(file) is bytes: file = open(file, ) self.insert_string(file.read())
insert_file(file) Load resources entries from FILE, and insert them into the database. FILE can be a filename (a string)or a file object.
380,150
def set_dhw_on(self, until=None): if until is None: data = {"Mode": "PermanentOverride", "State": "On", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", "State": "On", "UntilTime...
Sets the DHW on until a given time, or permanently.
380,151
async def _upload_chunks( cls, rfile: BootResourceFile, content: io.IOBase, chunk_size: int, progress_callback=None): content.seek(0, io.SEEK_SET) upload_uri = urlparse( cls._handler.uri)._replace(path=rfile._data[]).geturl() uploaded_size = 0 ...
Upload the `content` to `rfile` in chunks using `chunk_size`.
380,152
def predicate_type(self, pred: URIRef) -> URIRef: return self._o.value(pred, RDFS.range)
Return the type of pred :param pred: predicate to map :return:
380,153
def plot_poles(map_axis, plon, plat, A95, label=, color=, edgecolor=, marker=, markersize=20, legend=): map_axis.scatter(plon, plat, marker=marker, color=color, edgecolors=edgecolor, s=markersize, label=label, zorder=101, transform=ccrs.Geodetic()) if isinstance(c...
This function plots paleomagnetic poles and A95 error ellipses on a cartopy map axis. Before this function is called, a plot needs to be initialized with code such as that in the make_orthographic_map function. Examples ------- >>> plons = [200, 180, 210] >>> plats = [60, 40, 35] >>> A95 =...
380,154
def _get(self, url, params={}): req = self._session.get(self._api_prefix + url, params=params) return self._action(req)
Wrapper around request.get() to use the API prefix. Returns a JSON response.
380,155
def _get_argv(index, default=None): return _sys.argv[index] if len(_sys.argv) > index else default
get the argv input argument defined by index. Return the default attribute if that argument does not exist
380,156
def load_plume_package(package, plume_dir, accept_defaults): from canari.commands.load_plume_package import load_plume_package load_plume_package(package, plume_dir, accept_defaults)
Loads a canari package into Plume.
380,157
def is_attacked_by(self, color: Color, square: Square) -> bool: return bool(self.attackers_mask(color, square))
Checks if the given side attacks the given square. Pinned pieces still count as attackers. Pawns that can be captured en passant are **not** considered attacked.
380,158
def svm_train(arg1, arg2=None, arg3=None): prob, param = None, None if isinstance(arg1, (list, tuple)) or (scipy and isinstance(arg1, scipy.ndarray)): assert isinstance(arg2, (list, tuple)) or (scipy and isinstance(arg2, (scipy.ndarray, sparse.spmatrix))) y, x, options = arg1, arg2, arg3 param = svm_parameter...
svm_train(y, x [, options]) -> model | ACC | MSE y: a list/tuple/ndarray of l true labels (type must be int/double). x: 1. a list/tuple of l training instances. Feature vector of each training instance is a list/tuple or dictionary. 2. an l * n numpy ndarray or scipy spmatrix (n: number of features). ...
380,159
def places_photo(client, photo_reference, max_width=None, max_height=None): if not (max_width or max_height): raise ValueError("a max_width or max_height arg is required") params = {"photoreference": photo_reference} if max_width: params["maxwidth"] = max_width if max_height: ...
Downloads a photo from the Places API. :param photo_reference: A string identifier that uniquely identifies a photo, as provided by either a Places search or Places detail request. :type photo_reference: string :param max_width: Specifies the maximum desired width, in pixels. :type max_width: ...
380,160
def fetch(**kwargs): pre = post = run_args = {} if float(__grains__[]) >= 10.2: post += else: pre += run_args[] = True return _wrapper(, pre=pre, post=post, run_args=run_args, **kwargs)
.. versionadded:: 2016.3.4 freebsd-update fetch wrapper. Based on the currently installed world and the configuration options set, fetch all available binary updates. kwargs: Parameters of freebsd-update command.
380,161
def quad_info(name, quad, pretty): cl = clientv1() mosaic, = cl.get_mosaic_by_name(name).items_iter(1) echo_json_response(call_and_wrap(cl.get_quad_by_id, mosaic, quad), pretty)
Get information for a specific mosaic quad
380,162
def from_vertices_and_edges(vertices, edges, vertex_name_key=, vertex_id_key=, edge_foreign_keys=(, ), directed=True): vertex_data = _dicts_to_columns(vertices) edge_data = _dicts_to_columns(edges) n = len(vertices) vertex_index = dict(zip(vertex_data[vertex_id_key], ran...
This representation assumes that vertices and edges are encoded in two lists, each list containing a Python dict for each vertex and each edge, respectively. A distinguished element of the vertex dicts contain a vertex ID which is used in the edge dicts to refer to source and target vertices. All the re...
380,163
def render(obj): def get_v(v): return v % env if isinstance(v, basestring) else v if isinstance(obj, types.StringType): return obj % env elif isinstance(obj, types.TupleType) or isinstance(obj, types.ListType): rv = [] for v in obj: rv.append(get_v(v)) e...
Convienently render strings with the fabric context
380,164
def get_relevant_policy_section(self, policy_name, group=None): policy_bundle = self._operation_policies.get(policy_name) if not policy_bundle: self._logger.warning( "The policy does not exist.".format(policy_name) ) return None if ...
Look up the policy corresponding to the provided policy name and group (optional). Log any issues found during the look up.
380,165
def validate(self, key, value): if self._validator is not None: self._validator(key, value)
Validation function run before setting. Uses function from __init__.
380,166
def assert_satisfies(v, cond, message=None): if not cond: vname, vexpr = _retrieve_assert_arguments() if not message: message = "Argument `{var}` (= {val!r}) does not satisfy the condition {expr}" \ .format(var=vname, val=v, expr=vexpr) raise H2OValueEr...
Assert that variable satisfies the provided condition. :param v: variable to check. Its value is only used for error reporting. :param bool cond: condition that must be satisfied. Should be somehow related to the variable ``v``. :param message: message string to use instead of the default.
380,167
def close(self): if not self._closed: if self.protocol_version >= 3: log_debug("[ self._append(b"\x02", ()) try: self.send() except ServiceUnavailable: pass log_debug("[ ...
Close the connection.
380,168
def invert_projection(self, X, identities): distances = self.transform(X) if len(distances) != len(identities): raise ValueError("X and identities are not the same length: " "{0} and {1}".format(len(X), len(identities))) node_match = [] ...
Calculate the inverted projection. The inverted projectio of a SOM is created by association each weight with the input which matches it the most, thus giving a good approximation of the "influence" of each input item. Works best for symbolic (instead of continuous) input data. ...
380,169
def plotRatePSD(include=[, ], timeRange=None, binSize=5, maxFreq=100, NFFT=256, noverlap=128, smooth=0, overlay=True, ylim = None, popColors = {}, fontSize=12, figSize=(10,8), saveData=None, saveFig=None, showFig=True): allallCellsallNetStimsE1L2L5allCellseachPoplinebarlineratecountratefileNamefileName fr...
Plot firing rate power spectral density (PSD) - include (['all',|'allCells','allNetStims',|,120,|,'E1'|,('L2', 56)|,('L5',[4,5,6])]): List of data series to include. Note: one line per item, not grouped (default: ['allCells', 'eachPop']) - timeRange ([start:stop]): Time range of spikes show...
380,170
def convert_la_to_rgba(self, row, result): for i in range(len(row) // 3): for j in range(3): result[(4 * i) + j] = row[2 * i] result[(4 * i) + 3] = row[(2 * i) + 1]
Convert a grayscale image with alpha to RGBA.
380,171
def PostRegistration(method): if not isinstance(method, types.FunctionType): raise TypeError("@PostRegistration can only be applied on functions") validate_method_arity(method, "service_reference") _append_object_entry( method, constants.IPOPO_METHOD_CALLBACKS, ...
The service post-registration callback decorator is called after a service of the component has been registered to the framework. The decorated method must accept the :class:`~pelix.framework.ServiceReference` of the registered service as argument:: @PostRegistration def callback_method(...
380,172
def content(): message = m.Message() paragraph = m.Paragraph( m.Image( % resources_path()), style_class= ) message.add(paragraph) body = tr( structure\ highway\ ) tips = m.BulletedList() tips.add(tr( ...
Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message
380,173
def check_dupl_sources(self): dd = collections.defaultdict(list) for src_group in self.src_groups: for src in src_group: try: srcid = src.source_id except AttributeError: srcid = src[] dd[src...
Extracts duplicated sources, i.e. sources with the same source_id in different source groups. Raise an exception if there are sources with the same ID which are not duplicated. :returns: a list of list of sources, ordered by source_id
380,174
def get_data(self): "Get SNMP values from host" alarm_oids = [netsnmp.Varbind(alarms[alarm_id][]) for alarm_id in self.models[self.modem_type][]] metric_oids = [netsnmp.Varbind(metrics[metric_id][]) for metric_id in self.models[self.modem_type][]] response = self.snmp_session.get(netsnmp...
Get SNMP values from host
380,175
def start(self): if not self.auto_retry: self.curl() return while not self.is_finished: try: self.curl() except pycurl.error as e: if e.args[0] == pycurl.E_PARTIAL_FILE: pass ...
Start downloading, handling auto retry, download resume and path moving
380,176
def remove_target(self, target_name: str): if target_name in self.targets: del self.targets[target_name] build_module = split_build_module(target_name) if build_module in self.targets_by_module: self.targets_by_module[build_module].remove(target_name)
Remove (unregister) a `target` from this build context. Removes the target instance with the given name, if it exists, from both the `targets` map and the `targets_by_module` map. Doesn't do anything if no target with that name is found. Doesn't touch the target graph, if it exists.
380,177
def subn_filter(s, find, replace, count=0): return re.gsub(find, replace, count, s)
A non-optimal implementation of a regex filter
380,178
def remove_last(ol,value,**kwargs): aaaaaaaa if( in kwargs): mode = kwargs["mode"] else: mode = "new" new = copy.deepcopy(ol) new.reverse() new.remove(value) new.reverse() if(mode == "new"): return(new) else: ol.clear() ol.extend(new) r...
from elist.elist import * ol = [1,'a',3,'a',5,'a'] id(ol) new = remove_last(ol,'a') ol new id(ol) id(new) #### ol = [1,'a',3,'a',5,'a'] id(ol) rslt = remove_last(ol,'a',mode="original") ol rslt id(ol) ...
380,179
def _adjust_auto(self, real_wave_mfcc, algo_parameters): self.log(u"Called _adjust_auto") self.log(u"Nothing to do, return unchanged")
AUTO (do not modify)
380,180
def start(self): self.log.info("Starting Insecure Session for Monitor %s" % self.monitor_id) if self.socket is not None: raise Exception("Socket already established for %s." % self) try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
Creates a TCP connection to Device Cloud and sends a ConnectionRequest message
380,181
def after_unassign(duplicate_analysis): analysis_events.after_unassign(duplicate_analysis) parent = duplicate_analysis.aq_parent logger.info("Removing duplicate from " .format(duplicate_analysis.getId(), parent.getId())) parent.manage_delObjects([duplicate_analysis.getId()])
Removes the duplicate from the system
380,182
def create_oracle(username, password, host, port, database, **kwargs): return create_engine( _create_oracle(username, password, host, port, database), **kwargs )
create an engine connected to a oracle database using cx_oracle.
380,183
def payload_class_for_element_name(element_name): logger.debug(" looking up payload class for element: {0!r}".format( element_name)) logger.debug(" known: {0!r}".format(STANZA_PAYLOAD_CLASSES)) if element_name in STANZA_PAYLOAD_CLASSES: ...
Return a payload class for given element name.
380,184
def _set_gbc(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=gbc.gbc, is_container=, presence=False, yang_name="gbc", rest_name="gbc", parent=self, choice=(u, u), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extens...
Setter method for gbc, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/gbc (container) If this variable is read-only (config: false) in the source YANG file, then _set_gbc is considered as a private method. Backends looking to populate this variable should do so vi...
380,185
def get_workflow(self): extra_context = self.get_initial() entry_point = self.request.GET.get("step", None) workflow = self.workflow_class(self.request, context_seed=extra_context, entry_point=entry_point) ...
Returns the instantiated workflow class.
380,186
def preferred_width(self, cli, max_available_width): if cli.current_buffer.complete_state: state = cli.current_buffer.complete_state return 2 + max(get_cwidth(c.display_meta) for c in state.current_completions) else: return 0
Report the width of the longest meta text as the preferred width of this control. It could be that we use less width, but this way, we're sure that the layout doesn't change when we select another completion (E.g. that completions are suddenly shown in more or fewer columns.)
380,187
def _get_adjusted_merge_area(self, attrs, insertion_point, no_to_insert, axis): assert axis in range(2) if "merge_area" not in attrs or attrs["merge_area"] is None: return top, left, bottom, right = attrs["merge_area"] selection = ...
Returns updated merge area Parameters ---------- attrs: Dict \tCell attribute dictionary that shall be adjusted insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that shall be...
380,188
def get_variants(data, include_germline=False): data = utils.deepish_copy(data) supported = ["precalled", "vardict", "vardict-java", "vardict-perl", "freebayes", "octopus", "strelka2"] if include_germline: supported.insert(1, "gatk-haplotype") out = [] ...
Retrieve set of variant calls to use for heterogeneity analysis.
380,189
def _count_leading(line, ch): i, n = 0, len(line) while i < n and line[i] == ch: i += 1 return i
Return number of `ch` characters at the start of `line`. Example: >>> _count_leading(' abc', ' ') 3
380,190
def create(self): if self._track is None: self._track = self.db[self.tracking_collection_name]
Create tracking collection. Does nothing if tracking collection already exists.
380,191
def from_file(filepath, delimiter=, blanklines=False): data = [] try: with open(filepath, ) as f: for line in f: if blanklines and line.strip() == : continue data.append(line) except IOError: raise IOError(.format(filepat...
Imports userdata from a file. :type filepath: string :param filepath The absolute path to the file. :type delimiter: string :param: delimiter Delimiter to use with the troposphere.Join(). :type blanklines: boolean :param blanklines If blank lines shoud be ignored rtype: troposphere...
380,192
def map_(input_layer, fn): if not input_layer.is_sequence(): raise ValueError() return [fn(x) for x in input_layer]
Maps the given function across this sequence. To map an entire template across the sequence, use the `as_fn` method on the template. Args: input_layer: The input tensor. fn: A function of 1 argument that is applied to each item in the sequence. Returns: A new sequence Pretty Tensor. Raises: ...
380,193
async def send_from_directory( directory: FilePath, file_name: str, *, mimetype: Optional[str]=None, as_attachment: bool=False, attachment_filename: Optional[str]=None, add_etags: bool=True, cache_timeout: Optional[int]=None, conditional: bool=True...
Send a file from a given directory. Arguments: directory: Directory that when combined with file_name gives the file path. file_name: File name that when combined with directory gives the file path. See :func:`send_file` for the other arguments.
380,194
def build_global(self, global_node): config_block_lines = self.__build_config_block( global_node.config_block) return config.Global(config_block=config_block_lines)
parse `global` section, and return the config.Global Args: global_node (TreeNode): `global` section treenode Returns: config.Global: an object
380,195
def get_first_node( node, node_not_to_step_past ): ingoing = None i = 0 current_node = node while current_node.ingoing: i = random.randrange(len(current_node.ingoing)) if current_node.ingoing[i] == node_not_to_step_past: break ingoing = ...
This is a super hacky way of getting the first node after a statement. We do this because we visit a statement and keep on visiting and get something in return that is rarely the first node. So we loop and loop backwards until we hit the statement or there is nothing to step back to.
380,196
def get_reviews(self, user_id): url = _REVIEWS_USER.format(c_api=_C_API_BEGINNING, api=_API_VERSION, user_id=user_id, at=self.access_token) return _get_request(url...
Get reviews for a particular user
380,197
def conn_aws(cred, crid): driver = get_driver(Provider.EC2) try: aws_obj = driver(cred[], cred[], region=cred[]) except SSLError as e: abort_err("\r SSL Error with AWS: {}".format(e)) except InvalidCredsError as e: abort_err(...
Establish connection to AWS service.
380,198
def uninstall(self, auto_confirm=False): if not self.check_if_exists(): raise UninstallationError("Cannot uninstall requirement %s, not installed" % (self.name,)) dist = self.satisfied_by or self.conflicts_with paths_to_remove = UninstallPathSet(dist) pip_egg_info_...
Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virt...
380,199
def inbox(request, template_name=): message_list = Message.objects.inbox_for(request.user) return render(request, template_name, { : message_list, })
Displays a list of received messages for the current user. Optional Arguments: ``template_name``: name of the template to use.