Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
8,800
def add_content(obj, language, slot, content): placeholder = obj.placeholders.get(slot=slot) add_plugin(placeholder, TextPlugin, language, body=content)
Adds a TextPlugin with given content to given slot
8,801
def get_film(film_id): result = _get(film_id, settings.FILMS) return Film(result.content)
Return a single film
8,802
def _calc_min_width(self, table): width = len(table.name) cap = table.consumed_capacity["__table__"] width = max(width, 4 + len("%.1f/%d" % (cap["read"], table.read_throughput))) width = max(width, 4 + len("%.1f/%d" % (cap["write"], table.write_throughput))) for index_na...
Calculate the minimum allowable width for a table
8,803
def prepare_url(self, url, params): url = to_native_string(url) if not path: path = if is_py2: if isinstance(scheme, str): scheme = scheme.encode() if isinstance(netloc, str): netloc = netloc.encode() ...
Prepares the given HTTP URL.
8,804
def delimit(delimiters, content): if len(delimiters) != 2: raise ValueError( "`delimiters` must be of length 2. Got %r" % delimiters ) return .join([delimiters[0], content, delimiters[1]])
Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") # doctest: +SKIP '[foo]' >>> delimit('""', "foo") # doctest: +SKIP '"foo"'
8,805
def _set_lastpage(self): self.last_page = (len(self._page_data) - 1) // self.screen.page_size
Calculate value of class attribute ``last_page``.
8,806
def verify_signature(certificate, signing_pub_key=None, signing_pub_key_passphrase=None): * cert = _get_certificate_obj(certificate) if signing_pub_key: signing_pub_key = get_public_key(signing_pub_key, passphrase=signing_pub_key_passphr...
Verify that ``certificate`` has been signed by ``signing_pub_key`` certificate: The certificate to verify. Can be a path or string containing a PEM formatted certificate. signing_pub_key: The public key to verify, can be a string or path to a PEM formatted certificate, csr, or ...
8,807
def optimise_partition_multiplex(self, partitions, layer_weights=None, n_iterations=2): if not layer_weights: layer_weights = [1]*len(partitions) itr = 0 diff = 0 continue_iteration = itr < n_iterations or n_iterations < 0 while continue_iteration: diff_inc = _c_leiden._Optimiser_o...
Optimise the given partitions simultaneously. Parameters ---------- partitions List of :class:`~VertexPartition.MutableVertexPartition` layers to optimise. layer_weights List of weights of layers. n_iterations : int Number of iterations to run the Leiden algorithm. By default, 2...
8,808
def ind_nodes(self, graph=None): if graph is None: graph = self.graph dependent_nodes = set( node for dependents in six.itervalues(graph) for node in dependents ) return [node for node in graph.keys() if node not in dependent_nodes]
Returns a list of all nodes in the graph with no dependencies.
8,809
def transform_config_from_estimator(estimator, task_id, task_type, instance_count, instance_type, data, data_type=, content_type=None, compression_type=None, split_type=None, job_name=None, model_name=None, strategy=None, assemble_with=None, output...
Export Airflow transform config from a SageMaker estimator Args: estimator (sagemaker.model.EstimatorBase): The SageMaker estimator to export Airflow config from. It has to be an estimator associated with a training job. task_id (str): The task id of any airflow.contrib.operators.SageMa...
8,810
def understand(self): if self._understand is None: self._understand = Understand(self) return self._understand
:returns: Version understand of preview :rtype: twilio.rest.preview.understand.Understand
8,811
def fix_parameters(self): for W, b in zip(self.W_list, self.b_list): W.fix() b.fix()
Helper function that fixes all parameters
8,812
def get_correlation_matrix_from_columns(self): header_to_column = {} for header in self.headers: header_to_column[header] = self.headers.index(header) data_to_test = [] for header in self.headers_to_test: header_column = Matrix(self.data) \ ...
Computes correlation matrix of columns :return: Correlation matrix of columns
8,813
def to_pandas_closed_closed(date_range, add_tz=True): if not date_range: return None start = date_range.start end = date_range.end if start: start = to_dt(start, mktz()) if add_tz else start if date_range.startopen: start += timedelta(milliseconds=1) if end...
Pandas DateRange slicing is CLOSED-CLOSED inclusive at both ends. Parameters ---------- date_range : `DateRange` object converted to CLOSED_CLOSED form for Pandas slicing add_tz : `bool` Adds a TimeZone to the daterange start and end if it doesn't have one. Returns ---...
8,814
def index(self): config_list = self.config layout = self.layout for (dirpath, dirnames, filenames) in os.walk(self.path): layout_file = self.layout.config_filename if layout_file in filenames: filenames.remove(layout_file) ...
Index all files/directories below the current BIDSNode.
8,815
def decode_terminated(data, encoding, strict=True): codec_info = codecs.lookup(encoding) encoding = codec_info.name if encoding in ("utf-8", "iso8859-1"): index = data.find(b"\x00") if index == -1: res = data.decode(encoding), b"" if str...
Returns the decoded data until the first NULL terminator and all data after it. Args: data (bytes): data to decode encoding (str): The codec to use strict (bool): If True will raise ValueError in case no NULL is found but the available data decoded successfully. Returns:...
8,816
def avoid(self) -> Tuple[Tuple[int], Tuple[int]]: to_avoid = set() for i, state in enumerate(self.global_avoid_states): for word_id in state.avoid(): if word_id > 0: to_avoid.add((i, word_id)) for i, state in enumerate(self.local_avoid_s...
Assembles a list of per-hypothesis words to avoid. The indices are (x, y) pairs into the scores array, which has dimensions (beam_size, target_vocab_size). These values are then used by the caller to set these items to np.inf so they won't be selected. Words to be avoided are selected by consult...
8,817
def json_response(request, data): data["messages"] = [] for msg in messages.get_messages(request): data["messages"].append({: msg.message, : msg.level_tag}) return HttpResponse(json.dumps(data), content_type="application/json")
Wrapper dumping `data` to a json and sending it to the user with an HttpResponse :param django.http.HttpRequest request: The request object used to generate this response. :param dict data: The python dictionnary to return as a json :return: The content of ``data`` serialized in json :r...
8,818
def confd_state_loaded_data_models_data_model_namespace(self, **kwargs): config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") loaded_data_models = ET.SubElement(confd_state, "loaded-data-models") data_m...
Auto Generated Code
8,819
def _calculate_timestamps(self): self._timestamps_data = [] if not self._is_reversed: self._calc_timestamps(self.st_time, self.end_time) else: self._calc_timestamps(self.st_time, DateTime.from_hoy(8759)) self._calc_timestamps(DateTime.from_hoy(0), sel...
Return a list of Ladybug DateTime in this analysis period.
8,820
def kill_tasks(self, app_id, scale=False, wipe=False, host=None, batch_size=0, batch_delay=0): def batch(iterable, size): sourceiter = iter(iterable) while True: batchiter = itertools.islice(sourceiter, size) yield itertools.cha...
Kill all tasks belonging to app. :param str app_id: application ID :param bool scale: if true, scale down the app by the number of tasks killed :param str host: if provided, only terminate tasks on this Mesos slave :param int batch_size: if non-zero, terminate tasks in groups of this si...
8,821
def require_scopes_exact(self, scope_string): num_scopes = len(_process_scopes(scope_string)) pks = [v[] for v in self.annotate(models.Count()).require_scopes(scope_string).filter( scopes__count=num_scopes).values(, )] return self.filter(pk__in=pks)
:param scope_string: The required scopes. :type scope_string: Union[str, list] :return: The tokens with only the requested scopes. :rtype: :class:`esi.managers.TokenQueryset`
8,822
def excess_sharpe(returns, factor_returns, out=None): allocated_output = out is None if allocated_output: out = np.empty(returns.shape[1:]) returns_1d = returns.ndim == 1 if len(returns) < 2: out[()] = np.nan if returns_1d: out = out.item() return out ...
Determines the Excess Sharpe of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns: float / series Benchmark return to compare returns ag...
8,823
def get_terms_in_subset(ont, subset): namedGraph = get_named_graph(ont) query = .format(s=subset, g=namedGraph) bindings = run_sparql(query) return [(r[][],r[][]) for r in bindings]
Find all nodes in a subset. We assume the oboInOwl encoding of subsets, and subset IDs are IRIs
8,824
def set_theme(self, theme_name, toplevel=None, themebg=None): if self._toplevel is not None and toplevel is None: toplevel = self._toplevel if self._themebg is not None and themebg is None: themebg = self._themebg ThemedWidget.set_theme(self, theme_name) ...
Redirect the set_theme call to also set Tk background color
8,825
def _make_namespace(self) -> Namespace: namespace = Namespace( name=self._get_namespace_name(), keyword=self._get_namespace_keyword(), url=self._get_namespace_url(), version=str(time.asctime()), ) self.session.add(namespace) entri...
Make a namespace.
8,826
def _writeData(self, config=None): if config is None: config = ID3SaveConfig() if config.v2_version == 3: frame = self._get_v23_frame(sep=config.v23_separator) else: frame = self data = [] for writer in self._framespec: ...
Raises error
8,827
def check_version_info(conn, version_table, expected_version): version_from_table = conn.execute( sa.select((version_table.c.version,)), ).scalar() if version_from_table is None: version_from_table = 0 if (version_from_table != expected_version): raise Asse...
Checks for a version value in the version table. Parameters ---------- conn : sa.Connection The connection to use to perform the check. version_table : sa.Table The version table of the asset database expected_version : int The expected version of the asset database Rai...
8,828
def datetime_period(base=None, hours=None, minutes=None, seconds=None): if base is None: base = utcnow() base -= timedelta( hours = 0 if hours is None else (base.hour % hours), minutes = (base.minute if hours else 0) if minutes is None else (base.minute % minutes), seconds = (base.second if minutes o...
Round a datetime object down to the start of a defined period. The `base` argument may be used to find the period start for an arbitrary datetime, defaults to `utcnow()`.
8,829
def init_logger( name="", handler_path_levels=None, level=logging.INFO, formatter=None, formatter_str=None, datefmt="%Y-%m-%d %H:%M:%S", ): levels = { "NOTSET": logging.NOTSET, "DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, ...
Add a default handler for logger. Args: name = '' or logger obj. handler_path_levels = [['loggerfile.log',13],['','DEBUG'],['','info'],['','notSet']] # [[path,level]] level = the least level for the logger. formatter = logging.Formatter( '%(levelname)-7s %(asctime)s %(name)s (%(file...
8,830
def get_service_instance(host, username=None, password=None, protocol=None, port=None, mechanism=, principal=None, domain=None): if protocol is None: protocol = if port is None: port = 443 service_instance = GetSi() if service_ins...
Authenticate with a vCenter server or ESX/ESXi host and return the service instance object. host The location of the vCenter server or ESX/ESXi host. username The username used to login to the vCenter server or ESX/ESXi host. Required if mechanism is ``userpass`` password ...
8,831
def goto_assignments(request_data): code = request_data[] line = request_data[] + 1 column = request_data[] path = request_data[] encoding = script = jedi.Script(code, line, column, path, encoding) try: definitions = script.goto_assignments() except jedi.NotFoundError:...
Go to assignements worker.
8,832
def _sid_subdir_path(sid): padded_sid = format(sid, ) return os.path.join( padded_sid[0:2], padded_sid[2:4], "{0}.bcolz".format(str(padded_sid)) )
Format subdir path to limit the number directories in any given subdirectory to 100. The number in each directory is designed to support at least 100000 equities. Parameters ---------- sid : int Asset identifier. Returns ------- out : string A path for the bcolz ro...
8,833
def readString(self, st): if not isinstance(st, str) and not isinstance(st, bytes): raise ValueError("String must be of type string or bytes, not %s" % type(st)) return etree.fromstring(st)
Parse a WFS capabilities document, returning an instance of WFSCapabilitiesInfoset string should be an XML capabilities document
8,834
def geom2localortho(geom): cx, cy = geom.Centroid().GetPoint_2D() lon, lat, z = cT_helper(cx, cy, 0, geom.GetSpatialReference(), wgs_srs) local_srs = localortho(lon,lat) local_geom = geom_dup(geom) geom_transform(local_geom, local_srs) return local_geom
Convert existing geom to local orthographic projection Useful for local cartesian distance/area calculations
8,835
def tablecopy(tablename, newtablename, deep=False, valuecopy=False, dminfo={}, endian=, memorytable=False, copynorows=False): t = table(tablename, ack=False) return t.copy(newtablename, deep=deep, valuecopy=valuecopy, dminfo=dminfo, endian=endian, memorytable=memorytable, ...
Copy a table. It is the same as :func:`table.copy`, but without the need to open the table first.
8,836
def _create_subepochs(x, nperseg, step): axis = x.ndim - 1 nsmp = x.shape[axis] stride = x.strides[axis] noverlap = nperseg - step v_shape = *x.shape[:axis], (nsmp - noverlap) // step, nperseg v_strides = *x.strides[:axis], stride * step, stride v = as_strided(x, shape=v_shape, stride...
Transform the data into a matrix for easy manipulation Parameters ---------- x : 1d ndarray actual data values nperseg : int number of samples in each row to create step : int distance in samples between rows Returns ------- 2d ndarray a view (i.e. doesn'...
8,837
def _bg_combine(self, bgs): out = np.ones(self.h5["raw"].shape, dtype=float) for bg in bgs: out *= bg[:] return out
Combine several background amplitude images
8,838
def grep(self, path, content, flags): try: match = re.compile(content, flags) except sre_constants.error as ex: print("Bad regexp: %s" % (ex)) return for gpath, matches in self.do_grep(path, match): yield (gpath, matches)
grep every child path under path for content
8,839
def start_server(self, host=, port=9000, app=None): from wsgiref.simple_server import make_server if app is None: app = self.wsgi server = make_server(host, port, app) server_addr = "%s:%s" % (server.server_name, server.server_port) print "Server listening at...
Start a `wsgiref.simple_server` based server to run this mapper.
8,840
def leader_get(attribute=None): cmd = [, ] + [attribute or ] return json.loads(subprocess.check_output(cmd).decode())
Juju leader get value(s)
8,841
def set_pending_symbol(self, pending_symbol=None): if pending_symbol is None: pending_symbol = CodePointArray() self.value = bytearray() self.pending_symbol = pending_symbol self.line_comment = False return self
Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``. If the input is None, an empty :class:`CodePointArray` is used.
8,842
def encode(data, encoding=None, errors=, keep=False, preserve_dict_class=False, preserve_tuples=False): if isinstance(data, Mapping): return encode_dict(data, encoding, errors, keep, preserve_dict_class, preserve_tuples) elif isinstance(data, list): ret...
Generic function which will encode whichever type is passed, if necessary If `strict` is True, and `keep` is False, and we fail to encode, a UnicodeEncodeError will be raised. Passing `keep` as True allows for the original value to silently be returned in cases where encoding fails. This can be useful ...
8,843
def sg_flatten(tensor, opt): r dim = np.prod(tensor.get_shape().as_list()[1:]) return tf.reshape(tensor, [-1, dim], name=opt.name)
r"""Reshapes a tensor to `batch_size x -1`. See `tf.reshape()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: name: If provided, it replaces current tensor's name. Returns: A 2-D tensor.
8,844
def name(self): basename = self.basename if basename is None: return None parent = self.Naming_parent if parent is None: return basename else: return parent.generate_unique_name(basename)
The unique name of this object, relative to the parent.
8,845
def compute_freq(self, csd=False): progress = QProgressDialog(, , 0, len(self.data) - 1, self) progress.setWindowModality(Qt.ApplicationModal) freq = self.frequency prep = freq[].get_value() scaling = freq[].get_value() log_tra...
Compute frequency domain analysis. Returns ------- list of dict each item is a dict where 'data' is an instance of ChanFreq for a single segment of signal, 'name' is the event type, if applicable, 'times' is a tuple of the start and end times in sec, 'duratio...
8,846
def get_cgi_parameter_list(form: cgi.FieldStorage, key: str) -> List[str]: return form.getlist(key)
Extracts a list of values, all with the same key, from a CGI form.
8,847
def self_register_user(self, user_name, account_id, user_terms_of_use, pseudonym_unique_id, communication_channel_address=None, communication_channel_type=None, user_birthdate=None, user_locale=None, user_short_name=None, user_sortable_name=None, user_time_zone=None): path = {} data = {} ...
Self register a user. Self register and return a new user and pseudonym for an account. If self-registration is enabled on the account, you can use this endpoint to self register new users.
8,848
def send(self, to, message): super(ProtobufProcess, self).send(to, message.DESCRIPTOR.full_name, message.SerializeToString())
Send a message to another process. Same as ``Process.send`` except that ``message`` is a protocol buffer. Returns immediately. :param to: The pid of the process to send a message. :type to: :class:`PID` :param message: The message to send :type method: A protocol buffer instance. :raises:...
8,849
def italic(s, *, escape=True): r if escape: s = escape_latex(s) return NoEscape(r + s + )
r"""Make a string appear italicized in LaTeX formatting. italic() wraps a given string in the LaTeX command \textit{}. Args ---- s : str The string to be formatted. escape: bool If true the italic text will be escaped Returns ------- NoEscape The formatted stri...
8,850
def get_datetime_type(to_string): from datetime import datetime def datetime_type(string): accepted_date_formats = [, , , ] for form in accepted_date_formats: try: if to_string: return datetime.strpti...
Validates UTC datetime. Examples of accepted forms: 2017-12-31T01:11:59Z,2017-12-31T01:11Z or 2017-12-31T01Z or 2017-12-31
8,851
def container_stop(name, timeout=30, force=True, remote_addr=None, cert=None, key=None, verify_cert=True): container = container_get( name, remote_addr, cert, key, verify_cert, _raw=True ) container.stop(timeout, force, wait=True) return _pylxd_model_to_dict(container)
Stop a container name : Name of the container to stop remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote_addr and its a TCP Address! Examples: https://myserver.lan:8443 /var/lib/mysocket.sock cert : ...
8,852
def unflatten_list(flat_dict, separator=): _unflatten_asserts(flat_dict, separator) unflattened_dict = unflatten(flat_dict, separator) def _convert_dict_to_list(object_, parent_object, parent_object_key): if isinstance(object_, dict): for key in object_: if is...
Unflattens a dictionary, first assuming no lists exist and then tries to identify lists and replaces them This is probably not very efficient and has not been tested extensively Feel free to add test cases or rewrite the logic Issues that stand out to me: - Sorting all the keys in the dictionary, wh...
8,853
def get_win32_short_path_name(long_name): import ctypes from ctypes import wintypes _GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW _GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD] _GetShortPathNameW.restype = wintypes.DWORD output_buf_size = 0...
Gets the short path name of a given long path. References: http://stackoverflow.com/a/23598461/200291 http://stackoverflow.com/questions/23598289/get-win-short-fname-python Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut ...
8,854
def makeDependencyMap(aMap): index = {} for i in aMap.keys(): iNode = index.get(i,None) if not iNode: iNode = Node(i) index[i] = iNode for c in aMap[i]: cNode = index.get(c,None) if not cNode: cNode = Node(c) index[c] = cNode iNode.addChild(cNode) retur...
create a dependency data structure as follows: - Each key in aMap represents an item that depends on each item in the iterable which is that key's value - Each Node represents an item which is a precursor to its parents and depends on its children Returns a map whose keys are the items described in aMap and whose...
8,855
def ip_hide_as_path_holder_as_path_access_list_name(self, **kwargs): config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") hide_as_path_holder = ET.SubElement(ip, "hide-as-path-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-poli...
Auto Generated Code
8,856
def drain_K(self): drain_K = minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_EXIT_K_MINOR return drain_K
Return the minor loss coefficient of the drain pipe. :returns: Minor Loss Coefficient :return: float
8,857
def dehtml(text): try: from HTMLParser import HTMLParser except ImportError: from html.parser import HTMLParser class _DeHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.__text ...
Remove HTML tag in input text and format the texts accordingly.
8,858
def stream(self,Tsec = 2,numChan = 1): self.Tsec = Tsec self.numChan = numChan self.N_samples = int(self.fs*Tsec) self.data_capture = [] self.data_capture_left = [] self.data_capture_right = [] self.capture_sample_count = 0 self.DSP_tic =...
Stream audio using callback Parameters ---------- Tsec : stream time in seconds if Tsec > 0. If Tsec = 0, then stream goes to infinite mode. When in infinite mode, Tsec.stop() can be used to stop the stream. numChan : number of channels. Use 1 for mono and 2 f...
8,859
def get_qcqp_form(prob): if not prob.objective.args[0].is_quadratic(): raise Exception("Objective is not quadratic.") if not all([constr._expr.is_quadratic() for constr in prob.constraints]): raise Exception("Not all constraints are quadratic.") if prob.is_dcp(): logging.wa...
Returns the problem metadata in QCQP class
8,860
def build_application_map(vertices_applications, placements, allocations, core_resource=Cores): application_map = defaultdict(lambda: defaultdict(set)) for vertex, application in iteritems(vertices_applications): chip_cores = application_map[application][placements[vertex...
Build a mapping from application to a list of cores where the application is used. This utility function assumes that each vertex is associated with a specific application. Parameters ---------- vertices_applications : {vertex: application, ...} Applications are represented by the path...
8,861
def _catalog_report_helper(catalog, catalog_validation, url, catalog_id, catalog_org): fields = OrderedDict() fields["catalog_metadata_url"] = url fields["catalog_federation_id"] = catalog_id fields["catalog_federation_org"] = catalog_org f...
Toma un dict con la metadata de un catálogo, y devuelve un dict con los valores que catalog_report() usa para reportar sobre él. Args: catalog (dict): Diccionario con la metadata de un catálogo. validation (dict): Resultado, únicamente a nivel catálogo, de la val...
8,862
def reformat_python_docstrings(top_dirs: List[str], correct_copyright_lines: List[str], show_only: bool = True, rewrite: bool = False, process_only_filenum: int = None) -> None: filenum =...
Walk a directory, finding Python files and rewriting them. Args: top_dirs: list of directories to descend into correct_copyright_lines: list of lines (without newlines) representing the copyright docstring block, including the transition lines of equals symbols ...
8,863
def scale(self, sx, sy=None): if sy is None: sy = sx cairo.cairo_scale(self._pointer, sx, sy) self._check_status()
Modifies the current transformation matrix (CTM) by scaling the X and Y user-space axes by :obj:`sx` and :obj:`sy` respectively. The scaling of the axes takes place after any existing transformation of user space. If :obj:`sy` is omitted, it is the same as :obj:`sx` so t...
8,864
def list_roles(self, principal_name, principal_type): self.send_list_roles(principal_name, principal_type) return self.recv_list_roles()
Parameters: - principal_name - principal_type
8,865
def item_dict(self, item): ret_dict = {"terms":{"category":[],"post_tag":[]}} for e in item: if "category" in e.tag: slug = e.attrib["nicename"] name = htmlparser.unescape(e.text) ...
create a default dict of values, including category and tag lookup
8,866
async def __handle_ping(self, _ : Ping): self.__last_ping = time.time() await ZMQUtils.send(self.__backend_socket, Pong())
Handle a Ping message. Pong the backend
8,867
def compute_ranks(x): assert x.ndim == 1 ranks = np.empty(len(x), dtype=int) ranks[x.argsort()] = np.arange(len(x)) return ranks
Returns ranks in [0, len(x)) Note: This is different from scipy.stats.rankdata, which returns ranks in [1, len(x)].
8,868
def OpenFile(filename, binary=False, newline=None, encoding=None): \n\r\r\nio.opens encoding. If not None, contents obtained from file will be decoded using this `encoding`. :returns file: The open file, it must be closed by the caller @raise: FileNotFoundError When the given filen...
Open a file and returns it. Consider the possibility of a remote file (HTTP, HTTPS, FTP) :param unicode filename: Local or remote filename. :param bool binary: If True returns the file as is, ignore any EOL conversion. If set ignores univeral_newlines parameter. :param None|''...
8,869
def match(self, name): if self.method == Ex.Method.PREFIX: return name.startswith(self.value) elif self.method == Ex.Method.SUFFIX: return name.endswith(self.value) elif self.method == Ex.Method.CONTAINS: return self.value in name elif self.me...
Check if given name matches. Args: name (str): name to check. Returns: bool: matches name.
8,870
def rpc_method(func=None, name=None, entry_point=ALL, protocol=ALL, str_standardization=settings.MODERNRPC_PY2_STR_TYPE, str_standardization_encoding=settings.MODERNRPC_PY2_STR_ENCODING): def decorated(_func): _func.modernrpc_enabled = True _func.modernrpc_name =...
Mark a standard python function as RPC method. All arguments are optional :param func: A standard function :param name: Used as RPC method name instead of original function name :param entry_point: Default: ALL. Used to limit usage of the RPC method for a specific set of entry points :param protoc...
8,871
def update(self, ng_template_id, name=NotUpdated, plugin_name=NotUpdated, hadoop_version=NotUpdated, flavor_id=NotUpdated, description=NotUpdated, volumes_per_node=NotUpdated, volumes_size=NotUpdated, node_processes=NotUpdated, node_configs=NotUpdated, floatin...
Update a Node Group Template.
8,872
def get_ftr(self): if not self.ftr: return self.ftr width = self.size()[0] return re.sub( "%time", "%s\n" % time.strftime("%H:%M:%S"), self.ftr).rjust(width)
Process footer and return the processed string
8,873
def load_toml_path_config(filename): if not os.path.exists(filename): LOGGER.info( "Skipping path loading from non-existent config file: %s", filename) return PathConfig() LOGGER.info("Loading path information from config: %s", filename) try: with open(...
Returns a PathConfig created by loading a TOML file from the filesystem.
8,874
def put_item(TableName=None, Item=None, Expected=None, ReturnValues=None, ReturnConsumedCapacity=None, ReturnItemCollectionMetrics=None, ConditionalOperator=None, ConditionExpression=None, ExpressionAttributeNames=None, ExpressionAttributeValues=None): pass
Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist...
8,875
def __getDependenciesRecursiveWithProvider(self, available_components = None, search_dirs = None, target = None, traverse_links = False, ...
Get installed components using "provider" to find (and possibly install) components. This function is called with different provider functions in order to retrieve a list of all of the dependencies, or install all dependencies. Returns ======= ...
8,876
def view_matrix(self): self._update_yaw_and_pitch() return self._gl_look_at(self.position, self.position + self.dir, self._up)
:return: The current view matrix for the camera
8,877
def police_priority_map_exceed_map_pri7_exceed(self, **kwargs): config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map, "name") name_key.text = kw...
Auto Generated Code
8,878
def max(self, spec): if not isinstance(spec, (list, tuple)): raise TypeError("spec must be an instance of list or tuple") self.__check_okay_to_chain() self.__max = SON(spec) return self
Adds `max` operator that specifies upper bound for specific index. :Parameters: - `spec`: a list of field, limit pairs specifying the exclusive upper bound for all keys of a specific index in order. .. versionadded:: 2.7
8,879
def options(self, *args, **kwargs): data = OrderedDict([(k, v.options(*args, **kwargs)) for k, v in self.data.items()]) return self.clone(data)
Applies simplified option definition returning a new object Applies options defined in a flat format to the objects returned by the DynamicMap. If the options are to be set directly on the objects in the HoloMap a simple format may be used, e.g.: obj.options(cmap='viridis',...
8,880
def get_generator(self, field): if isinstance(field, fields.AutoField): return None if self.is_inheritance_parent(field): return None if ( field.default is not fields.NOT_PROVIDED and not self.overwrite_defaults and field.name ...
Return a value generator based on the field instance that is passed to this method. This function may return ``None`` which means that the specified field will be ignored (e.g. if no matching generator was found).
8,881
def _find_parenthesis(self, position, forward=True): commas = depth = 0 document = self._text_edit.document() char = document.characterAt(position) while category(char) != and position > 0: if char == and depth == 0: commas += 1 ...
If 'forward' is True (resp. False), proceed forwards (resp. backwards) through the line that contains 'position' until an unmatched closing (resp. opening) parenthesis is found. Returns a tuple containing the position of this parenthesis (or -1 if it is not found) and the...
8,882
def tangency_portfolio(cov_mat, exp_rets, allow_short=False): if not isinstance(cov_mat, pd.DataFrame): raise ValueError("Covariance matrix is not a DataFrame") if not isinstance(exp_rets, pd.Series): raise ValueError("Expected returns is not a Series") if not cov_mat.index.equals(exp...
Computes a tangency portfolio, i.e. a maximum Sharpe ratio portfolio. Note: As the Sharpe ratio is not invariant with respect to leverage, it is not possible to construct non-trivial market neutral tangency portfolios. This is because for a positive initial Sharpe ratio the sharpe grows unbound ...
8,883
def import_from_string(self, text, title=None): data = self.model.get_data() if not hasattr(data, "keys"): return editor = ImportWizard(self, text, title=title, contents_title=_("Clipboard contents"), ...
Import data from string
8,884
def mknts(self, add_dct): nts = [] assert len(add_dct) == len(self.nts) flds = list(next(iter(self.nts))._fields) + list(next(iter(add_dct)).keys()) ntobj = cx.namedtuple("ntgoea", " ".join(flds)) for dct_new, ntgoea in zip(add_dct, self.nts): dct_curr = ntgo...
Add information from add_dct to a new copy of namedtuples stored in nts.
8,885
def channels(self): if self._channels is None: self._channels = ChannelList(self._version, service_sid=self._solution[], ) return self._channels
Access the channels :returns: twilio.rest.chat.v2.service.channel.ChannelList :rtype: twilio.rest.chat.v2.service.channel.ChannelList
8,886
def _init_metadata(self): self._min_integer_value = None self._max_integer_value = None self._integer_value_metadata = { : Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, ), : ...
stub
8,887
def match_serializers(self, serializers, default_media_type): return self._match_serializers_by_query_arg(serializers) or self.\ _match_serializers_by_accept_headers(serializers, default_media_type)
Choose serializer for a given request based on query arg or headers. Checks if query arg `format` (by default) is present and tries to match the serializer based on the arg value, by resolving the mimetype mapped to the arg value. Otherwise, chooses the serializer by retrieving the best...
8,888
def binary_dilation(x, radius=3): mask = disk(radius) x = _binary_dilation(x, selem=mask) return x
Return fast binary morphological dilation of an image. see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__. Parameters ----------- x : 2D array A binary image. radius : int For the radius of mas...
8,889
def read_namespaced_event(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.read_namespaced_event_with_http_info(name, namespace, **kwargs) else: (data) = self.read_namespaced_event_with_http_info(name, namespace, **kwargs) ...
read_namespaced_event # noqa: E501 read the specified Event # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_event(name, namespace, async_req=True) >>> result...
8,890
def destroy(self): if self._running is False: return self._running = False if hasattr(self, ): del self.schedule if hasattr(self, ) and self.pub_channel is not None: self.pub_channel.on_recv(None) if hasattr(self.pub_channel, ): ...
Tear down the minion
8,891
def set_cache_complex_value(self, name, value): for item in self.json_state.get(): if item.get() == name: item[] = str(value)
Set a variable in the local complex state dictionary. This does not change the physical device. Useful if you want the device state to refect a new value which has not yet updated from Vera.
8,892
def _join_json_files(cls, prefix, clear=False): filetype_list = [, , ] json_dict = {} try: for filetype in filetype_list: fname = prefix + + filetype + with open(fname, ) as f: json_dict[filetype] = json.load(f) ...
Join different REACH output JSON files into a single JSON object. The output of REACH is broken into three files that need to be joined before processing. Specifically, there will be three files of the form: `<prefix>.uaz.<subcategory>.json`. Parameters ---------- prefi...
8,893
def on_install(self, editor): EditorExtension.on_install(self, editor) self.setParent(editor) self.setPalette(QApplication.instance().palette()) self.setFont(QApplication.instance().font()) self.editor.panels.refresh() self._background_brush = QBrush(QColor( ...
Extends :meth:`spyder.api.EditorExtension.on_install` method to set the editor instance as the parent widget. .. warning:: Don't forget to call **super** if you override this method! :param editor: editor instance :type editor: spyder.plugins.editor.widgets.codeeditor.CodeE...
8,894
def main(args): args = parse_args(args) setup_logging(args.loglevel) _logger.debug("Starting crazy calculations...") print("The {}-th Fibonacci number is {}".format(args.n, fib(args.n))) _logger.info("Script ends here")
Main entry point allowing external calls Args: args ([str]): command line parameter list
8,895
def facilities(self): facilities = [] try: list_items = self._ad_page_content.select(" except Exception as e: if self._debug: logging.error( "Error getting facilities. Error message: " + e.args[0]) return f...
This method returns the properties facilities. :return:
8,896
def fingerprint(P, obs1, obs2=None, p0=None, tau=1, k=None, ncv=None): r if obs2 is None: obs2 = obs1 R, D, L = rdl_decomposition(P, k=k, ncv=ncv) mu = L[0, :] w = np.diagonal(D) timescales = timescales_from_eigenvalues(w, tau) if p0 is None: amplitude...
r"""Dynamical fingerprint for equilibrium or relaxation experiment The dynamical fingerprint is given by the implied time-scale spectrum together with the corresponding amplitudes. Parameters ---------- P : (M, M) scipy.sparse matrix Transition matrix obs1 : (M,) ndarray Observ...
8,897
def from_db_value(self, value, expression, connection, context): if value is None: return value return json_decode(value)
"Called in all circumstances when the data is loaded from the database, including in aggregates and values() calls."
8,898
def get_system_config_dir(): from appdirs import site_config_dir return site_config_dir( appname=Config.APPNAME, appauthor=Config.APPAUTHOR )
Returns system config location. E.g. /etc/dvc.conf. Returns: str: path to the system config directory.
8,899
def get_element_mass(self, element): result = [0] for compound in self.material.compounds: c = self.get_compound_mass(compound) f = [c * x for x in emf(compound, [element])] result = [v+f[ix] for ix, v in enumerate(result)] return result[0]
Determine the masses of elements in the package. :returns: [kg] An array of element masses. The sequence of the elements in the result corresponds with the sequence of elements in the element list of the material.