code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' d = {1: 2, 3: {'a': 'b'}} km,vm = _d2kvmatrix(d) d = {1: {2:{22:222}}, 3: {'a': 'b'}} km,vm = _d2kvmatrix(d) ## km: 按照层次存储pathlist,层次从0开始, { 1: 2, 3: { 'a': 'b' } } km[0] = [[1],[3]] ...
def _d2kvmatrix(d)
d = {1: 2, 3: {'a': 'b'}} km,vm = _d2kvmatrix(d) d = {1: {2:{22:222}}, 3: {'a': 'b'}} km,vm = _d2kvmatrix(d) ## km: 按照层次存储pathlist,层次从0开始, { 1: 2, 3: { 'a': 'b' } } km[0] = [[1],[3]] km[1] = [[...
5.49714
2.305737
2.384114
''' d = {1: {2: {22: 222}}, 3: {'a': 'b'}} km = [[[1], [3]], [[1, 2], [3, 'a']], [[1, 2, 22]]] show_kmatrix(km) ''' rslt = [] for i in range(0,km.__len__()): level = km[i] for j in range(0,level.__len__()): kpl = level[j] print(kpl) ...
def show_kmatrix(km)
d = {1: {2: {22: 222}}, 3: {'a': 'b'}} km = [[[1], [3]], [[1, 2], [3, 'a']], [[1, 2, 22]]] show_kmatrix(km)
3.740611
2.015621
1.85581
''' d = {1: {2: {22: 222}}, 3: {'a': 'b'}} vm = [[[222]], ['b']] show_vmatrix(vm) ''' unhandled = vm while(unhandled.__len__()>0): next_unhandled = [] for i in range(0,unhandled.__len__()): ele = unhandled[i] print(ele) cond = e...
def show_vmatrix(vm)
d = {1: {2: {22: 222}}, 3: {'a': 'b'}} vm = [[[222]], ['b']] show_vmatrix(vm)
5.099692
3.146076
1.620969
''' km = [[[1], [3]], [[1, 2], [3, 'a']], [[1, 2, 22]]] show_kmatrix(km) vm = [[[222]], ['b']] show_vmatrix(vm) d = _kvmatrix2d(km,vm) ''' d = {} kmwfs = get_kmwfs(km) vmwfs = elel.get_wfs(vm) lngth = vmwfs.__len__() for i in range(0,...
def _kvmatrix2d(km,vm)
km = [[[1], [3]], [[1, 2], [3, 'a']], [[1, 2, 22]]] show_kmatrix(km) vm = [[[222]], ['b']] show_vmatrix(vm) d = _kvmatrix2d(km,vm)
4.678333
2.822835
1.657317
''' d = { 'x': { 'x2': 'x22', 'x1': 'x11' }, 'y': { 'y1': 'v1', 'y2': { 'y4': 'v4', 'y3': 'v3' } ...
def _get_rvmat(d)
d = { 'x': { 'x2': 'x22', 'x1': 'x11' }, 'y': { 'y1': 'v1', 'y2': { 'y4': 'v4', 'y3': 'v3' } }, ...
6.273304
3.230198
1.942081
''' get_vndmat_attr(d,['x'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['t'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['u'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['y'],'lsib_path',path2keypath=True) ''' kt,vn = _d2kvmatrix(d) kdmat = _scankm(kt) ...
def get_vndmat_attr(d,keypath,attr,**kwargs)
get_vndmat_attr(d,['x'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['t'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['u'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['y'],'lsib_path',path2keypath=True)
3.4989
2.877941
1.215765
''' d= {1:'a',2:'b',3:'a',4:'d',5:'e'} ed = eded.Edict(d) ed.sub_via_value('a','d') ''' sd = _select_norecur_via_value(self.dict,*vs,**kwargs) return(Edict(sd))
def sub_via_value(self,*vs,**kwargs)
d= {1:'a',2:'b',3:'a',4:'d',5:'e'} ed = eded.Edict(d) ed.sub_via_value('a','d')
7.40952
3.175569
2.333289
result = [] for markup in get_markup_choices(): markup_name = markup[0] result.append({ 'name': markup_name, 'title': markup[1], 'description': trim(get_reader(markup=markup_name).description) }) return result
def radpress_get_markup_descriptions()
Provides markup options. It used for adding descriptions in admin and zen mode. :return: list
4.717961
5.143434
0.917278
parser = argparse.ArgumentParser(description=description) parser.add_argument('key', help="Camellia key.") parser.add_argument('input_file', nargs='*', help="File(s) to read as input data. If none are " "provided, assume STDIN.") parser.add_argument('...
def _get_parser(description)
Build an ArgumentParser with common arguments for both operations.
3.674134
3.691947
0.995175
if keylen not in camcrypt.ACCEPTABLE_KEY_LENGTHS: raise ValueError("key length must be one of 128, 192, or 256") if hexkey: key = key.decode('hex') return camcrypt.CamCrypt(keylen=keylen, key=key)
def _get_crypto(keylen, hexkey, key)
Return a camcrypt.CamCrypt object based on keylen, hexkey, and key.
3.400314
2.420655
1.404708
if filenames: data = "" for filename in filenames: with open(filename, "rb") as f: data += f.read() else: data = sys.stdin.read() return data
def _get_data(filenames)
Read data from file(s) or STDIN. Args: filenames (list): List of files to read to get data. If empty or None, read from STDIN.
2.639387
2.709773
0.974025
if filename: with open(filename, 'wb') as f: f.write(data) else: print data
def _print_results(filename, data)
Print data to a file or STDOUT. Args: filename (str or None): If None, print to STDOUT; otherwise, print to the file with this name. data (str): Data to print.
2.795796
3.589863
0.778803
if not self._timestamp_is_valid(value): value = self._calculate_current_timestamp() self._timestamp = value
def timestamp(self, value)
The local time when the message was written. Must follow the format 'Mmm DD HH:MM:SS'. If the day of the month is less than 10, then it MUST be represented as a space and then the number.
5.659441
7.990125
0.708305
if value is None: value = socket.gethostname() self._hostname = value
def hostname(self, value)
The hostname where the log message was created. Should be the first part of the hostname, or an IP address. Should NOT be set to a fully qualified domain name.
3.439026
4.718889
0.728779
if value is None: value = sys.argv[0] self._tag = value[:self.MAX_TAG_LEN]
def tag(self, value)
The name of the program that generated the log message. The tag can only contain alphanumeric characters. If the tag is longer than {MAX_TAG_LEN} characters it will be truncated automatically.
5.684155
5.064122
1.122436
value = self._prepend_seperator(value) self._content = value
def content(self, value)
The main component of the log message. The content field is a freeform field that often begins with the process ID (pid) of the program that created the message.
10.890636
24.164949
0.450679
pri = PRI(facility, level) header = HEADER() if pid: msg = MSG(content=text, pid=os.getpid()) else: msg = MSG(content=text) packet = Packet(pri, header, msg) self._send_packet_to_hosts(packet)
def log(self, facility, level, text, pid=False)
Send the message text to all registered hosts. The facility and level will be used to create the packet's PRI part. The HEADER will be automatically determined from the current time and hostname. The MSG will be set from the running program's name and the text parameter. This i...
4.649573
4.160492
1.117553
start = time() while time() - start < timeout: tokens = [token for token, pos in self.brown.get_tagged_sent()] current_count = 0 for word, commonness in self.sentence_tool.rate(tokens): if commonness > min_common: current_c...
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 tokens on success >>> Generate...
5.784514
5.250049
1.101802
keywords = [self.wordlist.get_random_word() for _ in range(number_of_words)] password = self.conformizer.conformize(keywords) if hint: keywords = [hint] + keywords return password, self.to_sentence.from_keywords(keywords)
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!mplytheOreticalassessMeNt$', [('Mynheer', False...
5.743114
5.871384
0.978153
self.refresh(count_common=min_length, min_common=min_common, timeout=refresh_timeout) rating = self.sentence_tool.rate(self.tokens) start = time() while time() - start < timeout: pin = '' for token, commonness in rating: if commonness >= ...
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_timeout: timeout to new sentence :return str: ...
4.172633
4.1382
1.008321
self.uri = config["uri"] self.use_https = config.get("https", False) self.method = config.get("method", "GET")
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.
3.977991
2.044744
1.945472
if self.use_https: conn = client.HTTPSConnection(self.host, self.port) else: conn = client.HTTPConnection(self.host, self.port) conn.request(self.method, self.uri) response = conn.getresponse() conn.close() return bool(response.status ...
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 GE...
2.488446
2.030663
1.225435
def sync(): for balancer in self.configurables[Balancer].values(): balancer.sync_file(self.configurables[Cluster].values()) self.work_pool.submit(sync)
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.
9.109601
6.318586
1.441715
if len(self.configurables[Balancer]) == 1: logger.critical( "'%s' config file removed! It was the only balancer left!", name )
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.
12.344252
9.03638
1.366062
discovery.connect() for cluster in self.configurables[Cluster].values(): if cluster.discovery != discovery.name: continue self.launch_thread( cluster.name, discovery.start_watching, cluster, self.sync_balancer_files ...
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.
12.108219
7.830707
1.546249
self.configurables[Discovery][name].stop() self.sync_balancer_files()
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.
52.992203
35.826069
1.479152
if cluster.discovery not in self.configurables[Discovery]: return discovery = self.configurables[Discovery][cluster.discovery] self.launch_thread( cluster.name, discovery.start_watching, cluster, 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).
11.321825
7.910472
1.431245
cluster = self.configurables[Cluster][name] old_discovery = cluster.discovery new_discovery = new_config["discovery"] if old_discovery == new_discovery: self.sync_balancer_files() return logger.info( "Switching '%s' cluster discovery...
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) and that the ne...
3.177374
2.625436
1.210227
discovery_name = self.configurables[Cluster][name].discovery if discovery_name in self.configurables[Discovery]: self.configurables[Discovery][discovery_name].stop_watching( self.configurables[Cluster][name] ) self.kill_thread(name) s...
def on_cluster_remove(self, name)
Stops the cluster's associated discovery method from watching for changes to the cluster's nodes.
7.189126
5.860414
1.226727
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, t...
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 fi...
null
null
null
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:3...
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' ...
null
null
null
parameters = [] pm_dict = self.get_dict() for k, v in pm_dict.iteritems(): parameters += ['--' + k, v] # distance matrix can be provided via remote folder if remote_folder_path is None: parameters += [distance_matrix_file_name] else: ...
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 containing distance matrix file
3.201426
3.87537
0.826095
if not color_available: return string return color + string + colorama.Fore.RESET
def color_string(color, string)
Colorizes a given string, if coloring is available.
7.909341
4.842686
1.633255
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, logging.CRITICAL: colorama.Fore.MAGENTA }.get(level, colorama.Fore...
def color_for_level(level)
Returns the colorama Fore color for a given log level. If color is not available, returns None.
1.996173
1.88393
1.059579
if not color_available: return itertools.cycle([None]) return itertools.cycle( ( colorama.Fore.CYAN, colorama.Fore.BLUE, colorama.Fore.MAGENTA, colorama.Fore.GREEN, ) )
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.
3.598681
3.421651
1.051738
if thread_id not in seen_thread_colors: seen_thread_colors[thread_id] = next(thread_colors) return seen_thread_colors[thread_id]
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.
2.698977
2.593028
1.040859
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), "[%(asctime)s " + level_abbrev + "]" ) thread = color_string( ...
def format(self, record)
Formats a given log record to include the timestamp, log level, thread ID and message. Colorized if coloring is available.
2.953373
2.96155
0.997239
title = cloud.get('title') provider = cloud.get('provider') key = cloud.get('apikey', "") secret = cloud.get('apisecret', "") tenant_name = cloud.get('tenant_name', "") region = cloud.get('region', "") apiurl = cloud.get('apiurl', "") compute_endpoint = cloud.get('compute_endpoint',...
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
2.414186
2.378124
1.015164
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 in machines: cloud_id = machine[0] machine_id...
def associate_keys(user_dict, client)
This whole function is black magic, had to however cause of the way we keep key-machine association
3.591797
3.429083
1.047451
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: retu...
def to_array(self, channels=2)
Generate the array of volume multipliers for the dynamic
2.330832
2.288084
1.018683
statement = SingleSqlStatement(sql) return self.statement(statement).execute(*qmark_params, **named_params)
def sql(self, sql: str, *qmark_params, **named_params)
:deprecated: use self.statement to execute properly-formatted sql statements
6.91679
4.352767
1.589056
statement = SingleSqlStatement(sql) return self.statement(statement).execute_for_params(params).cursor
def _sql(self, sql: str, params=())
:deprecated: use self.sql instead
21.788738
14.034879
1.552471
if self.SacrificeDate: self.Active = False super(PlugEvents, self).save()
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.
23.204557
4.152094
5.58864
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 command(state, args)
Show anime data.
4.455483
4.20851
1.058684
bucket_name, prefix = _get_bucket_and_prefix(s3_loc) datasets = _get_common_prefixes(bucket_name, prefix) bash_cmd = '' for dataset in datasets: dataset = _remove_trailing_backslash(dataset) try: bash_cmd += get_bash_cmd('s3://{}/{}'.format(bucket_name, dataset), ...
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 ignored. :param bucket_name :param prefix
2.727582
2.690379
1.013828
try: f = open(path, 'rb') return make_unicode(f.read(), encoding, encoding_errors) finally: f.close()
def read_unicode(path, encoding, encoding_errors)
Return the contents of a file as a unicode string.
2.986313
3.107969
0.960857
# Get the relative path relative_path = join(directory, template_name) file_with_ext = template_name if extension: # If there is a default extension, but no file extension, then add it file_name, file_ext = splitext(file_with_ext) if not file_ext: file_with_ext ...
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.
3.503925
3.635162
0.963898
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_file(path, encoding, encoding_errors)
Given an existing path, attempt to load it as a unicode string.
3.094052
2.806575
1.10243
abs_path = get_abs_template_path(name, directory, extension) return load_file(abs_path, encoding, encoding_errors)
def load_template(name, directory, extension, encoding, encoding_errors)
Load a template and return its contents as a unicode string.
2.897107
3.043198
0.951994
prepared_request = self.session.prepare_request( requests.Request(method=method_type, **params) ) return prepared_request
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.
3.246935
3.896074
0.833386
url = resource.get_resource_url( resource, base_url=self.Meta.base_url ) if method_type in SINGLE_RESOURCE_METHODS: if not uid and not kwargs: raise MissingUidException url = resource.get_url( url=url, uid=uid, **kwargs...
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: The resource c...
3.385255
3.486475
0.970968
if response.status_code not in valid_status_codes: raise InvalidStatusCodeError( status_code=response.status_code, expected_status_codes=valid_status_codes ) if response.content: data = response.json() if isinst...
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
3.302836
3.327148
0.992693
url = full_resource_url params = { 'headers': self.get_http_headers( resource.Meta.name, method_name, **kwargs), 'url': url } prepared_request = self.prepare_http_request( 'GET', params, **kwargs) response = self.sessio...
def _call_api_single_related_resource(self, resource, full_resource_url, method_name, **kwargs)
For HypermediaResource - make an API call to a known URL
3.753763
3.611703
1.039333
responses = [] for url in url_list: params = { 'headers': self.get_http_headers( resource.Meta.name, method_name, **kwargs), 'url': url } prepared_request = self.prepare_http_request( 'GET', ...
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
2.898604
2.848609
1.017551
assert all([ x.upper() in VALID_METHODS for x in resource_class.Meta.methods]) for method in resource_class.Meta.methods: self._assign_method( resource_class, method.upper() )
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
5.131175
4.593516
1.117047
method_name = resource_class.get_method_name( resource_class, method_type) valid_status_codes = getattr( resource_class.Meta, 'valid_status_codes', DEFAULT_VALID_STATUS_CODES ) # I know what you're going to say, and I'd ...
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
1.74584
1.754368
0.995139
state.cache_manager.teardown() state.cache_manager.setup() EpisodeTypes.forget(state.db) del state.file_picker
def command(state, args)
Purge all caches.
23.005941
18.735983
1.227901
row = tuple(row) if len(row) != self.table_width: raise ValueError('Wrong result row length') self.results.append(row)
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 ...
4.987445
5.152362
0.967992
self.results = list() for row in results: self.append(row)
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',)])
5.558901
7.708182
0.721169
print(tabulate( ((i, *row) for i, row in enumerate(self.results, 1)), headers=self.headers, ))
def print(self)
Print results table. >>> Results(['title'], [('Konosuba',), ('Oreimo',)]).print() # title --- -------- 1 Konosuba 2 Oreimo
5.503914
5.257968
1.046776
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...
def command(state, args)
Unregister watching regexp for an anime.
5.925715
5.342464
1.109173
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[-1:-size:-1]] w = np.hanning(size) y = np.conv...
def smooth_hanning(x, size=11)
smooth a 1D array using a hanning window with requested size.
1.740796
1.696103
1.026351
a = smooth_hanning(vec, k) k2 = (k - 1) / 2 peaks = np.r_[True, a[1:] > a[:-1]] & np.r_[a[:-1] > a[1:], True] p = np.array(np.where(peaks)[0]) maxidx = np.zeros(np.shape(p)) maxvals = np.zeros(np.shape(p)) for i, pk in enumerate(p): maxidx[i] = np.argmax(vec[pk - k2:pk +...
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
2.590825
2.519609
1.028265
def zeros_coefs(nmax, mmax, coef_type=scalar): if(mmax > nmax): raise ValueError(err_msg['nmax_g_mmax']) if(coef_type == scalar): L = (nmax + 1) + mmax * (2 * nmax - mmax + 1) vec = np.zeros(L, dtype=np.complex128) return ScalarCoefs(vec, nmax, mmax) elif(co...
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.) Examples:: ...
null
null
null
def random_coefs(nmax, mmax, mu=0.0, sigma=1.0, coef_type=scalar): if(mmax > nmax): raise ValueError(err_msg['nmax_g_mmax']) if(coef_type == scalar): L = (nmax + 1) + mmax * (2 * nmax - mmax + 1) vec = np.random.normal(mu, sigma, L) + \ 1j * np.random.normal...
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 largest *m* can be for any *n*. (See *ScalarCoefs* a...
null
null
null
def zeros_patt_uniform(nrows, ncols, patt_type=scalar): if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) if(patt_type == scalar): cdata = np.zeros((2 * nrows - 2, ncols), dtype=np.complex128) return ScalarPatternUniform(cdata, doublesphere=True) ...
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 and corresponds to the phi axis. (...
null
null
null
def random_patt_uniform(nrows, ncols, patt_type=scalar): if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) if(patt_type == scalar): vec = np.random.normal(0.0, 1.0, nrows * ncols) + \ 1j * np.random.normal(0.0, 1.0, nrows * ncols) return Scal...
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. *ncols* must be even and is the number...
null
null
null
def double_sphere(cdata, sym): nrows = cdata.shape[0] ncols = cdata.shape[1] ddata = np.zeros([nrows, ncols], dtype=np.complex128) for n in xrange(0, nrows): for m in xrange(0, ncols): s = sym * cdata[np.mod(nrows - n, nrows), np.mod(i...
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 symmet...
null
null
null
def pretty_coefs(c): cfit = c[0:2, :] cvec = cfit._vec sa = [_tiny_rep(val) for val in cvec] while len(sa) < 9: sa.append("") sa = [sa[n].center(13) for n in range(0, 9)] print(pretty_display_string.format(sa[0], sa[1], sa[2], ...
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 ...
null
null
null
def spht(ssphere, nmax=None, mmax=None): if nmax == None: nmax = ssphere.nrows - 2 mmax = int(ssphere.ncols / 2) - 1 elif mmax == None: mmax = nmax if mmax > nmax: raise ValueError(err_msg['nmax_g_mmax']) if nmax >= ssphere.nrows - 1: raise V...
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 pat...
null
null
null
def vspht(vsphere, nmax=None, mmax=None): 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_mmax']) if nmax >= vsphere.nrows - 1: ra...
Returns a VectorCoefs object containt the vector spherical harmonic coefficients of the VectorPatternUniform object
null
null
null
def spht_slow(ssphere, nmax, mmax): if mmax > nmax: raise ValueError(err_msg['nmax_g_mmax']) nrows = ssphere._dsphere.shape[0] ncols = ssphere._dsphere.shape[1] if np.mod(nrows, 2) == 1 or np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) fdata = np....
(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 (ScalarPatternUn...
null
null
null
def ispht(scoefs, nrows=None, ncols=None): if nrows == None: nrows = scoefs.nmax + 2 if ncols == None: ncols = 2 * scoefs.mmax + 2 if nrows <= scoefs.nmax: raise ValueError(err_msg['inverse_terr']) if ncols < 2 * scoefs.mmax + 2: raise ValueError(er...
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. ...
null
null
null
def ispht_slow(scoefs, nrows, ncols): dnrows = 2 * nrows - 2 if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) fdata = pysphi.sc_to_fc(scoefs._vec, scoefs._nmax, scoefs._mmax, dnrow...
(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 spa...
null
null
null
def sph_harmonic_tp(nrows, ncols, n, m): 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, np.pi, nrows) phi = np.linspace(0.0, 2.0 * np.pi - 2.0 * np.pi / ncols) nu = np.array(range(-...
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.
null
null
null
def size(self): N = self.nmax + 1; NC = N + self.mmax * (2 * N - self.mmax - 1); assert NC == len(self._vec) return NC
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
null
null
null
def copy(self): vec = np.copy(self._vec) return ScalarCoefs(vec, self.nmax, self.mmax)
Make a deep copy of this object. Example:: >>> c2 = c.copy()
null
null
null
def window(self, vec): slce = slice(None, None, None) self.__setitem__((slce, 0), self.__getitem__((slce, 0)) * vec) for m in xrange(1, self.mmax + 1): self.__setitem__((slce, -m), self.__getitem__((slce, -m)) * vec[m:]) self.__setitem__((slce...
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: ...
null
null
null
def angular_power_spectrum(self): # Added this routine as a result of my discussions with Ajinkya Nene #https://github.com/anene list_of_modes = self._reshape_m_vecs() Nmodes = len(list_of_modes) angular_power = np.zeros( Nmodes, dtype = np.double) ...
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.
null
null
null
def _array_2d_repr(self): 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] = lst[0] for m in xrange(1, self.mmax + 1): sc_array[m: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
null
null
null
def _reshape_n_vecs(self): 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
return list of arrays, each array represents a different m mode
null
null
null
def _reshape_m_vecs(self): 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.appe...
return list of arrays, each array represents a different n mode
null
null
null
def _scalar_coef_op_left(func): @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...
decorator for operator overloading when ScalarCoef is on the left
null
null
null
def _scalar_coef_op_right(func): @wraps(func) def verif(self, scoef): if isinstance(scoef, numbers.Number): return ScalarCoefs(func(self, self._vec, scoef), self.nmax, self.mmax) else: raise TypeE...
decorator for operator overloading when ScalarCoef is on the right
null
null
null
def copy(self): vec1 = np.copy(self.scoef1._vec) vec2 = np.copy(self.scoef2._vec) return VectorCoefs(vec1, vec2, self.nmax, self.mmax)
Make a deep copy of this object. Example:: >>> c2 = c.copy()
null
null
null
def _vector_coef_op_left(func): @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, ...
decorator for operator overloading when VectorCoef is on the left
null
null
null
def _vector_coef_op_right(func): @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), ...
decorator for operator overloading when VectorCoefs is on the right
null
null
null
def _scalar_pattern_uniform_op_left(func): @wraps(func) def verif(self, patt): if isinstance(patt, ScalarPatternUniform): if self._dsphere.shape == patt._dsphere.shape: return ScalarPatternUniform(func(self, self._dsphere, ...
Decorator for operator overloading when ScalarPatternUniform is on the left.
null
null
null
def _scalar_pattern_uniform_op_right(func): @wraps(func) def verif(self, patt): if isinstance(patt, numbers.Number): return ScalarPatternUniform(func(self, self._dsphere, patt), doublesphere=True) else: ...
Decorator for operator overloading when ScalarPatternUniform is on the right.
null
null
null
def single_val(self): sv_t = self._sv(self._tdsphere) sv_p = self._sv(self._tdsphere) return (sv_t, sv_p)
return relative error of worst point that might make the data none symmetric.
null
null
null
def _vector_pattern_uniform_op_left(func): @wraps(func) def verif(self, patt): if isinstance(patt, TransversePatternUniform): if self._tdsphere.shape == patt._tdsphere.shape: return TransversePatternUniform(func(self, self._tdsphere, ...
decorator for operator overloading when VectorPatternUniform is on the left
null
null
null
def _vector_pattern_uniform_op_right(func): @wraps(func) def verif(self, patt): if isinstance(patt, numbers.Number): return TransversePatternUniform(func(self, self._tdsphere, patt), func(self, self._pdsphere, patt), ...
decorator for operator overloading when VectorPatternUniform is on the right
null
null
null
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_config = False break if no_existing_config: self.port_overr...
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.
2.943557
2.886986
1.019595
output = _call(["list", "", ""], None, device, address) remotes = [l.split()[-1] for l in output.splitlines() if l] return remotes
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 documenta...
5.998954
7.169174
0.836771
output = _call(["list", remote, ""], None, device, address) codes = [l.split()[-1] for l in output.splitlines() if l] return codes
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 er...
5.919092
6.897341
0.85817
args = ['send_once', remote] + codes _call(args, count, device, address)
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 documentation for subproc...
6.778666
9.447437
0.717514
args = ['send_start', remote, code] _call(args, device, address)
def send_start(remote, code, device=None, address=None)
All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output t...
6.768439
10.57935
0.639778
args = ['send_stop', remote, code] _call(args, None, device, address)
def send_stop(remote, code, device=None, address=None)
All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output t...
7.231748
10.818484
0.668462
args = ['set_transmitters'] + [str(i) for i in transmitters] _call(args, None, device, address)
def set_transmitters(transmitters, device=None, address=None)
All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- transmitters: iterable yielding ints device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.che...
5.149906
6.480122
0.794724
count, packages = fetch() message = "No news is good news !" if count > 0: message = ("{0} software updates are available\n".format(count)) return [message, count, packages]
def check_updates()
Check and display upgraded packages
10.405639
10.004993
1.040045