content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def weighting_system_z(): """Z-weighting filter represented as polynomial transfer function. :returns: Tuple of `num` and `den`. Z-weighting is 0.0 dB for all frequencies and therefore corresponds to a multiplication of 1. """ numerator = [1] denomenator = [1] return nume...
8d84c572631c23f50f8a57e388e21fa62e316930
6,300
def shutdown(): """ Shuts down the API (since there is no legit way to kill the thread) Pulled from https://stackoverflow.com/questions/15562446/how-to-stop-flask-application-without-using-ctrl-c """ func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeEr...
a5c1a226fac7c912c11415abb08200cbe2e6f1e3
6,301
def on_post_request(): """This function triggers on every POST request to chosen endpoint""" data_sent = request.data.decode('utf-8') return Response(return_animal_noise(data_sent), mimetype='text/plain')
c43343c697bfde9751dc4bb36b7ad162e7578049
6,302
def settings(comid=None, community=None): """Modify a community.""" pending_records = \ len(CommunityRecordsCollection(community).filter({'status': 'P'})) return render_template( 'invenio_communities/settings.html', community=community, comid=comid, pending_records=pe...
702b41348b461876ebaae49187a3543dbdcd7d0d
6,303
import math def product_of_basins(): """Return the product of the sizes of the three largest basins.""" max_x = len(values[0]) - 1 max_y = len(values) - 1 def heightmap(x, y): """Return the height value in (xth column, yth row).""" return values[y][x] def is_lowpoint(x, y): ...
3624faa5b5d1e991c31f2f0c5f790c68619a0b85
6,304
def singularity26(function): """Decorator to set the global singularity version""" def wrapper(*args, **kwargs): hpccm.config.g_ctype = container_type.SINGULARITY hpccm.config.g_singularity_version = StrictVersion('2.6') return function(*args, **kwargs) return wrapper
a6cdd7f7a8b000a63fa459a38ef6dd3fa0eec037
6,305
def denormalize(series, last_value): """Denormalize the values for a given series. This uses the last value available (i.e. the last closing price of the week before our prediction) as a reference for scaling the predicted results. """ result = last_value * (series + 1) return result
f4c32aa4248378482f1294c54e706e6ee8d5332d
6,306
import warnings def tfidf( s: pd.Series, max_features=None, min_df=1, max_df=1.0, return_feature_names=False ) -> pd.Series.sparse: """ Represent a text-based Pandas Series using TF-IDF. *Term Frequency - Inverse Document Frequency (TF-IDF)* is a formula to calculate the _relative importance_ of ...
56f07d62254b873fc5581af26160d7bf4fc5d7e6
6,307
from typing import Tuple from typing import Any from typing import Dict import time from typing import cast def decorator(fn: AsyncFn, *, expire: int, maxsize: int) -> AsyncFn: """Cache decorator.""" cache = LRUCache(maxsize=maxsize) @wraps(fn) async def wrapper(*args: Tuple[Any, ...], **kwds: Dict[s...
07bcb2181787f5af00098b9de27186a3e6aa1cfa
6,308
import xml import os def cleanQrc(uiFile): """ Looks for included resources files in provided .ui file If it doesn't find any, it returns the original file else: Adds all search paths to Qt Converts all paths turns this> :/images/C:/Users/mindd/Desktop/Circle...
68d6a175d8080a05cd200ce1830daad0f9920fae
6,309
def pad(data, paddings, mode="CONSTANT", name=None, constant_value=0): """ PlaidML Pad """ # TODO: use / implement other padding method when required # CONSTANT -> SpatialPadding ? | Doesn't support first and last axis + # no support for constant_value # SYMMETRIC -> Requires implement ?...
b531cb4fe543da346c504c6aaca4b8787473e5d0
6,310
def taxon_id(_): """ Always returns 10090, the mouse taxon id. """ return 10090
117fe7f8d56eb9be4ee2b0f4d782b806576faedf
6,311
def rthread_if(data, *forms): """ Similar to rthread, but each form must be a tuple with (test, fn, ...args) and only pass the argument to fn if the boolean test is True. If test is callable, the current value to the callable to decide if fn must be executed or not. Like rthread, Arguments are...
a9afa8576ec3a308d7f1514933e462d4565cf738
6,312
def decompose_matrices(Ks): """ Apply Cholesky decomposition to each matrix in the given list :param Ks: a list of matrices """ Ls = [] for i, K_d in enumerate(Ks): Ls.append(np.linalg.cholesky(K_d)) return Ls
6a14363eab0646f59d3664843ef47c5ad34c5537
6,313
import os import asyncio import json async def plugin_remove_cmd(client, message): """remove an installed plugin. alemiBot plugins are git repos, cloned into the `plugins` folder as git submodules. This will call `git submodule deinit -f`, then remove the related folder in `.git/modules` and last remove \ plugin...
d46ec0a6c82de918bd29b5b68046b6bdf74bfac9
6,314
def ndcg_score(y_pre, y_true, k=20): """ get NDCG@k :param y_pre: numpy (batch_size,x) :param y_true: y_truth: list[batch_size][ground_truth_num] :param k: k :return: NDCG@k """ dcg = dcg_score(y_pre, y_true, k) idcg = dcg_score(y_true, y_true, k) return dcg / idcg
0e9e513f4c8e7ceba18c0a12d0c84e08d210ddcd
6,315
from typing import Optional def get_discount_weights( discount_factor: float, traj_len: int, num_trajs: int = 1 ) -> Optional[npt.NDArray[np.float32]]: """ Return the trajectory discount weight array if applicable :param discount_factor: the discount factor by which the displacements corresponding to ...
0d09fcf8228b1e04790d7874e0ecfffeae9a009a
6,316
import random def touch_to_square(touch_x, touch_y, num_rows, num_cols): """ Given a touch x and y, convert it to a coordinate on the square. """ x = clamp(maprange((PAD_Y_RANGE_MAX, PAD_Y_RANGE_MIN), (0, num_rows), touch_y) + random.randrange(-1, 2), ...
f7320e7e9738f7e05b3e675c706b28182a12de9a
6,317
def is_valid_scheme(url): """Judge whether url is valid scheme.""" return urlparse(url).scheme in ["ftp", "gopher", "http", "https"]
4240ec4251e8f937c6f755d123b0b52f88057420
6,318
def height_to_transmission(height, material, energy, rho=0, photo_only=False, source='nist'): """ Calculates the resulting x-ray transmission of an object based on the given height (thickness) and for a given material and energy. Parameters ========== height: grating...
54e2933b06e0489fdc521c4f173d516038f32ee8
6,319
def assignModelClusters(keyframe_model, colors): """ Map each colorspace segment to the closest color in the input. Parameters ---------- keyframe_model : FrameScorer colors : numpy array of int, shape (num_colors, 3) """ hsv_mean_img = keyframe_model.hsv_means.copy().reshape(1, keyframe_m...
d32c093c8931272215bec12d08b4b268da50f184
6,320
def sort_according_to_ref_list(fixturenames, param_names): """ Sorts items in the first list, according to their position in the second. Items that are not in the second list stay in the same position, the others are just swapped. A new list is returned. :param fixturenames: :param param_names:...
d4f1ca19b54ccbdbd70c865abceca1817ce5b2c1
6,321
def calc_ef_from_bases(x,*args): """ Calculate energies and forces of every samples using bases data. """ global _hl1,_ergs,_frcs,_wgt1,_wgt2,_wgt3,_aml,_bml #.....initialize variables if _nl == 1: _wgt1,_wgt2= vars2wgts(x) elif _nl == 2: _wgt1,_wgt2,_wgt3= vars2wgts(x) ...
d54c285c04dd8ae948fb13553251f0675c1af4bc
6,322
def HIadj_post_anthesis( NewCond_DelayedCDs, NewCond_sCor1, NewCond_sCor2, NewCond_DAP, NewCond_Fpre, NewCond_CC, NewCond_fpost_upp, NewCond_fpost_dwn, ...
9101dba12642dc7f1f4b0bbe9f35d7e926f6af0a
6,323
def packify(fmt=u'8', fields=[0x00], size=None, reverse=False): """ Packs fields sequence of bit fields into bytearray of size bytes using fmt string. Each white space separated field of fmt is the length of the associated bit field If not provided size is the least integer number of bytes that hold the...
882d4fd9e3ec626f499f7c4653f6c3864ad64095
6,324
def fix_conf_params(conf_obj, section_name): """from a ConfigParser object, return a dictionary of all parameters for a given section in the expected format. Because ConfigParser defaults to values under [DEFAULT] if present, these values should always appear unless the file is really bad. :param c...
55cdb572e2b45f437c583429ed9ee61f0de9b3de
6,325
def sackStringToSack(sackString): """ C{sackString} is a C{str}. Returns a L{window.SACK}. """ try: # If not enough args for split, Python raises ValueError joinedSackList, ackNumberStr = sackString.rsplit('|', 1) ackNumber = strToIntInRange(ackNumberStr, -1, 2**53) sackList = tuple(strToNonNegLimit(s, 2**...
9fd5ef91f6e897758f47de006a582b5b1ec99f82
6,326
def setup_graph(event, sta, chan, band, tm_shape, tm_type, wm_family, wm_type, phases, init_run_name, init_iteration, fit_hz=5, uatemplate_rate=1e-4, smoothing=0, dummy_fallback=False, raw_signals=False, init_templates=False, **kwargs): """ Set u...
45add3585b61db404a9edb31fe7363677c6cbaec
6,327
def getLogisticModelNames(config): """ Get the names of the models present in the configobj Args: config: configobj object defining the model and its inputs. Returns: list: list of model names. """ names = [] lmodel_space = config for key, value in lmodel_space.items():...
f7f82b12eb50a58c92970b5c2a8f99eb01945523
6,328
def checkfileCopyright(filename): """ return true if file has already a Copyright in first X lines """ infile = open(filename, 'r') for x in xrange(6): x = x line = infile.readline() if "Copyright" in line or "copyright" in line: return True return False
567b485a58e46796238a109de935904d747679c7
6,329
def TopicFormat(topic_name, topic_project=''): """Formats a topic name as a fully qualified topic path. Args: topic_name: (string) Name of the topic to convert. topic_project: (string) Name of the project the given topic belongs to. If not given, then the project defaults to the currentl...
e8a3d28cc81b7a31a2243b68c77aef77449c1b97
6,330
def mp0(g0): """Return 0th order free energy.""" return g0.sum()
5aa3580fec1322bd7b4e357ec6bee4d52fae592e
6,331
def create_diamond(color=None): """ Creates a diamond. :param color: Diamond color :type color: list :return: OpenGL list """ # noinspection PyArgumentEqualDefault a = Point3(-1.0, -1.0, 0.0) # noinspection PyArgumentEqualDefault b = Point3(1.0, -1.0, 0.0) # noinspection PyA...
421939be392abdba6ccedb8a946a93ebe35fb612
6,332
import copy import collections def merge_dicts(*dicts): """ Recursive dict merge. Instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. """ assert len(dicts) > 1 dict_ = copy.deepcopy(dicts[0]) for merge_dict...
6595343694b80928417c2a1f096cf4587f3dccbc
6,333
def getAllFWImageIDs(fwInvDict): """ gets a list of all the firmware image IDs @param fwInvDict: the dictionary to search for FW image IDs @return: list containing string representation of the found image ids """ idList = [] for key in fwInvDict: if 'Version' in fwInv...
54bbd28b80905c7b48e5ddc3e61187f5b5ad5f6a
6,334
import os def create_dataset(dataset_path, batch_size=1, repeat_size=1, max_dataset_size=None, shuffle=True, num_parallel_workers=1, phase='train', data_dir='testA', use_S=False): """ create Mnist dataset for train or eval. dataset_path: Data path batch_size: The number of data records ...
b5dcb8cb507c2e2f928e0becbeb014ce7780ad7f
6,335
def document_uris_from_data(document_data, claimant): """ Return one or more document URI dicts for the given document data. Returns one document uri dict for each document equivalence claim in document_data. Each dict can be used to init a DocumentURI object directly:: document_uri = Doc...
70f02c61f8cb1be21dd094c696f257e565d7c04c
6,336
def get_bond_angle_index(edge_index): """ edge_index: (2, E) bond_angle_index: (3, *) """ def _add_item( node_i_indices, node_j_indices, node_k_indices, node_i_index, node_j_index, node_k_index): node_i_indices += [node_i_index, node_k_index] node_j_indices +=...
7660b6b27b2a028092d39cac5e1b9dfcf6973984
6,337
def get_config(section=None, option=None): """Return dpm configuration objects. :param section: the name of the section in the ini file, e.g. "index:ckan". - May be omitted only when no other parameters are provided - Must be omitted elsewhere :type section: str :param ...
e4910cd804593da8a6fd4b1fae7f3bd3fcd32f2b
6,338
def match_intervals(intervals_from, intervals_to, strict=True): """Match one set of time intervals to another. This can be useful for tasks such as mapping beat timings to segments. Each element ``[a, b]`` of ``intervals_from`` is matched to the element ``[c, d]`` of ``intervals_to`` which maximiz...
a3b523b5aafd77a2fc1026c183ae6a690ec3538c
6,339
def correlate(x, y, margin, method='pearson'): """ Find delay and correlation between x and each column o y Parameters ---------- x : `pandas.Series` Main signal y : `pandas.DataFrame` Secondary signals method : `str`, optional Correlation method. Defaults to `pearson`. ...
45800fd580ad257a8f4663c06577860f952a9a79
6,340
def sortList2(head: ListNode) -> ListNode: """down2up""" h, length, intv = head, 0, 1 while h: h, length = h.next, length + 1 res = ListNode(0) res.next = head # merge the list in different intv. while intv < length: pre, h = res, res.next while h: # get the two m...
02ffae2012847b952197f1ed4c2af2178a552b4d
6,341
def _inverse_frequency_max(searcher, fieldname, term): """ Inverse frequency smooth idf schema """ n = searcher.doc_frequency(fieldname, term) maxweight = searcher.term_info(fieldname, term).max_weight() return log(1 + (maxweight / n), 10) if n != 0.0 else 0.0
e24497c2d67600b9744c5fafb7b503853c54d76c
6,342
def ha(data): """ Hadamard Transform This function is very slow. Implement a Fast Walsh-Hadamard Transform with sequency/Walsh ordering (FWHT_w) for faster tranforms. See: http://en.wikipedia.org/wiki/Walsh_matrix http://en.wikipedia.org/wiki/Fast_Hadamard_transform """ # i...
e46eb465e67ffe61872cdb321cbb642fb8a1a094
6,343
from typing import Dict def most_repeated_character(string: str) -> str: """ Find the most repeated character in a string. :param string: :return: """ map: Dict[str, int] = {} for letter in string: if letter not in map: map[letter] = 1 else: map[let...
c59a1e0a552f12c7561ecdb11530f98f15076cdc
6,344
import json def read_config(config_filename): """Read the expected system configuration from the config file.""" config = None with open(config_filename, 'r') as config_file: config = json.loads(config_file.read()) config_checks = [] for config_check in config: if '_comment' in ...
31203f77cb5e507d431ced0311423c2aec546a27
6,345
def transitions(bits): """Count the number of transitions in a bit sequence. >>> assert transitions([0, 0]) == 0 >>> assert transitions([0, 1]) == 1 >>> assert transitions([1, 1]) == 0 >>> assert transitions([1, 0]) == 1 >>> assert transitions([0, 0, 0]) == 0 >>> assert transitions([0, 1, 0...
bc65f7b57508fc0c34275c4794d73c106bce07fd
6,346
def _convert_code(code): """ 将聚宽形式的代码转化为 xalpha 形式 :param code: :return: """ no, mk = code.split(".") if mk == "XSHG": return "SH" + no elif mk == "XSHE": return "SZ" + no
11ffcde407da7afaaf0eb28a80244d85f5136199
6,347
def _is_arg_name(s, index, node): """Search for the name of the argument. Right-to-left.""" if not node.arg: return False return s[index : index+len(node.arg)] == node.arg
b0c995ea553184f266fd968ad60b4c5fb19a55d4
6,348
import logging def fitNoise(Sm_bw, L, K, Gamma): """ Estimate noise parameters Parameters ---------- Sm_bw : float array Sufficient statistics from measurements Sm_fw : float array Wavefield explained by modeled waves Returns ------- BIC : float Value of the ...
49f9c368afc2634fa352da01ffebbe3549c52cd4
6,349
def run_command(cmd, debug=False): """ Execute the given command and return None. :param cmd: A `sh.Command` object to execute. :param debug: An optional bool to toggle debug output. :return: ``sh`` object """ if debug: print_debug('COMMAND', str(cmd)) return cmd()
605249fbe94e5f1449ed9fdba73e67d4a282a96f
6,350
def goodness(signal, freq_range=None, D=None): """Compute the goodness of pitch of a signal.""" if D is None: D = libtfr.dpss(len(signal), 1.5, 1)[0] signal = signal * D[0, :] if freq_range is None: freq_range = 256 if np.all(signal == 0): return 0 else: return np...
00a44a373f56cd07570a89cef9b688f0aae4dd39
6,351
import os def checkForRawFile(op, graph, frm, to): """ Confirm the source is a raw image. :param op: :param graph: :param frm: :param to: :return: @type op: Operation @type graph: ImageGraph @type frm: str @type to: str """ snode = graph.get_node(frm) e...
35f4a0484f68111f0f3fb003738583b8ed2994fa
6,352
import socket import fcntl import struct def get_ip_address(dev="eth0"): """Retrieves the IP address via SIOCGIFADDR - only tested on Linux.""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', dev[:15]))[20:24])...
96f59f17937543ed9cd4652af4703eaf975b8069
6,353
def connect(**kwargs): # pylint: disable=unused-argument """ mock get-a-connection """ return MockConn()
a51dd696411e5572344313a73b89d0431bcb5bdf
6,354
def new_organization(request): """Creates a new organization.""" if request.method == 'POST': new_organization_form = OrganizationForm(request.POST) if new_organization_form.is_valid(): new_organization = new_organization_form.save(commit=False) new_organization.owner = ...
2ef5e47a3d42ef3c2ce2dee055cb5311f984496d
6,355
def _build_obs_freq_mat(acc_rep_mat): """ build_obs_freq_mat(acc_rep_mat): Build the observed frequency matrix, from an accepted replacements matrix The acc_rep_mat matrix should be generated by the user. """ # Note: acc_rep_mat should already be a half_matrix!! total = float(sum(acc_rep_mat...
8a400ca64c3907ee8c09a5e33f9c45703f267d45
6,356
def strip(s): """strip(s) -> string Return a copy of the string s with leading and trailing whitespace removed. """ i, j = 0, len(s) while i < j and s[i] in whitespace: i = i+1 while i < j and s[j-1] in whitespace: j = j-1 return s[i:j]
7edc91baf8e57e713b464060c05f954510219d34
6,357
def set_news(title: str, text: str, db_user: User, lang: str, main_page: str) -> dict: """ Sets a new news into the news table :param title: of the news :param text: of the news :param db_user: author of the news :param lang: ui_locales :param main_page: url :return: """ LOG.deb...
49ab28d9ef8032f6d39505282920b3757163b609
6,358
import numpy def _test_theano_compiled_dtw(input_size, hidden_size, ndim, distance_function, normalize, enable_grads, debug_level, eps): """ Performs a test of a Theano DTW implementation. :param input_size: The size of the inputs. :param hidden_size: The size of the hid...
3de3d09027804510c0b9e639aeb640c0e2892e6b
6,359
def test(seriesList): """This is a test function""" return seriesList
70eb3f5a518533e6243bed74931d5829c9546e2b
6,360
def perform_timeseries_analysis_iterative(dataset_in, intermediate_product=None, no_data=-9999): """ Description: ----- Input: dataset_in (xarray.DataSet) - dataset with one variable to perform timeseries on Output: dataset_out (xarray.DataSet) - dataset containing variables: no...
63e3211db70a2ae12db7d1d26a5dad89f308816f
6,361
def getDayOfYear(date): # type: (Date) -> int """Extracts the day of the year from a date. The first day of the year is day 1. Args: date: The date to use. Returns: An integer that is representative of the extracted value. """ print(date) return _now().timetuple().tm_y...
25d7c150a4d7be2e6ae275b10b01e67517ba6cdb
6,362
def predict(network, X_test): """신경망에서 사용되는 가중치 행렬들과 테스트 데이터를 파라미터로 전달받아서, 테스트 데이터의 예측값(배열)을 리턴. 파라미터 X_test: 10,000개의 테스트 이미지들의 정보를 가지고 있는 배열 """ y_pred = [] for sample in X_test: # 테스트 세트의 각 이미지들에 대해서 반복 # 이미지를 신경망에 전파(통과)시켜서 어떤 숫자가 될 지 확률을 계산. sample_hat = forward(network, sa...
63ac50b7787c6dd89f04532b0a6266fa4d0f7012
6,363
def best_fit_decreasing(last_n_vm_cpu, hosts_cpu, hosts_ram, inactive_hosts_cpu, inactive_hosts_ram, vms_cpu, vms_ram): """The Best Fit Decreasing (BFD) heuristic for placing VMs on hosts. :param last_n_vm_cpu: The last n VM CPU usage values to average. :para...
8e5ab522078384ecef6eb7ef548fc537e411bfae
6,364
def __sanitize_close_input(x, y): """ Makes sure that both x and y are ht.DNDarrays. Provides copies of x and y distributed along the same split axis (if original split axes do not match). """ def sanitize_input_type(x, y): """ Verifies that x is either a scalar, or a ht.DNDarray. I...
7f3cfc44a47493fcf18c179556c388f9d9e9c643
6,365
import os def _is_buildbot_cmdline(cmdline): """Returns (bool): True if a process is a BuildBot process. We determine this by testing if it has the command pattern: [...] [.../]python [.../]twistd [...] Args: cmdline (list): The command line list. """ return any((os.path.basename(cmdline[i]) == 'pyt...
936d62d4129f1ae4da538d21f143317e4de9016d
6,366
def table_information_one(soup, div_id_name: str = None) -> dict: """ first method for bringing back table information as a dict. works on: parcelInfo SummaryPropertyValues SummarySubdivision """ table = [] for x in soup.find_all("div", {"id": div_id_name}): for div i...
3b317faff07bff028d43f20b7cfaa8afa587ca50
6,367
import functools def Eval_point_chan(state, chan, data): """External validity, along a channel, where point-data is a pulled back along the channel """ # for each element, state.sp.get(*a), of the codomain vals = [(chan >> state)(*a) ** data(*a) for a in data.sp.iter_all()] val = functools.red...
99355101853f3caa5c75b7e3f47aa5439a11aef1
6,368
import pyranges as pr def dfi2pyranges(dfi): """Convert dfi to pyranges Args: dfi: pd.DataFrame returned by `load_instances` """ dfi = dfi.copy() dfi['Chromosome'] = dfi['example_chrom'] dfi['Start'] = dfi['pattern_start_abs'] dfi['End'] = dfi['pattern_end_abs'] dfi['Name'] = df...
98ce4fbac93f81a6022d1cc012ca5270d7d681f3
6,369
def cleared_nickname(nick: str) -> str: """Perform nickname clearing on given nickname""" if nick.startswith(('+', '!')): nick = nick[1:] if nick.endswith('#'): nick = nick[:-1] if all(nick.rpartition('(')): nick = nick.rpartition('(')[0] return nick
f3a5c838f0518a929dfa8b65f83a1d4c6e6dbbe4
6,370
def validate_model_on_lfw( strategy, model, left_pairs, right_pairs, is_same_list, ) -> float: """Validates the given model on the Labeled Faces in the Wild dataset. ### Parameters model: The model to be tested. dataset: The Labeled Faces in the Wild dataset, loaded from loa...
ead4ed84c53b0114c86ecf928d44114b5d896373
6,371
import sys def get_allsongs(): """ Get all the songs in your media server """ conn = database_connect() if(conn is None): return None cur = conn.cursor() try: # Try executing the SQL and get from the database sql = """select s.song_id, s.song_title, st...
fbef7b34930be8f9e87cc5d9307996238b3e2d25
6,372
import asyncio def nlu_audio(settings, logger): """Wrapper for NLU audio""" speech_args = settings['speech'] loop = asyncio.get_event_loop() interpretations = {} with Recorder(loop=loop) as recorder: interpretations = loop.run_until_complete(understand_audio( loop, ...
4d9c5eeacc0c1c36cad4575cc774b3faded33c23
6,373
def _gauss(sigma, n_sigma=3): """Discrete, normalized Gaussian centered on zero. Used for filtering data. Args: sigma (float): standard deviation of Gaussian n_sigma (float): extend x in each direction by ext_x * sigma Returns: ndarray: discrete Gaussian curve """ x_range...
baea764c15c33d99f26bbe803844e06df97d908e
6,374
def create_tentacle_mask(points, height, width, buzzmobile_width, pixels_per_m): """Creates a mask of a tentacle by drawing the points as a line.""" tentacle_mask = np.zeros((height, width), np.uint8) for i in range(len(points) - 1): pt1 = points[i] pt2 = points[i+1] cv2.line(tentacl...
764251efff298f4b1990910d04c31ea9ed1760fd
6,375
def _matrix_to_real_tril_vec(matrix): """Parametrize a positive definite hermitian matrix using its Cholesky decomposition""" tril_matrix = la.cholesky(matrix, lower=True) diag_vector = tril_matrix[np.diag_indices(tril_matrix.shape[0])].astype(float) complex_tril_vector = tril_matrix[np.tril_indices(tri...
c59a0cd9fde6d77619a9681c3989efc9d704c07b
6,376
import os def is_subdir(path, directory): """Check if path is a sub of directory. Arguments: path (string): the path to check direcotry (string): the path to use as relative starting point. Returns: bool: True if path is a sub of directory or False otherwis...
6d947da6fada3b04f9b75728260b34ddfbbb3724
6,377
def max_pool(pool_size, strides, padding='SAME', name=None): """max pooling layer""" return tf.layers.MaxPooling2D(pool_size, strides, padding, name=name)
5259160d3f2955b16e039482e7c51cb2f6d777e9
6,378
def size_as_minimum_int_or_none(size): """ :return: int, max_size as max int or None. For example: - size = no value, will return: None - size = simple int value of 5, will return: 5 - size = timed interval(s), like "2@0 22 * * *:24@0 10 * * *", will return: 2 """ ...
742dc4f2d175a9372cc60e73dad21da9e927dc0c
6,379
import torch def args_to_numpy(args): """Converts all Torch tensors in a list to NumPy arrays Args: args (list): list containing QNode arguments, including Torch tensors Returns: list: returns the same list, with all Torch tensors converted to NumPy arrays """ res = [] for i...
fbf01c2ea236cc11f7b1d7a835b0a0ba338ba153
6,380
def optimizer_setup(model, params): """ creates optimizer, can have layer specific options """ if params.optimizer == 'adam': if params.freeze_backbone: optimizer = optimizer_handler.layer_specific_adam(model, params) else: optimizer = optimizer_handler.plain_adam...
c58427d7da66a02c2a44f92cb7d6350e2b9a83fd
6,381
def charToEmoji(char, spaceCounter=0): """ If you insert a space, make sure you have your own space counter and increment it. Space counter goes from 0 to 3. """ if char in emojitable.table: print(char) if char == ' ': emoji = emojitable.table[char][spaceCounter] ...
4943152d932f1529af86cdff827ff069f173fcb3
6,382
def averages_area(averages): """ Computes the area of the polygon formed by the hue bin averages. Parameters ---------- averages : array_like, (n, 2) Hue bin averages. Returns ------- float Area of the polygon. """ N = averages.shape[0] triangle_areas = np...
62ef194172095a9e7ddd6b9cb0cccb6d95fb2c4a
6,383
def _tree_cmp(fpath1: PathLike, fpath2: PathLike, tree_format: str = 'newick') -> bool: """Returns True if trees stored in `fpath1` and `fpath2` are equivalent, False otherwise. Args: fpath1: First tree file path. fpath2: Second tree file path. tree_format: Tree format, i.e. ``newick``,...
0c42386b94d9bf6c157b0d60593413074af772f4
6,384
from typing import Sequence def parse_genemark(input_f, genbank_fp): """ Extract atypical genes identified by GeneMark Parameters ---------- input_f: string file descriptor for GeneMark output gene list (*.lst) genbank_fp: string file path to genome in GenBank format Notes ...
3621d81eedad83f66a1be405bc49c2da3ea520d9
6,385
def get_hex(fh, nbytes=1): """ get nbyte bytes (1 by default) and display as hexidecimal """ hstr = "" for i in range(nbytes): b = "%02X " % ord(fh) hstr += b return hstr
b1d426f7bfcceffa829c9dcc1150f32be5c48413
6,386
def fetch(pages, per_page, graph): """ Get a list of posts from facebook """ return [x.replace('\n', '') for name in pages for x in fetch_page(name, per_page, graph)]
ea9af2e1d2fe9c2880aebd1148cb8f6457f55bb2
6,387
def lifted_struct_loss(labels, embeddings, margin=1.0): """Computes the lifted structured loss. Args: labels: 1-D tf.int32 `Tensor` with shape [batch_size] of multiclass integer labels. embeddings: 2-D float `Tensor` of embedding vectors. Embeddings should not be l2 normalized. ...
ac6de39c7b4fc204dbf46a716f796434da959134
6,388
def get_uint8_rgb(dicom_path): """ Reads dicom from path and returns rgb uint8 array where R: min-max normalized, G: CLAHE, B: histogram equalized. Image size remains original. """ dcm = _read_dicom_image(dicom_path) feats = _calc_image_features(dcm) return (feats*255).astype(np.uint8)
a81362af49a8c93c2e0224f033260ed3a0e5931f
6,389
import random import subprocess import time import socket def start(host, port, options, timeout=10): """Start an instance of mitmproxy server in a subprocess. Args: host: The host running mitmproxy. port: The port mitmproxy will listen on. Pass 0 for automatic selection. ...
5396f45d05e8c45a66ad0e658de3b22251883c06
6,390
def query_db_cluster(instanceid): """ Querying whether DB is Clustered or not """ try: db_instance = RDS.describe_db_instances( DBInstanceIdentifier=instanceid ) return db_instance['DBInstances'][0]['DBClusterIdentifier'] except KeyError: return False
6b84db4ff0b3788085ca4313aa397a6bd675e696
6,391
from typing import Callable from re import T def is_nsfw() -> Callable[[T], T]: """A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.ApplicationNSFWChannelRequired` that is derived from :exc:`.ApplicationCheckFailure`. .. versionchanged:: 2....
5941b74e55c43597f3c3e367434c3a0b54d92209
6,392
def calc_MAR(residuals, scalefactor=1.482602218): """Return median absolute residual (MAR) of input array. By default, the result is scaled to the normal distribution.""" return scalefactor * np.median(np.abs(residuals))
1691bf7883310562f4ee9e84d07c1fa188fe306b
6,393
def resourceimport_redirect(): """ Returns a redirection action to the main resource importing view, which is a list of files available for importing. Returns: The redirection action. """ return redirect(url_for('resourceimportfilesview.index'))
be5c6e7ef9fcc5c369d31a75960c2849cede2b5f
6,394
def valid_attribute(node, whitelist): """Check the attribute access validity. Returns True if the member access is valid, False otherwise.""" # TODO: Support more than gast.Name? if not isinstance(node.value, gast.Name): if isinstance(node.value, gast.Attribute): return valid_attribute(n...
1576a8e0e08b9f9387180a41137f1fffd786a4a5
6,395
def gen_fov_chan_names(num_fovs, num_chans, return_imgs=False, use_delimiter=False): """Generate fov and channel names Names have the format 'fov0', 'fov1', ..., 'fovN' for fovs and 'chan0', 'chan1', ..., 'chanM' for channels. Args: num_fovs (int): Number of fov names to create ...
417490259c42a52c58aab418fbb63185602e6750
6,396
def get_supported(): """ Returns a list of hints supported by the window manager. :return: A list of atoms in the _NET_SUPPORTED property. :rtype: util.PropertyCookie (ATOM[]/32) """ return util.PropertyCookie(util.get_property(root, '_NET_SUPPORTED'))
038e7d74cd6cdf2a0dc1d04a5e54b312a1a44b0e
6,397
def get_exportables(): """Get all exportables models except snapshot""" exportables = set(converters.get_exportables().values()) exportables.discard(all_models.Snapshot) return exportables
21dddb65f0193d02aae47d88a2743b9c92b3b245
6,398
import time def playback(driver, settings, record, output, mode=None): # pylint: disable=W0621,R0912 """ Playback a given test. """ if settings.desc: output("%s ... " % settings.desc, flush=True) else: output("Playing back %s ... " % settings.name, flush=True) _begin_browsing(...
36cd718760b76100a9959a1568b8c21f2ea7e334
6,399