code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def post_customer_preferences(self, **kwargs): kwargs[] = True if kwargs.get(): return self.post_customer_preferences_with_http_info(**kwargs) else: (data) = self.post_customer_preferences_with_http_info(**kwargs) return data
Update selected fields of customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_customer_preferences(async_req=True) >>> result = thread.ge...
def most_populated(adf): feeds_only = adf[adf.columns[1:-1]] cnt_df = feeds_only.count() cnt = cnt_df.max() selected_feeds = cnt_df[cnt_df == cnt] pre_final = adf[selected_feeds.index[0]] final_df = pd.concat([adf.over...
Looks at each column, using the one with the most values Honours the Trump override/failsafe logic.
async def download(resource_url): scheme = resource_url.parsed.scheme if scheme in (, ): await download_http(resource_url) elif scheme in (, , ): await download_git(resource_url) else: raise ValueError( % scheme)
Download given resource_url
def map(self, mapper): new_categories = self.categories.map(mapper) try: return self.from_codes(self._codes.copy(), categories=new_categories, ordered=self.ordered) except ValueError: ...
Map categories using input correspondence (dict, Series, or function). Maps the categories to new categories. If the mapping correspondence is one-to-one the result is a :class:`~pandas.Categorical` which has the same order property as the original, otherwise a :class:`~pandas.Index` is...
def getImageForBulkExpressions(self, retina_name, body, get_fingerprint=None, image_scalar=2, plot_shape="circle", sparsity=1.0): resourcePath = method = queryParams = {} headerParams = {: , : } postData = None queryParams[] = retina_name queryParams...
Bulk get images for expressions Args: retina_name, str: The retina name (required) body, ExpressionOperation: The JSON encoded expression to be evaluated (required) get_fingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional) ...
def add_spark_slave(self, master, slave, configure): self.reset_server_env(master, configure) with cd(bigdata_conf.spark_home): if not exists(): sudo() spark_env = bigdata_conf.spark_env.format( spark_home=bigdata_conf.spark_home...
add spark slave :return:
def from_path(cls, spec_path): with spec_path.open() as spec_file: return cls.from_document(load(spec_file))
Load a specification from a path. :param FilePath spec_path: The location of the specification to read.
def remove_distribution(self, dist): logger.debug(, dist) name = dist.key del self.dists_by_name[name] del self.dists[(name, dist.version)] for p in dist.provides: name, version = parse_name_and_version(p) logger.debug(, name, version, dist) ...
Remove a distribution from the finder. This will update internal information about who provides what. :param dist: The distribution to remove.
def _year_month_delta_from_elements(elements): return divmod( (int(elements.get(, 0)) * MONTHS_IN_YEAR) + elements.get(, 0), MONTHS_IN_YEAR )
Return a tuple of (years, months) from a dict of date elements. Accepts a dict containing any of the following: - years - months Example: >>> _year_month_delta_from_elements({'years': 2, 'months': 14}) (3, 2)
def _nuclear_factor(self, Tp): sigmaRpp = 10 * np.pi * 1e-27 sigmainel = self._sigma_inel(Tp) sigmainel0 = self._sigma_inel(1e3) f = sigmainel / sigmainel0 f2 = np.where(f > 1, f, 1.0) G = 1.0 + np.log(f2) epsC = 1.37 eps1 = 0.29 ...
Compute nuclear enhancement factor
def metric_crud(client, to_delete): METRIC_NAME = "robots-%d" % (_millis(),) DESCRIPTION = "Robots all up in your server" FILTER = "logName:apache-access AND textPayload:robot" UPDATED_FILTER = "textPayload:robot" UPDATED_DESCRIPTION = "Danger, Will Robinson!" for metric in client.lis...
Metric CRUD.
def _on_ws_message(self, ws, message): logging.debug(message) json_list = json.loads(message) for rx_ack in json_list: ack = EventHub_pb2.Ack() for key, value in rx_ack.items(): setattr(ack, key, value) self._publisher_callback(ack)
on_message callback of websocket class, load the message into a dict and then update an Ack Object with the results :param ws: web socket connection that the message was received on :param message: web socket message in text form :return: None
def _parse_complement(self, tokens): tokens.pop(0) tokens.pop(0) res = self._parse_nested_interval(tokens) tokens.pop(0) res.switch_strand() return res
Parses a complement Complement ::= 'complement' '(' SuperRange ')'
def parse_value(self, value): value = value.strip() if value == : return None try: return float(value) except: pass try: return float.fromhex(value) except: pass ...
Convert value string to float for reporting
def freemem(**kwargs): * conn = __get_conn(**kwargs) mem = _freemem(conn) conn.close() return mem
Return an int representing the amount of memory (in MB) that has not been given to virtual machines on this node :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019....
def _place_ticks_vertical(self): for tick, label in zip(self.ticks, self.ticklabels): y = self.convert_to_pixels(tick) label.place_configure(y=y)
Display the ticks for a vertical slider.
def isUrl(urlString): parsed = urlparse.urlparse(urlString) urlparseValid = parsed.netloc != and parsed.scheme != regex = re.compile( r r r r r r r, re.IGNORECASE) return regex.match(urlString) and urlparseValid
Attempts to return whether a given URL string is valid by checking for the presence of the URL scheme and netloc using the urlparse module, and then using a regex. From http://stackoverflow.com/questions/7160737/
def reindex(self, force=False, background=True): if background: indexingStrategy = else: indexingStrategy = url = self._options[] + r = self._session.get(url, headers=self._options[]) if r.status_code == 503: ...
Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False. If you call reindex() without any parameters it will perform a background reindex only if JIRA thinks it should do it. :param force: reindex even if JIRA doesn't say this is needed, False by default. :pa...
def plot_kurtosis(self, f_start=None, f_stop=None, if_id=0, **kwargs): ax = plt.gca() plot_f, plot_data = self.grab_data(f_start, f_stop, if_id) if self.header[b] < 0: plot_data = plot_data[..., ::-1] plot_f = plot_f[::-1] try: pl...
Plot kurtosis Args: f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz kwargs: keyword args to be passed to matplotlib imshow()
def create_spot_requests(self, price, instance_type=, root_device_type=, size=, vol_type=, delete_on_termination=False, ...
Request creation of one or more EC2 spot instances. :param size: :param vol_type: :param delete_on_termination: :param root_device_type: The type of the root device. :type root_device_type: str :param price: Max price to pay for spot instance per hour. :type pric...
def update(self, other=None, **kwargs): copydict = ImmutableDict() if other: vallist = [(hash(key), (key, other[key])) for key in other] else: vallist = [] if kwargs: vallist += [(hash(key), (key, kwargs[key])) for key in kwargs] copydict.tree = s...
Takes the same arguments as the update method in the builtin dict class. However, this version returns a new ImmutableDict instead of modifying in-place.
def netflowv9_defragment(plist, verb=1): if not isinstance(plist, (PacketList, list)): plist = [plist] definitions = {} definitions_opts = {} ignored = set() for pkt in plist: _netflowv9_defragment_packet(pkt, definitions, ...
Process all NetflowV9/10 Packets to match IDs of the DataFlowsets with the Headers params: - plist: the list of mixed NetflowV9/10 packets. - verb: verbose print (0/1)
def getch(): try: termios.tcsetattr(_fd, termios.TCSANOW, _new_settings) ch = sys.stdin.read(1) finally: termios.tcsetattr(_fd, termios.TCSADRAIN, _old_settings) return ch
get character. waiting for key
def score_samples(self, X, lengths=None): check_is_fitted(self, "startprob_") self._check() X = check_array(X) n_samples = X.shape[0] logprob = 0 posteriors = np.zeros((n_samples, self.n_components)) for i, j in iter_from_X_lengths(X, lengths): ...
Compute the log probability under the model and compute posteriors. Parameters ---------- X : array-like, shape (n_samples, n_features) Feature matrix of individual samples. lengths : array-like of integers, shape (n_sequences, ), optional Lengths of the individ...
def wrap_rethink_errors(func_, *args, **kwargs): try: return func_(*args, **kwargs) except WRAP_RETHINK_ERRORS as reql_err: raise ValueError(str(reql_err))
Wraps rethinkdb specific errors as builtin/Brain errors :param func_: <function> to call :param args: <tuple> positional arguments :param kwargs: <dict> keyword arguments :return: inherits from the called function
def get_languages_from_model(app_label, model_label): try: mod_lan = TransModelLanguage.objects.filter(model=.format(app_label, model_label)).get() languages = [lang.code for lang in mod_lan.languages.all()] return languages except TransModelLanguage.DoesNotE...
Get the languages configured for the current model :param model_label: :param app_label: :return:
def getresponse(self): if self._error: raise compat.saved_exc(self._error) elif self._transport is None: raise HttpError() message = self._queue.get(timeout=self._timeout) if isinstance(message, Exception): raise compat.saved_exc(message) ...
Wait for and return a HTTP response. The return value will be a :class:`HttpMessage`. When this method returns only the response header has been read. The response body can be read using :meth:`~gruvi.Stream.read` and similar methods on the message :attr:`~HttpMessage.body`. No...
def InternalExchange(self, cmd, payload_in): self.logger.debug( + str(list(payload_in))) payload = bytearray() payload[:] = payload_in for _ in range(2): self.InternalSend(cmd, payload) ret_cmd, ret_payload = self.InternalRecv() if ret_cmd == UsbHidTransport.U2FHID_ERROR: ...
Sends and receives a message from the device.
def widgetValue( widget ): for wtype in reversed(_widgetValueTypes): if isinstance(widget, wtype[0]): try: return (wtype[1](widget), True) except: return (None, False) return (None, False)
Returns the value for the inputed widget based on its type. :param widget | <QWidget> :return (<variant> value, <bool> success)
def perform_command(self): if len(self.actual_arguments) < 1: return self.print_help() if self.has_option([u"-e", u"--examples"]): return self.print_examples(False) if self.has_option(u"--examples-all"): return self.print_examples(True) if ...
Perform command and return the appropriate exit code. :rtype: int
def as_cnpj(numero): _num = digitos(numero) if is_cnpj(_num): return .format( _num[:2], _num[2:5], _num[5:8], _num[8:12], _num[12:]) return numero
Formata um número de CNPJ. Se o número não for um CNPJ válido apenas retorna o argumento sem qualquer modificação.
def direction(self, direction): if not isinstance(direction, str): raise TypeError("direction must be of type str") accepted_values = [, , , , , ] if direction not in accepted_values: raise ValueError("must be one of: {}".format(accepted_values)) self._...
set the direction
def recvSecurityList(self, data): securityList = [] while data.dataLen() > 0: securityElement = UInt8() data.readType(securityElement) securityList.append(securityElement) for s in securityList: if s.value in [SecurityType.NONE, S...
Read security list packet send from server to client @param data: Stream that contains well formed packet
def coerce_date_dict(date_dict): keys = [, , , , , ] ret_val = { : 1, : 1, : 1, : 0, : 0, : 0} modified = False for key in keys: try: ret_val[key] = int(date_dict[key]) modified = True except KeyError: ...
given a dictionary (presumed to be from request.GET) it returns a tuple that represents a date. It will return from year down to seconds until one is not found. ie if year, month, and seconds are in the dictionary, only year and month will be returned, the rest will be returned as min. If none of the p...
def _onDecorator(self, name, line, pos, absPosition): d = Decorator(name, line, pos, absPosition) if self.__lastDecorators is None: self.__lastDecorators = [d] else: self.__lastDecorators.append(d)
Memorizes a function or a class decorator
def lsf_stable(filt): lsf_data = lsf(ZFilter(filt.denpoly)) return all(a < b for a, b in blocks(lsf_data, size=2, hop=1))
Tests whether the given filter is stable or not by using the Line Spectral Frequencies (LSF) of the given filter. Needs NumPy. Parameters ---------- filt : A LTI filter as a LinearFilter object. Returns ------- A boolean that is true only when the LSF values from forward and backward prediction fi...
def get_admins(self, account_id, params={}): url = ADMINS_API.format(account_id) admins = [] for data in self._get_paged_resource(url, params=params): admins.append(CanvasAdmin(data=data)) return admins
Return a list of the admins in the account. https://canvas.instructure.com/doc/api/admins.html#method.admins.index
def mi(mi, iq=None, pl=None): CONN.ModifyInstance(mi, IncludeQualifiers=iq, PropertyList=pl)
This function is a wrapper for :meth:`~pywbem.WBEMConnection.ModifyInstance`. Modify the property values of an instance. Parameters: mi (:class:`~pywbem.CIMInstance`): Modified instance, also indicating its instance path. The properties defined in this object specify the new pr...
def user_organization_membership_create(self, user_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organization_memberships api_path = "/api/v2/users/{user_id}/organization_memberships.json" api_path = api_path.format(user_id=user_id) return self.call(api_path, met...
https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-membership
def parse_instancepath(parser, event, node): (next_event, next_node) = six.next(parser) if not _is_start(next_event, next_node, ): raise ParseError() host, namespacepath = parse_namespacepath(parser, next_event, next_node) (next_event, next_node) = six.next(parser) if not _is_...
Parse the CIM/XML INSTANCEPATH element and return an instancname <!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)>
def geo_distance(a, b): a_y = radians(a.y) b_y = radians(b.y) delta_x = radians(a.x - b.x) cos_x = (sin(a_y) * sin(b_y) + cos(a_y) * cos(b_y) * cos(delta_x)) return acos(cos_x) * earth_radius_km
Distance between two geo points in km. (p.x = long, p.y = lat)
def _poll(self) -> None: if self._subprocess is None: raise SublemonLifetimeError( ) elif self._subprocess.returncode is not None: self._exit_code = self._subprocess.returncode self._done_running_evt.set() self._server._running_set...
Check the status of the wrapped running subprocess. Note: This should only be called on currently-running tasks.
def get_templates(self): base = base = self._get_and_update_setting(, base) base = "%s/configs.json" %base return self._get(base)
list templates in the builder bundle library. If a name is provided, look it up
def multiplicity(self): sga = SpacegroupAnalyzer(self.bulk_structure) periodic_struc = sga.get_symmetrized_structure() poss_deflist = sorted( periodic_struc.get_sites_in_sphere(self.site.coords, 2, include_index=True), key=lambda x: x[1]) defindex = poss_deflist[0][2...
Returns the multiplicity of a defect site within the structure (needed for concentration analysis)
def next_offsets(self): resume_bytes = self._resume() with self._meta_lock: if self._chunk_num >= self._total_chunks: return None, resume_bytes if self._offset + self._chunk_size > self._ase.size: num_bytes = self._ase.size - self...
Retrieve the next offsets :param Descriptor self: this :rtype: Offsets :return: upload offsets
def fetchmany(self, *args, **kwargs): if not self.single_cursor_mode: raise S3MError("Calling Connection.fetchmany() while not in single cursor mode") return self._cursor.fetchmany(*args, **kwargs)
Analogous to :any:`sqlite3.Cursor.fetchmany`. Works only in single cursor mode.
def compare_adjs(self, word1, word2): return self._plequal(word1, word2, self.plural_adj)
compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as adjectives return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural for...
def coerce(self, value): if isinstance(value, int) or isinstance(value, compat.long): return value return int(value)
Convert text values into integer values. Args: value (str or int): The value to coerce. Raises: TypeError: If the value is not an int or string. ValueError: If the value is not int or an acceptable value. Returns: int: The integer valu...
def save(self, path): file_handle = open(path, ) file_handle.write(self._file_contents) file_handle.close()
Writes file to a particular location This won't work for cloud environments like Google's App Engine, use with caution ensure to catch exceptions so you can provide informed feedback. prestans does not mask File IO exceptions so your handler can respond better.
def wait_for(self, predicate, timeout=None): if not is_locked(self._lock): raise RuntimeError() hub = get_hub() try: with switch_back(timeout, lock=thread_lock(self._lock)) as switcher: handle = add_callback(self, switcher, predicate) ...
Like :meth:`wait` but additionally for *predicate* to be true. The *predicate* argument must be a callable that takes no arguments. Its result is interpreted as a boolean value.
def _parse_extra(self, fp): comment = section = fp.seek(0) for line in fp: line = line.rstrip() if not line: if comment: comment += continue if line.startswith(): com...
Parse and store the config comments and create maps for dot notion lookup
def session(self): if not self._session: self._session = requests.Session() self._session.headers.update(dict(Authorization=.format(self.token))) return self._session
This is what you should use to make requests. It sill authenticate for you. :return: requests.sessions.Session
def notify_listeners(self, msg_type, params): for c in self.listeners: c.notify(msg_type, params)
Send a message to all the observers.
def net_fluxes(sources, sinks, msm, for_committors=None): flux_matrix = fluxes(sources, sinks, msm, for_committors=for_committors) net_flux = flux_matrix - flux_matrix.T net_flux[np.where(net_flux < 0)] = 0.0 return net_flux
Computes the transition path theory net flux matrix. Parameters ---------- sources : array_like, int The set of unfolded/reactant states. sinks : array_like, int The set of folded/product states. msm : msmbuilder.MarkovStateModel MSM fit to data. for_committors : np.ndar...
def vocab_account_type(instance): for key, obj in instance[].items(): if in obj and obj[] == : try: acct_type = obj[] except KeyError: continue if acct_type not in enums.ACCOUNT_TYPE_OV: yield JSONError("Object is a U...
Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary.
def _build_bst_from_sorted_values(sorted_values): if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_valu...
Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node
def _make_tuple(x): if isinstance(x, prettytensor.PrettyTensor): if x.is_sequence(): return tuple(x.sequence) else: return (x.tensor,) elif isinstance(x, tuple): return x elif (isinstance(x, collections.Sequence) and not isinstance(x, six.string_types)): return tuple(x) el...
TF has an obnoxious habit of being lenient with single vs tuple.
def two_phase_dP_acceleration(m, D, xi, xo, alpha_i, alpha_o, rho_li, rho_gi, rho_lo=None, rho_go=None): r G = 4*m/(pi*D*D) if rho_lo is None: rho_lo = rho_li if rho_go is None: rho_go = rho_gi in_term = (1.-xi)**2/(rho_li*(1.-alpha_i)) + xi*xi/(rho_gi...
r'''This function handles calculation of two-phase liquid-gas pressure drop due to acceleration for flow inside channels. This is a discrete calculation for a segment with a known difference in quality (and ideally known inlet and outlet pressures so density dependence can be included). .. math::...
def disconnectMsToNet(Facility_presence=0, UserUser_presence=0, SsVersionIndicator_presence=0): a = TpPd(pd=0x3) b = MessageType(mesType=0x25) c = Cause() packet = a / b / c if Facility_presence is 1: d = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = pac...
Disconnect Section 9.3.7.2
def write_bel_namespace(self, file: TextIO, use_names: bool = False) -> None: if not self.is_populated(): self.populate() if use_names and not self.has_names: raise ValueError values = ( self._get_namespace_name_to_encoding(desc=) if use...
Write as a BEL namespace file.
def _get_packages(): return [Package(pkg_obj=pkg) for pkg in sorted(pkg_resources.working_set, key=lambda x: str(x).lower())]
Convert `pkg_resources.working_set` into a list of `Package` objects. :return: list
def Down(self, n = 1, dl = 0): self.Delay(dl) self.keyboard.tap_key(self.keyboard.down_key, n)
下方向键n次
def get_indicators_metadata(self, indicators): data = [{ : i.value, : i.type } for i in indicators] resp = self._client.post("indicators/metadata", data=json.dumps(data)) return [Indicator.from_dict(x) for x in resp.json()]
Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has READ access to. :param indicators: a list of |Indicator| objects to quer...
def get_allowed_reset_keys_values(self): reset_keys_action = self._get_reset_keys_action_element() if not reset_keys_action.allowed_values: LOG.warning( , self.path) return set(mappings.SECUREBOOT_RESET_KEYS_MAP_REV) return set([mappings...
Get the allowed values for resetting the system. :returns: A set with the allowed values.
def viewzen_corr(data, view_zen): def ratio(value, v_null, v_ref): return (value - v_null) / (v_ref - v_null) def tau0(t): T_0 = 210.0 T_REF = 320.0 TAU_REF = 9.85 return (1 + TAU_REF)**ratio(t, T_0, T_REF) - 1 def tau(t): T_0 = 170.0 T_REF = 29...
Apply atmospheric correction on the given *data* using the specified satellite zenith angles (*view_zen*). Both input data are given as 2-dimensional Numpy (masked) arrays, and they should have equal shapes. The *data* array will be changed in place and has to be copied before.
def cli_login(self, username=, password=): if not username: username = _cli_input("Username: ") if not password: password = getpass() auth_code = two_factor_code = None prompt_for_unavailable = True result = self.login(username, password) ...
Generates CLI prompts to complete the login process :param username: optionally provide username :type username: :class:`str` :param password: optionally provide password :type password: :class:`str` :return: logon result, see `CMsgClientLogonResponse.eresult <https://github.c...
def from_dataframe(cls, name, df, indices, primary_key=None): column_types = [] nullable = set() for column_name in df.columns: values = df[column_name] if values.isnull().any(): nullable.add(column_name) c...
Infer table metadata from a DataFrame
def Rz_to_coshucosv(R,z,delta=1.,oblate=False): if oblate: d12= (R+delta)**2.+z**2. d22= (R-delta)**2.+z**2. else: d12= (z+delta)**2.+R**2. d22= (z-delta)**2.+R**2. coshu= 0.5/delta*(sc.sqrt(d12)+sc.sqrt(d22)) cosv= 0.5/delta*(sc.sqrt(d12)-sc.sqrt(d22)) if oblat...
NAME: Rz_to_coshucosv PURPOSE: calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta INPUT: R - radius z - height delta= focus oblate= (False) if True, compute oblate confocal coordinates instead of prolate OUTPUT: (cosh(u),co...
def execute(self, table_name=None, table_mode=, use_cache=True, priority=, allow_large_results=False, dialect=None, billing_tier=None): job = self.execute_async(table_name=table_name, table_mode=table_mode, use_cache=use_cache, priority=priority, allow_large_results=a...
Initiate the query, blocking until complete and then return the results. Args: table_name: the result table name as a string or TableName; if None (the default), then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request ...
def xml_entities_to_utf8(text, skip=(, , )): def fixup(m): text = m.group(0) if text[:2] == "& try: if text[:3] == "& return unichr(int(text[3:-1], 16)).encode("utf-8") else: return unichr(int(text[...
Translate HTML or XML character references to UTF-8. Removes HTML or XML character references and entities from a text string and replaces them with their UTF-8 representation, if possible. :param text: The HTML (or XML) source text. :type text: string :param skip: list of entity names to skip wh...
def getwinsize(self): TIOCGWINSZ = getattr(termios, , 1074295912L) s = struct.pack(, 0, 0, 0, 0) x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s) return struct.unpack(, x)[0:2]
This returns the terminal window size of the child tty. The return value is a tuple of (rows, cols).
def create( cls, path, template_engine=None, output_filename=None, output_ext=None, view_name=None ): if isinstance(path, dict): return StatikViewComplexPath( path, templ...
Create the relevant subclass of StatikView based on the given path variable and parameters.
def Hughmark(m, x, alpha, D, L, Cpl, kl, mu_b=None, mu_w=None): r ml = m*(1-x) RL = 1-alpha Nu_TP = 1.75*(RL)**-0.5*(ml*Cpl/RL/kl/L)**(1/3.) if mu_b and mu_w: Nu_TP *= (mu_b/mu_w)**0.14 return Nu_TP*kl/D
r'''Calculates the two-phase non-boiling laminar heat transfer coefficient of a liquid and gas flowing inside a tube of any inclination, as in [1]_ and reviewed in [2]_. .. math:: \frac{h_{TP} D}{k_l} = 1.75(1-\alpha)^{-0.5}\left(\frac{m_l C_{p,l}} {(1-\alpha)k_l L}\right)^{1/3}\left(\f...
def initialize_path(self, path_num=None): for p in self.producers: p.initialize_path(path_num) self.random.seed(hash(self.seed) + hash(path_num))
inits producer for next path, i.e. sets current state to initial state
def cross_validate(data=None, folds=5, repeat=1, metrics=None, reporters=None, model_def=None, **kwargs): md_kwargs = {} if model_def is None: for arg in ModelDefinition.params: if arg in kwargs: md_kwargs[arg] = kwargs.pop(arg) model_def = Mod...
Shortcut to cross-validate a single configuration. ModelDefinition variables are passed in as keyword args, along with the cross-validation parameters.
def do_page_has_content(parser, token): nodelist = parser.parse((,)) parser.delete_first_token() args = token.split_contents() try: content_type = unescape_string_literal(args[1]) except IndexError: raise template.TemplateSyntaxError( "%r tag requires the argument co...
Conditional tag that only renders its nodes if the page has content for a particular content type. By default the current page is used. Syntax:: {% page_has_content <content_type> [<page var name>] %} ... {%_end page_has_content %} Example use:: {% page_has_conten...
def list_pkgs(versions_as_list=False, **kwargs): <package_name><version>* versions_as_list = salt.utils.data.is_true(versions_as_list) if any([salt.utils.data.is_true(kwargs.get(x)) for x in (, )]): return {} if in __context__: if versions_as_list: return _...
List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
def check_bounds_variables(self, dataset): recommended_ctx = TestCtx(BaseCheck.MEDIUM, ) bounds_map = { : { : , : }, : { : , : }, : { : , },...
Checks the grid boundary variables. :param netCDF4.Dataset dataset: An open netCDF dataset
def CopyToStatTimeTuple(self): normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None, None if self._precision in ( definitions.PRECISION_1_NANOSECOND, definitions.PRECISION_100_NANOSECONDS, definitions.PRECISION_1_MICROSECOND, ...
Copies the date time value to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder in 100 nano seconds or (None, None) on error.
def flat_git_tree_to_nested(flat_tree, prefix=): root = _make_empty_dir_dict(prefix if prefix else ) descendent_files = [ info for info in flat_tree if os.path.dirname(info[PATH]).startswith(prefix) ] children_files = [ info for info in descendent_files ...
Given an array in format: [ ["100644", "blob", "ab3ce...", "748", ".gitignore" ], ["100644", "blob", "ab3ce...", "748", "path/to/thing" ], ... ] Outputs in a nested format: { "path": "/", "type": "directory", "children"...
def resize(self, width, height): if not self.fbo: return self.width = width // self.widget.devicePixelRatio() self.height = height // self.widget.devicePixelRatio() self.buffer_width = width self.buffer_height = height super().resize(width,...
Pyqt specific resize callback.
def get_grouped_issues(self, keyfunc=None, sortby=None): if not keyfunc: keyfunc = default_group if not sortby: sortby = self.DEFAULT_SORT self._ensure_cleaned_issues() return self._group_issues(self._cleaned_issues, keyfunc, sortby)
Retrieves the issues in the collection grouped into buckets according to the key generated by the keyfunc. :param keyfunc: a function that will be used to generate the key that identifies the group that an issue will be assigned to. This function receives a single ti...
def load_json(path: str, encoding: str = "utf-8") -> HistogramBase: with open(path, "r", encoding=encoding) as f: text = f.read() return parse_json(text)
Load histogram from a JSON file.
def add(self, indent, line): if isinstance(line, str): list.append(self, indent*4* + line) else: for subline in line: list.append(self, indent*4* + subline)
Appends the given text line with prefixed spaces in accordance with the given number of indentation levels.
def memoize(func): def model(cls, energy, *args, **kwargs): try: memoize = cls._memoize cache = cls._cache queue = cls._queue except AttributeError: memoize = False if memoize: try: w...
Cache decorator for functions inside model classes
def get_metadata(self, handle): handle = os.path.expanduser(os.path.expandvars(handle)) with open(self._prefixed( % handle)) as f: return json.load(f)
Returns the associated metadata info for the given handle, the metadata file must exist (``handle + '.metadata'``). Args: handle (str): Path to the template to get the metadata from Returns: dict: Metadata for the given handle
def simplify_soc_marker(self, text, prev_text): if self.cell_marker_start: return text if self.is_code() and text and text[0] == self.comment + : if not prev_text or not prev_text[-1].strip(): text[0] = self.comment + return text
Simplify start of cell marker when previous line is blank
def set(self, indexes, values=None): if isinstance(indexes, (list, blist)): self.set_rows(indexes, values) else: self.set_cell(indexes, values)
Given indexes will set a sub-set of the Series to the values provided. This method will direct to the below methods based on what types are passed in for the indexes. If the indexes contains values not in the Series then new rows or columns will be added. :param indexes: indexes value, list o...
def create_check(self, label=None, name=None, check_type=None, disabled=False, metadata=None, details=None, monitoring_zones_poll=None, timeout=None, period=None, target_alias=None, target_hostname=None, target_receiver=None, test_only=False, include_debug=False): ...
Creates a check on this entity with the specified attributes. The 'details' parameter should be a dict with the keys as the option name, and the value as the desired setting.
def execute(self, string, max_tacts=None): self.init_tape(string) counter = 0 while True: self.execute_once() if self.state == self.TERM_STATE: break counter += 1 if max_tacts is not None and counter >= max_tacts: ...
Execute algorithm (if max_times = None, there can be forever loop).
def filesfile_string(self): lines = [] app = lines.append pj = os.path.join app(self.input_file.path) app(self.output_file.path) app(pj(self.workdir, self.prefix.idata)) app(pj(self.workdir, self.prefix.odata)) ...
String with the list of files and prefixes needed to execute ABINIT.
def list(self, group=None, host_filter=None, **kwargs): if group: kwargs[] = kwargs.get(, ()) + ((, group),) if host_filter: kwargs[] = kwargs.get(, ()) + ((, host_filter),) return super(Resource, self).list(**kwargs)
Return a list of hosts. =====API DOCS===== Retrieve a list of hosts. :param group: Primary key or name of the group whose hosts will be listed. :type group: str :param all_pages: Flag that if set, collect all pages of content from the API when returning results. :type a...
def ldap_server_host_retries(self, **kwargs): config = ET.Element("config") ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa") host = ET.SubElement(ldap_server, "host") hostname_key = ET.SubElement(host, "hostname") hostname_key....
Auto Generated Code
def unset_variable(section, value): if not value: value = section section = None try: logger.debug() settings = config.Settings(section=section) conf = s3conf.S3Conf(settings=settings) env_vars = conf.get_envfile() env_vars.unset(value) except ex...
Unset a variable in an environment file for the given section. The value is given is the variable name, e.g.: s3conf unset test ENV_VAR_NAME
def is_import_exception(mod): return (mod in IMPORT_EXCEPTIONS or any(mod.startswith(m + ) for m in IMPORT_EXCEPTIONS))
Check module name to see if import has been whitelisted. Import based rules should not run on any whitelisted module
def _parse(self): if self._element.tag == : return self._parse_template(self._element) if self._element.tag == : return self._parse_redirect(self._element) for child in self._element: method_name = + child.tag if hasa...
Loop through all child elements and execute any available parse methods for them
def items(self): contents = self.paths contents = ( BinFile(path.path) if path.is_file else BinDir(path.path) for path in contents ) return contents
Get an iter of VenvDirs and VenvFiles within the directory.
def essays(self): for essay_name in self.dest_user.profile.essays.essay_names: setattr(self.dest_user.profile.essays, essay_name, getattr(self.source_profile.essays, essay_name))
Copy essays from the source profile to the destination profile.
def _num_integral(self, r, c): out = integrate.quad(lambda x: (1-np.exp(-c*x**2))/x, 0, r) return out[0]
numerical integral (1-e^{-c*x^2})/x dx [0..r] :param r: radius :param c: 1/2sigma^2 :return:
def export(self, exporter=None, force_stroke=False): exporter = SVGExporter() if exporter is None else exporter if self._data is None: raise Exception("This SWF was not loaded! (no data)") if len(self.tags) == 0: raise Exception("This SWF doesn't contain any tags...
Export this SWF using the specified exporter. When no exporter is passed in the default exporter used is swf.export.SVGExporter. Exporters should extend the swf.export.BaseExporter class. @param exporter : the exporter to use @param force_stroke : set to true ...