code stringlengths 1 18.2k |
|---|
= Packet(pri, header, msg) self._send_packet_to_hosts(packet) |
def refresh(self, count_common=4, min_common=1000, timeout=20): """ Generate a new sentence :param int count_common: the number of words with minimal commonness :param int min_common: the minimal commonness based on Google common word list :param float timeout: time in seconds to timeout :return list of str: return tok... |
def new_common_diceware_password(self, number_of_words=6, hint=''): """ Return a suggested password :param int number_of_words: number of words generated :param str hint: :return tuple: a suggested password and a sentence >>> GeneratePassword().new_common_diceware_password() ('rive2sidelauraarchitectss!mplytheOreticala... |
def new_pin(self, min_length=4, min_common=1000, timeout=20, refresh_timeout=3): """ Return a suggested PIN :param int min_length: minimum length of the PIN generated :param int min_common: the minimal commonness to be considered convertible to a PIN :param float timeout: main timeout in seconds :param float refresh_ti... |
self.refresh(count_common=min_length, min_common=min_common, timeout=refresh_timeout) rating = self.sentence_tool.rate(self.tokens) else: return pin, list(self.overlap_pin(pin, self.tokens)) return None |
def apply_check_config(self, config): """ Takes a validated config dictionary and sets the `uri`, `use_https` and `method` attributes based on the config's contents. """ self.uri = config["uri"] self.use_https = config.get("https", False) self.method = config.get("method", "GET") |
def perform(self): """ Performs a simple HTTP request against the configured url and returns true if the response has a 2xx code. The url can be configured to use https via the "https" boolean flag in the config, as well as a custom HTTP method via the "method" key. The default is to not use https and the GET method. "... |
def sync_balancer_files(self): """ Syncs the config files for each present Balancer instance. Submits the work to sync each file as a work pool job. """ def sync(): for balancer in self.configurables[Balancer].values(): balancer.sync_file(self.configurables[Cluster].values()) self.work_pool.submit(sync) |
def on_balancer_remove(self, name): """ The removal of a load balancer config isn't supported just yet. If the balancer being removed is the only configured one we fire a critical log message saying so. A writer setup with no balancers is less than useless. """ if len(self.configurables[Balancer]) == 1: logger.critical... |
def on_discovery_add(self, discovery): """ When a discovery is added we call `connect()` on it and launch a thread for each cluster where the discovery watches for changes to the cluster's nodes. """ discovery.connect() for cluster in self.configurables[Cluster].values(): if cluster.discovery != discovery.name: continu... |
def on_discovery_remove(self, name): """ When a Discovery is removed we must make sure to call its `stop()` method to close any connections or do any clean up. """ self.configurables[Discovery][name].stop() self.sync_balancer_files() |
def on_cluster_add(self, cluster): """ Once a cluster is added we tell its associated discovery method to start watching for changes to the cluster's child nodes (if the discovery method is configured and available). """ if cluster.discovery not in self.configurables[Discovery]: return discovery = self.configurables[Di... |
def on_cluster_update(self, name, new_config): """ Callback hook for when a cluster is updated. Or main concern when a cluster is updated is whether or not the associated discovery method changed. If it did, we make sure that the old discovery method stops watching for the cluster's changes (if the old method is around... |
"New discovery '%s' for cluster '%s' is unknown/unavailable.", new_discovery, name ) self.sync_balancer_files() return discovery = self.configurables[Discovery][new_discovery] self.launch_thread( cluster.name, discovery.start_watching, cluster, self.sync_balancer_files ) |
def on_cluster_remove(self, name): """ Stops the cluster's associated discovery method from watching for changes to the cluster's nodes. """ discovery_name = self.configurables[Cluster][name].discovery if discovery_name in self.configurables[Discovery]: self.configurables[Discovery][discovery_name].stop_watching( self.... |
def parse_path(path): '''Parses an address into directory and port parts. The last segment of the address will be checked to see if it matches a port specification (i.e. contains a colon followed by text). This will be returned separately from the directory parts. If a leading / is given, that will be returned as the f... |
parse_path('localhost:30000/manager/comp0.rtc') (['localhost:30000', 'manager', 'comp0.rtc'], None) >>> parse_path('localhost/manager/comp0.rtc:in') (['localhost', 'manager', 'comp0.rtc'], 'in') >>> parse_path('/localhost/manager/comp0.rtc') (['/', 'localhost', 'manager', 'comp0.rtc'], None) >>> parse_path('/localhost/... |
def format_path(path): '''Formats a path as a string, placing / between each component. @param path A path in rtctree format, as a tuple with the port name as the second component. Examples: >>> format_path((['localhost:30000', 'manager', 'comp0.rtc'], None)) 'localhost:30000/manager/comp0.rtc' >>> format_path((['local... |
def cmdline_params(self, distance_matrix_file_name='distance.matrix', remote_folder_path=None): """Synthesize command line parameters e.g. [ ['--output-file', 'out.barcode'], ['distance_matrix.file']] :param distance_matrix_file_name: Name of distance matrix file :param remote_folder_path: Path to remote folder contain... |
def color_string(color, string): """ Colorizes a given string, if coloring is available. """ if not color_available: return string return color + string + colorama.Fore.RESET |
def color_for_level(level): """ Returns the colorama Fore color for a given log level. If color is not available, returns None. """ if not color_available: return None return { logging.DEBUG: colorama.Fore.WHITE, logging.INFO: colorama.Fore.BLUE, logging.WARNING: colorama.Fore.YELLOW, logging.ERROR: colorama.Fore.RED, ... |
def create_thread_color_cycle(): """ Generates a never-ending cycle of colors to choose from for individual threads. If color is not available, a cycle that repeats None every time is returned instead. """ if not color_available: return itertools.cycle([None]) return itertools.cycle( ( colorama.Fore.CYAN, colorama.Fore... |
def color_for_thread(thread_id): """ Associates the thread ID with the next color in the `thread_colors` cycle, so that thread-specific parts of a log have a consistent separate color. """ if thread_id not in seen_thread_colors: seen_thread_colors[thread_id] = next(thread_colors) return seen_thread_colors[thread_id] |
def format(self, record): """ Formats a given log record to include the timestamp, log level, thread ID and message. Colorized if coloring is available. """ if not self.is_tty: return super(CLIHandler, self).format(record) level_abbrev = record.levelname[0] time_and_level = color_string( color_for_level(record.levelno)... |
def add_bare_metal_cloud(client, cloud, keys): """ Black magic is happening here. All of this wil change when we sanitize our API, however, this works until then """ title = cloud.get('title') provider = cloud.get('provider') key = cloud.get('apikey', "") secret = cloud.get('apisecret', "") tenant_name = cloud.get('ten... |
== machine_id: machine_key = i break else: pass client.add_cloud(title, provider, key, secret, tenant_name=tenant_name, region=region, apiurl=apiurl, machine_ip=machine_ip, machine_key=machine_key, machine_user=machine_user, compute_endpoint=compute_endpoint, machine_port=machine_port) |
def associate_keys(user_dict, client): """ This whole function is black magic, had to however cause of the way we keep key-machine association """ added_keys = user_dict['keypairs'] print ">>>Updating Keys-Machines association" for key in added_keys: machines = added_keys[key]['machines'] if machines: try: for machine ... |
def to_array(self, channels=2): """Generate the array of volume multipliers for the dynamic""" if self.fade_type == "linear": return np.linspace(self.in_volume, self.out_volume, self.duration * channels)\ .reshape(self.duration, channels) elif self.fade_type == "exponential": if self.in_volume < self.out_volume: return... |
def sql(self, sql: str, *qmark_params, **named_params): """ :deprecated: use self.statement to execute properly-formatted sql statements """ statement = SingleSqlStatement(sql) return self.statement(statement).execute(*qmark_params, **named_params) |
def _sql(self, sql: str, params=()): """ :deprecated: use self.sql instead """ statement = SingleSqlStatement(sql) return self.statement(statement).execute_for_params(params).cursor |
def save(self): """Over-rides the default save function for PlugEvents. If a sacrifice date is set for an object in this model, then Active is set to False.""" if self.SacrificeDate: self.Active = False super(PlugEvents, self).save() |
def command(state, args): """Show anime data.""" args = parser.parse_args(args[1:]) aid = state.results.parse_aid(args.aid, default_key='db') anime = query.select.lookup(state.db, aid, episode_fields=args.episode_fields) complete_string = 'yes' if anime.complete else 'no' print(SHOW_MSG.format( anime.aid, anime.title, ... |
def load_prefix(s3_loc, success_only=None, recent_versions=None, exclude_regex=None, just_sql=False): """Get a bash command which will load every dataset in a bucket at a prefix. For this to work, all datasets must be of the form `s3://$BUCKET_NAME/$PREFIX/$DATASET_NAME/v$VERSION/$PARTITIONS`. Any other formats will be... |
def read_unicode(path, encoding, encoding_errors): """ Return the contents of a file as a unicode string. """ try: f = open(path, 'rb') return make_unicode(f.read(), encoding, encoding_errors) finally: f.close() |
def get_abs_template_path(template_name, directory, extension): """ Given a template name, a directory, and an extension, return the absolute path to the template. """ # Get the relative path relative_path = join(directory, template_name) file_with_ext = template_name if extension: # If there is a default extension, bu... |
def load_file(path, encoding, encoding_errors): """ Given an existing path, attempt to load it as a unicode string. """ abs_path = abspath(path) if exists(abs_path): return read_unicode(abs_path, encoding, encoding_errors) raise IOError('File %s does not exist' % (abs_path)) |
def load_template(name, directory, extension, encoding, encoding_errors): """ Load a template and return its contents as a unicode string. """ abs_path = get_abs_template_path(name, directory, extension) return load_file(abs_path, encoding, encoding_errors) |
def prepare_http_request(self, method_type, params, **kwargs): """ Prepares the HTTP REQUEST and returns it. Args: method_type: The HTTP method type params: Additional parameters for the HTTP request. kwargs: Any extra keyword arguements passed into a client method. returns: prepared_request: An HTTP request object. ""... |
def call_api(self, method_type, method_name, valid_status_codes, resource, data, uid, **kwargs): """ Make HTTP calls. Args: method_type: The HTTP method method_name: The name of the python method making the HTTP call valid_status_codes: A tuple of integer status codes deemed acceptable as response statuses resource: Th... |
} if method_type in ['POST', 'PUT', 'PATCH'] and isinstance(data, dict): params.update(json=data) prepared_request = self.prepare_http_request( method_type, params, **kwargs) response = self.session.send(prepared_request) return self._handle_response(response, valid_status_codes, resource) |
def _handle_response(self, response, valid_status_codes, resource): """ Handles Response objects Args: response: An HTTP reponse object valid_status_codes: A tuple list of valid status codes resource: The resource class to build from this response returns: resources: A list of Resource instances """ if response.status_... |
def _call_api_single_related_resource(self, resource, full_resource_url, method_name, **kwargs): """ For HypermediaResource - make an API call to a known URL """ url = full_resource_url params = { 'headers': self.get_http_headers( resource.Meta.name, method_name, **kwargs), 'url': url } prepared_request = self.prepare_... |
def _call_api_many_related_resources(self, resource, url_list, method_name, **kwargs): """ For HypermediaResource - make an API call to a list of known URLs """ responses = [] for url in url_list: params = { 'headers': self.get_http_headers( resource.Meta.name, method_name, **kwargs), 'url': url } prepared_request = se... |
def assign_methods(self, resource_class): """ Given a resource_class and it's Meta.methods tuple, assign methods for communicating with that resource. Args: resource_class: A single resource class """ assert all([ x.upper() in VALID_METHODS for x in resource_class.Meta.methods]) for method in resource_class.Meta.method... |
def _assign_method(self, resource_class, method_type): """ Using reflection, assigns a new method to this class. Args: resource_class: A resource class method_type: The HTTP method type """ """ If we assigned the same method to each method, it's the same method in memory, so we need one for each acceptable HTTP method.... |
method_name=method_name, valid_status_codes=valid_status_codes, resource=resource_class, data=None, uid=None, **kwargs): return self.call_api( method_type, method_name, valid_status_codes, resource, data, uid=uid, **kwargs) def patch(self, method_type=method_type, method_name=method_name, valid_status_codes=valid_statu... |
def command(state, args): """Purge all caches.""" state.cache_manager.teardown() state.cache_manager.setup() EpisodeTypes.forget(state.db) del state.file_picker |
def append(self, row): """Append a result row and check its length. >>> x = Results(['title', 'type']) >>> x.append(('Konosuba', 'TV')) >>> x Results(['title', 'type'], [('Konosuba', 'TV')]) >>> x.append(('Konosuba',)) Traceback (most recent call last): ... ValueError: Wrong result row length """ row = tuple(row) if le... |
def set(self, results): """Set results. results is an iterable of tuples, where each tuple is a row of results. >>> x = Results(['title']) >>> x.set([('Konosuba',), ('Oreimo',)]) >>> x Results(['title'], [('Konosuba',), ('Oreimo',)]) """ self.results = list() for row in results: self.append(row) |
def print(self): """Print results table. >>> Results(['title'], [('Konosuba',), ('Oreimo',)]).print() # title --- -------- 1 Konosuba 2 Oreimo """ print(tabulate( ((i, *row) for i, row in enumerate(self.results, 1)), headers=self.headers, )) |
def command(state, args): """Unregister watching regexp for an anime.""" args = parser.parse_args(args[1:]) if args.complete: query.files.delete_regexp_complete(state.db) else: if args.aid is None: parser.print_help() else: aid = state.results.parse_aid(args.aid, default_key='db') query.files.delete_regexp(state.db, ai... |
def novelty(song, k=64, wlen_ms=100, start=0, duration=None, nchangepoints=5, feature="rms"): """Return points of high "novelty" in a song (e.g., significant musical transitions) :param song: Song to analyze :type song: :py:class:`radiotool.composer.Song` :param k: Width of comparison kernel (larger kernel finds coarse... |
list of floats """ if feature != "rms" and feature != "mfcc": raise ValueError, "novelty currently only supports 'rms' and 'mfcc' features" if feature == "rms": frames = song.all_as_mono() wlen_samples = int(wlen_ms * song.samplerate / 1000) if duration is None: frames = frames[start * song.samplerate:] else: frames = ... |
a gaussian taper C_matrix = np.kron(np.eye(2), np.ones((k,k))) -\ np.kron([[0, 1], [1, 0]], np.ones((k,k))) g = scipy.signal.gaussian(2*k, k) C_matrix = np.multiply(C_matrix, np.multiply.outer(g.T, g)) # Created checkerboard kernel N_vec = np.zeros(np.shape(S_matrix)[0]) for i in xrange(k, len(N_vec) - k): S_part = S_m... |
/ 2)] if RMS_energy(left_frames) <\ RMS_energy(right_frames): out_peaks.append(p) out_peaks = [(x[0] * wlen_ms / 2000.0, x[1]) for x in out_peaks] for i, p in enumerate(out_peaks): if i == nchangepoints: break return [x[0] for x in out_peaks[:nchangepoints]] elif feature == "mfcc": beats = analysis["beats"] return [bea... |
def smooth_hanning(x, size=11): """smooth a 1D array using a hanning window with requested size.""" if x.ndim != 1: raise ValueError, "smooth_hanning only accepts 1-D arrays." if x.size < size: raise ValueError, "Input vector needs to be bigger than window size." if size < 3: return x s = np.r_[x[size - 1:0:-1], x, x[-... |
def naive_peaks(vec, k=33): """A naive method for finding peaks of a signal. 1. Smooth vector 2. Find peaks (local maxima) 3. Find local max from original signal, pre-smoothing 4. Return (sorted, descending) peaks """ a = smooth_hanning(vec, k) k2 = (k - 1) / 2 peaks = np.r_[True, a[1:] > a[:-1]] & np.r_[a[:-1] > a[1:]... |
def zeros_coefs(nmax, mmax, coef_type=scalar): """Returns a ScalarCoefs object or a VectorCoeffs object where each of the coefficients is set to 0. The structure is such that *nmax* is th largest *n* can be in c[n, m], and *mmax* is the largest *m* can be for any *n*. (See *ScalarCoefs* and *VectorCoefs* for details.) ... |
hamonic coefficients, the preferred way to do so is vc = spherepy.zeros_coefs( 10, 12, coef_type = spherepy.vector). Returns: coefs: Returns a ScalarCoefs object if coef_type is either blank or set to 0. Returns a VectorCoefs object if coef_type = 1. Raises: TypeError: If coef_type is anything but 0 or 1. """ if(mmax >... |
def random_coefs(nmax, mmax, mu=0.0, sigma=1.0, coef_type=scalar): """Returns a ScalarCoefs object or a VectorCoeffs object where each of the coefficients is a normal random variable with mean 0 and standardard deviation 1.0. The structure is such that *nmax* is th largest *n* can be in c[n, m], and *mmax* is the large... |
you would like to return a set of vector spherical hamonic coefficients, the preferred way to do so is vc = spherepy.zeros_coefs( 10, 12, coef_type = spherepy.vector). Returns: coefs: Returns a ScalarCoefs object if coef_type is either blank or set to 0. Returns a VectorCoefs object if coef_type = 1. Raises: TypeError:... |
sigma, L) vec1[0] = 0 vec2 = np.random.normal(mu, sigma, L) + \ 1j * np.random.normal(mu, sigma, L) vec2[0] = 0 return VectorCoefs(vec1, vec2, nmax, mmax) else: raise TypeError(err_msg['ukn_coef_t']) |
def zeros_patt_uniform(nrows, ncols, patt_type=scalar): """Returns a ScalarPatternUniform object or a VectorPatternUniform object where each of the elements is set to 0. *nrows* is the number of rows in the pattern, which corresponds to the theta axis. *ncols* must be even and is the number of columns in the pattern an... |
scalar, and 1 for vector. The default option is scalar. Returns: coefs: Returns a ScalarPatternUniform object if coef_type is either blank or set to 0. Returns a VectorPatternUniform object if coef_type = 1. Raises: ValueError: If ncols is not even. TypeError: If coef_type is anything but 0 or 1. """ if np.mod(ncols, 2... |
def random_patt_uniform(nrows, ncols, patt_type=scalar): """Returns a ScalarPatternUniform object or a VectorPatternUniform object where each of the elements is set to a normal random variable with zero mean and unit standard deviation. *nrows* is the number of rows in the pattern, which corresponds to the theta axis. ... |
**must** be even. coef_type (int, optional): Set to 0 for scalar, and 1 for vector. The default option is scalar. Returns: coefs: Returns a ScalarPatternUniform object if coef_type is either blank or set to 0. Returns a VectorPatternUniform object if coef_type = 1. Raises: ValueError: If ncols is not even. TypeError: I... |
vec2.reshape((nrows, ncols)), doublesphere=False) else: raise TypeError(err_msg['ukn_patt_t']) |
def double_sphere(cdata, sym): """ Ensures that the data within cdata has double sphere symmetry. Example:: >>> spherepy.doublesphere(cdata, 1) Args: sym (int): is 1 for scalar data and -1 for vector data Returns: numpy.array([*,*], dtype=np.complex128) containing array with doublesphere symmetry. """ nrows = cdata.sha... |
def pretty_coefs(c): """Prints out the first 2 modes of a ScalarCoeffs object. This is mostly used for instructional purposes. (*ScalarPatternUniform*) Example:: >>> spherepy.pretty_coefs(c) c[n, m] ======= 2: 0j 0j 0j 0j 0j 1: 1+0j 0j -1+0j 0: 1j n ------------- ------------- ------------- ------------- ------------- ... |
def spht(ssphere, nmax=None, mmax=None): """Transforms ScalarPatternUniform object *ssphere* into a set of scalar spherical harmonics stored in ScalarCoefs. Example:: >>> p = spherepy.random_patt_uniform(6, 8) >>> c = spherepy.spht(p) >>> spherepy.pretty_coefs(c) Args: ssphere (ScalarPatternUniform): The pattern to be ... |
/ 2) - 1 elif mmax == None: mmax = nmax if mmax > nmax: raise ValueError(err_msg['nmax_g_mmax']) if nmax >= ssphere.nrows - 1: raise ValueError(err_msg['nmax_too_lrg']) if mmax >= ssphere.ncols / 2: raise ValueError(err_msg['mmax_too_lrg']) dnrows = ssphere._dsphere.shape[0] ncols = ssphere._dsphere.shape[1] if np.mod(... |
def vspht(vsphere, nmax=None, mmax=None): """Returns a VectorCoefs object containt the vector spherical harmonic coefficients of the VectorPatternUniform object""" if nmax == None: nmax = vsphere.nrows - 2 mmax = int(vsphere.ncols / 2) - 1 elif mmax == None: mmax = nmax if mmax > nmax: raise ValueError(err_msg['nmax_g_... |
# check if we are using c extended versions of the code or not if use_cext: N = nmax + 1; NC = N + mmax * (2 * N - mmax - 1); sc1 = np.zeros(NC, dtype=np.complex128) sc2 = np.zeros(NC, dtype=np.complex128) csphi.fc_to_sc(Lf1, sc1, nmax, mmax) csphi.fc_to_sc(Lf2, sc2, nmax, mmax) else: sc1 = pysphi.fc_to_sc(Lf1, nmax, m... |
def spht_slow(ssphere, nmax, mmax): """(PURE PYTHON) Transforms ScalarPatternUniform object *ssphere* into a set of scalar spherical harmonics stored in ScalarCoefs. Example:: >>> p = spherepy.random_patt_uniform(6, 8) >>> c = spherepy.spht(p) >>> spherepy.pretty_coefs(c) Args: ssphere (ScalarPatternUniform): The patte... |
= ssphere._dsphere.shape[1] if np.mod(nrows, 2) == 1 or np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) fdata = np.fft.fft2(ssphere._dsphere) / (nrows * ncols) ops.fix_even_row_data_fc(fdata) fdata_extended = np.zeros([nrows + 2, ncols], dtype=np.complex128) ops.pad_rows_fdata(fdata, fdata_extended) ops.... |
def ispht(scoefs, nrows=None, ncols=None): """Transforms ScalarCoefs object *scoefs* into a scalar pattern ScalarPatternUniform. Example:: >>> c = spherepy.random_coefs(3,3) >>> p = spherepy.ispht(c) >>> print(p) Args: scoefs (ScalarCoefs): The coefficients to be transformed to pattern space. nrows (int): The number of... |
raise ValueError(err_msg['inverse_terr']) if ncols < 2 * scoefs.mmax + 2: raise ValueError(err_msg['inverse_terr']) dnrows = int(2 * nrows - 2) if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) if use_cext: fdata = np.zeros([dnrows, ncols], dtype=np.complex128) csphi.sc_to_fc(fdata, scoefs._vec, scoefs.... |
def ispht_slow(scoefs, nrows, ncols): """(PURE PYTHON) Transforms ScalarCoefs object *scoefs* into a scalar pattern ScalarPatternUniform. Example:: >>> c = spherepy.random_coefs(3,3) >>> p = spherepy.ispht(c) >>> print(p) Args: scoefs (ScalarCoefs): The coefficients to be transformed to pattern space. nrows (int): The ... |
def sph_harmonic_tp(nrows, ncols, n, m): """Produces Ynm(theta,phi) theta runs from 0 to pi and has 'nrows' points. phi runs from 0 to 2*pi - 2*pi/ncols and has 'ncols' points. """ nuvec = pysphi.ynunm(n, m, n + 1) num = nuvec[1:] * (-1) ** m num = num[::-1] yvec = np.concatenate([num, nuvec]) theta = np.linspace(0.0, ... |
def size(self): """Total number of coefficients in the ScalarCoefs structure. Example:: >>> sz = c.size >>> N = c.nmax + 1 >>> L = N+ c.mmax * (2 * N - c.mmax - 1); >>> assert sz == L """ N = self.nmax + 1; NC = N + self.mmax * (2 * N - self.mmax - 1); assert NC == len(self._vec) return NC |
def copy(self): """Make a deep copy of this object. Example:: >>> c2 = c.copy() """ vec = np.copy(self._vec) return ScalarCoefs(vec, self.nmax, self.mmax) |
def window(self, vec): """Apply a window to the coefficients defined by *vec*. *vec* must have length *nmax* + 1. This is good way to filter the pattern by windowing in the coefficient domain. Example:: >>> vec = numpy.linspace(0, 1, c.nmax + 1) >>> c.window(vec) Args: vec (numpy.array): Vector of values to apply in th... |
def angular_power_spectrum(self): """Returns the angular power spectrum for the set of coefficients. That is, we compute n c_n = sum cnm * conj( cnm ) m=-n Returns: power_spectrum (numpy.array, dtype=double) spectrum as a function of n. """ # Added this routine as a result of my discussions with Ajinkya Nene #https://g... |
def _array_2d_repr(self): """creates a 2D array that has nmax + 1 rows and 2*mmax + 1 columns and provides a representation for the coefficients that makes plotting easier""" sc_array = np.zeros((self.nmax + 1, 2 * self.mmax + 1), dtype=np.complex128) lst = self._reshape_n_vecs() sc_array[0:self.nmax + 1, self.mmax] = ... |
def _reshape_n_vecs(self): """return list of arrays, each array represents a different m mode""" lst = [] sl = slice(None, None, None) lst.append(self.__getitem__((sl, 0))) for m in xrange(1, self.mmax + 1): lst.append(self.__getitem__((sl, -m))) lst.append(self.__getitem__((sl, m))) return lst |
def _reshape_m_vecs(self): """return list of arrays, each array represents a different n mode""" lst = [] for n in xrange(0, self.nmax + 1): mlst = [] if n <= self.mmax: nn = n else: nn = self.mmax for m in xrange(-nn, nn + 1): mlst.append(self.__getitem__((n, m))) lst.append(mlst) return lst |
def _scalar_coef_op_left(func): """decorator for operator overloading when ScalarCoef is on the left""" @wraps(func) def verif(self, scoef): if isinstance(scoef, ScalarCoefs): if len(self._vec) == len(scoef._vec): return ScalarCoefs(func(self, self._vec, scoef._vec), self.nmax, self.mmax) else: raise ValueError(err_msg... |
def _scalar_coef_op_right(func): """decorator for operator overloading when ScalarCoef is on the right""" @wraps(func) def verif(self, scoef): if isinstance(scoef, numbers.Number): return ScalarCoefs(func(self, self._vec, scoef), self.nmax, self.mmax) else: raise TypeError(err_msg['no_combi_SC']) return verif |
def copy(self): """Make a deep copy of this object. Example:: >>> c2 = c.copy() """ vec1 = np.copy(self.scoef1._vec) vec2 = np.copy(self.scoef2._vec) return VectorCoefs(vec1, vec2, self.nmax, self.mmax) |
def _vector_coef_op_left(func): """decorator for operator overloading when VectorCoef is on the left""" @wraps(func) def verif(self, vcoef): if isinstance(vcoef, VectorCoefs): if len(vcoef.scoef1._vec) == len(vcoef.scoef1._vec): return VectorCoefs(func(self, self.scoef1._vec, vcoef.scoef1._vec), func(self, self.scoef2.... |
def _vector_coef_op_right(func): """decorator for operator overloading when VectorCoefs is on the right""" @wraps(func) def verif(self, vcoef): if isinstance(vcoef, numbers.Number): return VectorCoefs(func(self, self.scoef1._vec, vcoef), func(self, self.scoef2._vec, vcoef), self.nmax, self.mmax) else: raise TypeError(e... |
def _scalar_pattern_uniform_op_left(func): """Decorator for operator overloading when ScalarPatternUniform is on the left.""" @wraps(func) def verif(self, patt): if isinstance(patt, ScalarPatternUniform): if self._dsphere.shape == patt._dsphere.shape: return ScalarPatternUniform(func(self, self._dsphere, patt._dsphere)... |
def _scalar_pattern_uniform_op_right(func): """Decorator for operator overloading when ScalarPatternUniform is on the right.""" @wraps(func) def verif(self, patt): if isinstance(patt, numbers.Number): return ScalarPatternUniform(func(self, self._dsphere, patt), doublesphere=True) else: raise TypeError(err_msg['no_combi... |
def single_val(self): """return relative error of worst point that might make the data none symmetric. """ sv_t = self._sv(self._tdsphere) sv_p = self._sv(self._tdsphere) return (sv_t, sv_p) |
def _vector_pattern_uniform_op_left(func): """decorator for operator overloading when VectorPatternUniform is on the left""" @wraps(func) def verif(self, patt): if isinstance(patt, TransversePatternUniform): if self._tdsphere.shape == patt._tdsphere.shape: return TransversePatternUniform(func(self, self._tdsphere, patt... |
def _vector_pattern_uniform_op_right(func): """decorator for operator overloading when VectorPatternUniform is on the right""" @wraps(func) def verif(self, patt): if isinstance(patt, numbers.Number): return TransversePatternUniform(func(self, self._tdsphere, patt), func(self, self._pdsphere, patt), doublesphere=True) e... |
async def async_set_port_poe_mode(self, port_idx, mode): """Set port poe mode. Auto, 24v, passthrough, off. Make sure to not overwrite any existing configs. """ no_existing_config = True for port_override in self.port_overrides: if port_idx == port_override['port_idx']: port_override['poe_mode'] = mode no_existing_conf... |
def list_remotes(device=None, address=None): """ List the available remotes. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- device: str address: str Returns ------- [str] Notes ----- No attempt is made to catch or handle errors. See the documentatio... |
def list_codes(remote, device=None, address=None): """ List the codes for a given remote. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str device: str address: str Returns ------- [str] Notes ----- No attempt is made to catch or handle err... |
def send_once(remote, codes, count=None, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str codes: [str] count: int device: str address: str Notes ----- No attempt is made to catch or handle errors. See the do... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.