content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def load(path, has_ids=True, has_header=True, has_labels=True, delimiter=","): """ Loads a data set from a delimited text file. Args: path: the path to the file containing the data set. has_ids: boolean set to False if the first column in the loaded dataset should not be ...
79f336359bcc7d87f5faecedb27dd314b33a2db9
3,599,763
import re def natural_key(some_string): """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', some_string)]
147d36719a899fbf07471af2fe9fd6b1a2440a27
3,599,764
def add_account_receive(account_receive_data): """ 添加信息 :param account_receive_data: :return: None/Value of user.id :except: """ return db_instance.add(AccountReceive, account_receive_data)
e029e00b0cc429e42e15be8badf2a5f69be70f2f
3,599,765
def handle_extends(tail, line_index): """Handles an extends line in a snippet.""" if tail: return 'extends', ([p.strip() for p in tail.split(',')],) else: return 'error', ("'extends' without file types", line_index)
3b20cc5719d123e36db954c5ffc4537df64f268a
3,599,768
def bin_phase_curve(phase, data, statistic="median", bins=20): """ Bin phase curve. """ bin_medians, bin_edges, _ = binned_statistic( phase, data, statistic=statistic, bins=bins ) bin_width = bin_edges[1] - bin_edges[0] bin_centers = bin_edges[1:] - bin_width / 2 return bin_cent...
7719fee2f5ab716e542a297e462424f660d865cc
3,599,769
def get_frames_from_sequence(event_list, num_events_per_frame, data_format, frame_gen_method, is_x_first, is_x_flipped, is_y_flipped, maxpool_subsampling, do_clip_three_sigma, chip_size, target_shape=None...
7ce5d741bc1374e953bf4423f4618562a73c0861
3,599,770
def pad(img: np.ndarray, target_height: int, target_width: int) -> np.ndarray: """Pads the image to have the target size for the network input.""" return np.pad(img, [(0, max(0, target_height-img.shape[0])), (0, max(0, target_width-img.shape[1]))], constant_values=0)
7cb9fd8c9d82b669b340162bfa231f481448acbd
3,599,771
def entryID(entry): """Try to make an unique ID for entry.""" id = None if entry.get('guidislink', None): id = entry.get('id', None) if id is None: id = entry.get('link', None) if id is None: raise Exception return id
f1ca161d60db7197e8b51f40585d74690a00c004
3,599,773
import torch def repackage_hidden(h): """Wraps hidden states in new Tensors, to detach them from their history.""" if isinstance(h, torch.Tensor): return h.detach() else: return tuple(repackage_hidden(v) for v in h)
b435d7537e4418d3877db55077285d35a24e46b3
3,599,774
def cityblock(u, v): """ d = cityblock(u, v) Computes the Manhattan distance between two n-vectors u and v, \sum {u_i-v_i}. """ u = np.asarray(u) v = np.asarray(v) return abs(u-v).sum()
07553804b20a0269b959ecccead4206fc372cdf2
3,599,776
def determineThresholdCrossing(latencies, baselineLatencies, alpha=0.001): """ Determines when the latencies cross the significance level designated by alpha. Confidence intervales of the baseline latency distribution are determined by applying the Dvoretzky-Kiefer-Wolfowitz inequality. Inputs: ...
18b5eacf5458fdf15bea7f92836afe02409e783a
3,599,777
def minus(evaluator, ast, state): """Evaluates "-expr".""" return -evaluator.eval_ast(ast["expr"], state)
bf945c368e84d3badd7a90bfce74cb3c89b6890a
3,599,778
from typing import List def _validate(vector: np.ndarray, sizes: List[int], name: str): """Validate vector has one of the expected sizes.""" sizes = [sizes] if type(sizes) == int else sizes if vector.shape[0] in sizes: return np.copy(vector) else: sizes_str = ', '.join(["(%d,1), (%d)" ...
c1cb8be31076291b2fe5ef134e34230dffccd6ac
3,599,779
import torch def query_ball_point(radius, nsample, xyz, new_xyz, itself_indices=None): """ Grouping layer in PointNet++. Inputs: radius: local region radius nsample: max sample number in local region xyz: all points, (B, N, C) new_xyz: query points, (B, S, C) itself_in...
c304988065bd71a458f6b62fd322a75319b97a87
3,599,780
def angle_M(M_r: float, n: float, t_r: float, t: float) -> float: """ M = Mr + n * (t - tr) :param M_r: mean anomaly at tr :type M_r: float :param n: mean movement :type n: float :param t_r: reference time :type t_r: float :param t: time :type t: float :return: mean anomaly ...
c99e5dacffea44fa7fadfaebaf6ce734eea81e16
3,599,781
from typing import Union from typing import Dict import torch def convert_double_to_float(data: Union[Dict, torch.Tensor]): """ Utility function to convert double tensors to float tensors in nested dictionary with Tensors """ if type(data) is torch.Tensor and data.dtype == torch.float64: retur...
737edbb9625b6cc1dbce425f7e8df8e06cb80410
3,599,782
import re def is_transaction_expired_exception(e): """ Checks if exception occurred for an expired transaction :type e: :py:class:`botocore.exceptions.ClientError` :param e: The ClientError caught. :rtype: bool :return: True if the exception denote that a transaction has expired. False other...
c836521a7137b61ad8443157824ca5da59de65e3
3,599,783
def otsu_triangles(img, KERNEL_SIZE = 5): """ Transforms the image using otsu binarizarion method, similar to the "otsu" function on this module. The only difference, however, is that this version draws a small triangle (5 percent of img's width) on each of the four corners, and applies floodFill to all of ...
ee57256a1a8574340c0a4e316618c796a74e97d7
3,599,784
def adjust_ws_gs_comp(ws, bms, gs): """Adjusts the compatibility of widths and groups.""" ws_bot = [int(w * b) for w, b in zip(ws, bms)] gs = [min(g, w_bot) for g, w_bot in zip(gs, ws_bot)] ws_bot = [quantize_float(w_bot, g) for w_bot, g in zip(ws_bot, gs)] ws = [int(w_bot / b) for w_bot, b in zip(ws_bot, bms...
2790fb708162b369d9c016c0f2acbbc90a4f7d91
3,599,785
def convert_base64_exams_to_PIL(exams: list[str]): """ Convers a list of base64 images or pdfs into PIL Image objects """ exames_pil = [] for exam in exams: if get_base64_datatype(exam) == "pdf": exam = convert_base64_pdf_to_base_64_img(exam) exames_pil.append(base_64_to...
fbf52936ab8be90a7fa01da38eb3e54401d3c367
3,599,786
def get_reverb_send(header: bytes) -> int: """Return reverb send value (0-100).""" assert isinstance(value := _unpack(header, "REVERB_SEND"), int), type(value) assert 0 <= value <= 100, value return value
733634443f8b9c7c8ae575bd5523b2af1cdee153
3,599,787
def stations_within_radius(stations, centre, r): """Function to return a list of all stations (type MonitoringStation) within radius r of geographic coordinate x""" stationlist = [] for i in stations: # Find distance from centre to station, if it is < r, add to list dist = haversine(i.coord ...
320a8d6a240023af9d2dae30a7ecde4dc2e54c84
3,599,788
from typing import List from typing import Literal from typing import Tuple def parity_network(n: int, S: List[List[Literal[0,1]]]) -> List[CNOT]: """Implements the parity network algorithm of https://arxiv.org/pdf/1712.01859.pdf. Specifically, it follows the pseudo-code of page 14.""" c = [] # List of cn...
78b0e0197b0fccd14173c3f7162cb2021747eeb6
3,599,789
def _convert_room_label(room_name): """ Convert room label from str to index, using the mapping defined by FloorNet""" room_name = room_name.split('-')[0] original_room_label_map = getRoomLabelMap() room_name = room_name.replace(' ', '_').lower() try: room_label = original_room_label_map[ro...
2ad86678e40465520bfc25d0b592c50704075a3b
3,599,790
import re def get_all_local_funcs(vba): """Get the names of all locally defined functions. Also get the names of all defined constants. The constant names are saved in core.strip_lines.defined_constants. @params vba (VBA_Parser object) The olevba VBA_Parser object for reading the Office file bein...
600b0f1860b9026ec9179cd8586add231dea21f0
3,599,791
def get_legal_moves_lshift(size, mask, player, blank, shift_size): """ 左シフトで石が置ける場所を取得 """ tmp = mask & (player << shift_size) for _ in range(size-3): tmp |= mask & (tmp << shift_size) return blank & (tmp << shift_size)
42a259f21b2ae1c0c57007f939e5e7e935761b88
3,599,793
def _make_stacked_ensemble_pipeline(input_pipelines, problem_type, n_jobs=-1, random_seed=0): """ Creates a pipeline with a stacked ensemble estimator. Arguments: input_pipelines (list(PipelineBase or subclass obj)): List of pipeline instances to use as the base estimators for the stacked ensemble....
58fc0fbcd39a0896ae3a4721ce841b8ea2ad22ee
3,599,794
def TokenEndBlockquote(depth=1): """ `TokenEndBlockquote` is used to denote that we are ending a blockquote. This token will not render anything. """ return { "type": "SpaceCharacters", "data": "", "_md_type": mdTokenTypes["TokenEndBlockquote"], "_md_depth": depth, ...
e19142a780aa44f951980ce184dae068f6949629
3,599,795
import warnings def _compute_angles_list(view_index_list, num_acquired_scans, total_angles, rotation_direction="positive"): """Return angles list from indexes list. Args: view_index_list (list[int]): Final index list after subsampling and time point selection. num_acquired_scans (int): Total ...
2c942044072a455b21b7d95ffc1f6b73f6331eb4
3,599,796
def discriminator_patch(input_image, leaky_relu_alpha: float = 0.2, reuse: bool = None, scope: str = None, dim: int = 64, ks: int = 4): """ Discriminator (Patch GAN) Input 256 x 256 x 3 image...
7ef1869f7404a2164660256cd7ac7d76ae8c9df9
3,599,799
def _get_user_and_accounts(access_token, cache_date): """ We cache API calls for the Coinbase `User` object and account data, refreshing it once per day. We pass in `cache_date` which has the current date, forcing an API call if the date changes (and eventually evicting expired dates). """ c...
98da0f4e3c9d9e9f30393a6badb3b00d3c05ea32
3,599,801
def parse_int(sin): """A version of int but fail-safe""" return int(sin) if sin.isdigit() else -99
204cbcb01b6df1bbdd09af318fdfe90feb5fe68f
3,599,802
def dirac_recon_joint_alg_fast(G, measurement, num_dirac, shape_b, flatten_order='F', noise_level=0, max_ini=100, stop_cri='mse', max_inner_iter=20, max_num_same_x=1, max_num_same_y=1): """ ...
5d17e31330c4ed52b194ff0649b7b9fd67abecdd
3,599,803
def get_enrollments(case_trigger_info, case_config): """ DHIS2 allows tracked entity instances to be enrolled in programs without any events, but CommCare does not currently have a mechanism for that. Cases/TEIs are enrolled in a program when the first event in that program occurs. """ case_...
0af71a5655d4598d457479a1d4150f533c3dd23b
3,599,804
def test_set_montage_mgh(rename): """Test setting 'mgh60' montage to old fif.""" raw = read_raw_fif(fif_fname) eeg_picks = pick_types(raw.info, meg=False, eeg=True, exclude=()) assert list(eeg_picks) == [ii for ii, name in enumerate(raw.ch_names) if name.startswith('EEG')]...
77cb783dfc1f8eb9967156545417818621571345
3,599,805
def translate_mixmm(mix_mm, session): """ Translate mixmm into phenotype and into percentages and return as list """ mix_keys = list(mix_mm.keys()) df = pd.DataFrame(columns=["serotype", "mm"], dtype=object) for hit in mix_keys: pheno = list(get_pheno_list([hit], session))[0] df...
08cc6a8e9e1470a2643d9944effadba09680f28e
3,599,806
def check_read(read): """ a callback function for pysam.count function, returns true if the read should be included in the count :param read: the read to check :return: True of False whether the read should be included in the count """ return read.is_proper_pair
1bc80c9156bdeb0bc34b2724da8d0147a435b3dd
3,599,807
def glVertex( *args ): """Choose glVertexX based on number of args""" if len(args) == 1: # v form... args = args[0] return glVertexDispatch[ len(args) ]( *args )
b0e0e8a2c232fd36b77a8d5f21056009b353a2bc
3,599,808
def _iter_child_nodes_in_order(node): """ Yield all direct child nodes of C{node}, that is, all fields that are nodes and all items of fields that are lists of nodes. C{_iter_child_nodes_in_order} yields nodes in the same order that they appear in the source. C{ast.iter_child_nodes} does the s...
54ba42f5bae971572a343121d8b3bef5a480a2d6
3,599,809
def build_scheduler(optimizer, total_iters_each_epoch, total_epochs, last_epoch, optim_cfg): """ 构建学习率调度器:三种方式adam_onecycle、LambdaLR、CosineWarmupLR Args: optimizer:优化器 total_iters_each_epoch:一个epoch的迭代次数:982 total_epoch:总共的epoch数:80 last_epoch:上一次的epoch_id optim_cfg:优...
fd86986dec0585390585868ec5eb11970cee975a
3,599,810
import re def replace_src(html_body, base=''): """ 替换图片文件链接(替换本地链接) :param html_body: :param base: :return: """ rule = r'src="(.*?)"' img_data_src_list = re.compile(rule, re.I).findall(html_body) for img_src in img_data_src_list: # 处理//,补充协议 if img_src.startswith('/...
8e60ed496b25f713847fd3df5e7a3f0452bced19
3,599,811
def createAggregatedTestCase(doc, parent_node, testclass_name): """ Create a node which represents a single aggregated testcase. Aggregated testcase sums the result of all test cases that belong to the speified classname. If one of these test cases fails, the aggregated test case's status is set to ...
a6cfaa405464a09e76d3e4840f99a3d5ff9a87b1
3,599,812
def process_in_parallel(process_count=5, tasks=[]): """ General-purpose function for programming :param process_count: The number of processes used for the given task :return: """ outputs = mp.Queue() def parallel_process_decorator(process_fn): """ :p...
9b0b0c7c04232b15e6aa151fd0473f6f564b19f6
3,599,813
import ray def _internal_kv_put(key, value, overwrite=False): """Globally associates a value with a given binary key. This only has an effect if the key does not already have a value. Returns: already_exists (bool): whether the value already exists. """ worker = ray.worker.global_worker...
11cf7586e1fc4f5956111f3391db64d987c83de5
3,599,814
import copy def beautiful_nx(g): """A wrapper to draw graph nets beautifully. Args: g: a networkx graph object. Source: https://gist.github.com/jg-you/144a35013acba010054a2cc4a93b07c7.js """ pos = nx.layout.spectral_layout(g) pos = nx.spring_layout(g, pos=pos, iterations=50...
08997d759c786556dd90c6b2b72b8b51ddc8161f
3,599,815
def next_generation(data, current, colors): """ Create the next generation from the previous one Args: data (np.array): the matrix representing the input current (list): the current generation Returns: list: The generation of results with their respective quality and fea...
ca2fb70f56721993bea1785efabfa139726355d3
3,599,816
import urllib import json import requests def lambda_handler(event, context): """ Google Chat Webhook にエラーイベント情報を送信する Parameters ---------- event : json トリガーイベント情報 context : json 実行環境情報 Returns ---------- response : json POSTリクエスト実行結果 """ try: ...
21a5170c7b789b5f4c06f5b8ad5c346ad41345f0
3,599,817
def _datastore_lookup(keys, read_options, retries=None, timeout=None): """Issue a Lookup call to Datastore using gRPC. Args: keys (Iterable[entity_pb2.Key]): The entity keys to look up. read_options (Union[datastore_pb2.ReadOptions, NoneType]): Options for the request. ...
92e457366a7aeebdf26346383631efd8c68fd55c
3,599,818
def expr_analysis(filename,filename2,altmerge_constituitive,exon_db,analyze_dabg): """import list of expression values for arrayids and calculates statistics""" constitutive_keep={}; keep_probesets={}; keep_genes={} global expression_status_db; global pvalue_status_db; global export_db expression_statu...
38ea159d3f96cf4114daec4072bf6281939c279d
3,599,819
def _lcs_iter_simple_alt1(full_seq1, full_seq2, open_to_close, node_affinity, open_to_tok): """ Depth first stack trajectory """ all_decomp1 = generate_all_decompositions(full_seq1, open_to_close, open_to_tok) all_decomp2 = generate_all_decompositions(full_seq2, open_to_close, open_to_tok) args...
cffd68451c3878ec4a5a00001a108800c254f03a
3,599,820
def saferep(x, n): """ Repeat `x` to array of length `n` if it's a literal, or check that `len(x) == n` if it's iterable. """ try: if len(x) == 1: raise TypeError assert len(x) == n, f'`len({x})` != {n}' return x except TypeError: return np.repeat(x, n)
cc4556147c002b98b7ab1a5edbb425e60cfdc4a5
3,599,821
def makeToUnicodeCMap(fontname, subset): """Creates a ToUnicode CMap for a given subset. See Adobe _PDF_Reference (ISBN 0-201-75839-3) for more information.""" cmap = [ "/CIDInit /ProcSet findresource begin", "12 dict begin", "begincmap", "/CIDSystemInfo", "<< /Regis...
dbcb57eddcaa63373da63a90cd937f6d9e4cb835
3,599,822
import warnings def distance_cn_correlation(sr_a: pd.Series, sr_b: pd.Series) -> float: """Metric that uses non-linear correlation distance to obtain a correlation coefficient for categorical-numerical column pairs. Args: sr_a (pd.Series): The categorical series to analyze, used for g...
b3f414e81b9f35e0f6d9de4a09387dd141e09ad4
3,599,823
def breadcrumb_bar(context): """ Breadcrumbs and language switcher displayed below proposition header - creates alternate language links if SHOW_LANGUAGE_SWITCH is set - takes "breadcrumbs" from the context - takes "breadcrumbs_back" from the context to show a back link *instead* of breadcrumbs ...
81b2f72bdab92a46803f6c8ebeca1303eb317fde
3,599,824
import pandas def ReadData(): """Reads data about cannabis transactions. http://zmjones.com/static/data/mj-clean.csv returns: DataFrame """ transactions = pandas.read_csv('mj-clean.csv', parse_dates=[5]) return transactions
2652635ae2ed765bc9465706866c017ea171383f
3,599,826
def rsa_encrypt(key): """ 加密 :return: """ public_key = RSA.import_key(open('pubkey.pem', 'r').read()) # data = data.encode() cipher = PKCS1_OAEP.new(public_key) key = cipher.encrypt(key) print("加密后的key", key) # print(binascii.b2a_hex(msg)) return key
570342f41fec5428fa8b811d9240937ad760d5a4
3,599,827
def rsquared(evaluation,simulation): """ Coefficient of Determination .. math:: r^2=(\\frac{\\sum ^n _{i=1}(e_i - \\bar{e})(s_i - \\bar{s})}{\\sqrt{\\sum ^n _{i=1}(e_i - \\bar{e})^2} \\sqrt{\\sum ^n _{i=1}(s_i - \\bar{s})^2}})^2 :evaluation: Observed data to compared with...
b72829ef2f333faf4f01ee0cdffeb237761f50b9
3,599,829
def decrypt(private_key, ciphertext): """Decrypt a message with a given private key. Takes in a private_key generated by Crypto.PublicKey.RSA, which must be of size exactly 4096 If the ciphertext is invalid, return None """ if len(ciphertext) < 512 + 16: return None msg_header = ciphertext[:512] m...
0414eff85830427752299723ce415d6459ddd9d9
3,599,830
def decimal_to_binary(num): """Exercise: 1.3.5. The code given in the exercise is the logic to print binary representation of the decimal number """ stack = Stack() while num > 0: stack.push(num % 2) num = num // 2 binary = "" while not stack.is_empty(): binary ...
5a552968fe054560dc034169f3e069ea60821d43
3,599,831
def pack(data, nbit): """downgrade data from 8bits to nbits (per value)""" data = data.flatten() if 8 % nbit != 0: raise ValueError("unpack: nbit must divide into 8") if data.dtype not in (np.uint8, np.int8): raise TypeError("unpack: dtype must be 8-bit") outdata = np.zeros(data.size...
800e111e68eb5c72f35effb32ae50ba6db2cc3e3
3,599,832
def level_dir(name, level): """The directory containing the results of one level of the search.""" return storage.join(experiment_dir(name), 'level%d' % level)
19162a133b0f57dabb1786355cb9c2ca14cedc16
3,599,833
def create_dict(**kwargs): """Create a dict only with values that exists so we avoid send keys with None values """ return {k: v for k, v in kwargs.items() if v}
0abd94a4ec3a84685635affbe038d9b513287f6e
3,599,834
def _read_from_socket(conn, length): """Read a chunk of data from a connection""" chunks = [] remaining = length while remaining > 0: # Read a maximum of READ_MAX_CHUNK each iteration chunk = remaining if chunk > READ_MAX_CHUNK: chunk = READ_MAX_CHUNK # In Py...
37324c4ec88bf88797936bf4f4cdd2d08af914cf
3,599,835
def nb_distance_vec(indices, seqs_mat, seqs_L, nb_metric, *args): """Compute distances between pairs of sequences in seqs_mat specified by indices. Note: numba raised errors when this function tried to use *args inside the prange function. Without *args the prange function appears to fully parallelize the ...
46fdfea41f7e18f464bdb6f85e10177b4e1a5dbc
3,599,836
def hospitalized_case(I, AGE_DATA): """ Calculated hospitalization cases""" AGE_DATA['Snapshot_hospitalized'] = round(AGE_DATA['Proportion_DE_2020'] * I * AGE_DATA['Hospitalization Rate']) no_h = AGE_DATA['Sna...
9876bd1e6420b0e12db3ef4300d25fb84931b759
3,599,837
def aic(model, X_train, y_train): """ Compute the Akaike Information Criterion (AIC) AIC's objective is to prevent model overfitting by adding a penalty term which penalizes more complex models. Its formal definition is: .. math:: -2ln(L) + 2k where :math:`L` is the maximized value of...
8f1789bca6ca8d48af5cb6d6760ce1ddefbbb59a
3,599,838
def DeclareSort(name, ctx=None): """Create a new uninterpreted sort named `name`. If `ctx=None`, then the new sort is declared in the global SMT context. >>> A = DeclareSort('A') >>> a = Const('a', A) >>> b = Const('b', A) >>> a.sort() == A True >>> b.sort() == A True >>> a == ...
e7ade3a622bfef04fd3453c6678d52c3b23801a4
3,599,839
import select def get_key_events( bio_events: bool = False, stressors: bool = False, detailed: bool = False, species: int = None, verbose: bool = False, ) -> pd.DataFrame: """Get table of key events. Parameters ---------- bio_events : bool If True, produces a detailed Data...
1434476c020182743ef4620fa0a7a64c4d8e152f
3,599,840
def RegionateFITS(fitsFile,minLodPixels,maxPer,rootKml,outputDir,surveyName, iconURL,orderbyField='',hdu=1,maxLodPixels=-1,outputUrl=''): """ Regionate a FITS file into kml """ if not os.access(outputDir, os.W_OK): if verbose: print '%s: must exist and must be writeable' % outputDir...
27a54ffe138e27e864a6f7f703ea525263f59998
3,599,841
def raster(event_times_list): """ event_times_list : iterable a list of event time iterables color : string color of vlines Returns ------- ax : an axis containing the raster plot """ color='k' ax = plt.gca() for ith, trial in enumerate(event_times_list): plt...
1c4dd8a21c60227297c0827095d0629911969fe3
3,599,843
def segmented_intersections(lines): """Finds the intersections between groups of lines.""" intersections = [] for i, group in enumerate(lines[:-1]): for next_group in lines[i+1:]: for line1 in group: for line2 in next_group: intersections.append(inter...
677014c1f1ee99e6100f6b91d63018afac11cd6e
3,599,844
def index(request): """ handle top level pages. """ page_name = request.path[1:][:-1] view_objects = {} if page_name != "home" and not challenge_mgr.is_page_unlock(request.user, page_name): return HttpResponseForbidden('<h1>Permission denied</h1>') # get the view_objects is_pa...
ac1ef9b1e36a6fe0759780de38aa238bbe154f82
3,599,845
def pie_chart(df, col, colors=None, title=None): """Create Pie Chart""" df_p = pd.DataFrame(df.groupby(col)[col].agg("count") / len(df)) if title == None: title = col fig = go.Figure() fig.add_trace(go.Pie(labels=df_p.index, values=df_p.iloc[:,0])) if colors == None: fig.update_t...
ab168ce3e691eb3d7ffb12ee204c04e6d0a55cc5
3,599,846
def remove_deulicated_resource(resource_list): """ 移除所有具有重复 url 的资源,并返回移除重复项之后的资源列表 """ url_added = set() unduplicated_resources = [] for resource in resource_list: if resource[KEY_URL] not in url_added: url_added.add(resource[KEY_URL]) unduplicated_resources.appe...
9b8f9960f7c030898a3633d9bc3f0576dbf07957
3,599,847
def Lagrangian(frame, *body): """Lagrangian of a multibody system. This function returns the Lagrangian of a system of Particle's and/or RigidBody's. The Lagrangian of such a system is equal to the difference between the kinetic energies and potential energies of its constituents. If T and V are th...
836fe525896e44c420f4864084f1fb2d3cdaa84b
3,599,848
import unicodedata def unicode_to_ascii(s): """Convert unicode to ASCII.""" return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' )
eb53883802155bfa237d7aa85b025c1205decd71
3,599,849
def set_kernel(k, normalizer=no_norm): """ Decorator that makes a normalized set kernel out of a standard kernel k """ def K(X, Y): if type(X) == list: def norm(x): return normalizer(x, k) x_norm = matrix([elem for elem in map(norm, X)]) if id(X) == id(Y)...
5745803f0e96ccda8316a3c0bba7d0778f8e6964
3,599,850
def w3(): """Provide a Web3 client to interact with a local chain.""" client = Web3(HTTPProvider('http://localhost:8545')) client.eth.defaultAccount = client.eth.accounts[0] return client
9842a2250524fbebbcad4237d83ecf6352208a89
3,599,851
def run_async(*args) -> Popen: """https://stackoverflow.com/questions/16071866/non-blocking-subprocess-call p = run_async("command") while p.poll() is None: ... p.stdout p.stderr """ command = ' '.join(args) return Popen(command, shell=True, stdout=PIPE)
e2ff67b0d4b0ab63740fb5bacf8210ca25e7b101
3,599,853
def get_ospf_process_id_and_area( device, vrf="default", interface=None, address_family="ipv4" ): """ Get ospf process id and area Args: device ('obj'): device to run on vrf ('str'): vrf to search under interface ('str') interface to serach under address_...
01926c47e70536a88ce5351e9e1dcb677bb0192c
3,599,854
def GetInternalIPAddress(instance_resource): """Returns the internal IP address of the instance. Args: instance_resource: An instance resource object. Raises: ToolException: If instance has no network interfaces. Returns: A string IP address. """ return GetInternalInterface(instance_resource)...
94c2b2bdf45c4acf207c2e29025c2f4a9ce91515
3,599,855
def load_and_numberize_data(path="../data/", nb_words=None, maxlen=None, seed=113, start_char=1, oov_char=2, index_from=3, init_type="random", embfile=None, dev_train_merge=0, map_labels_to_five_class=0): """ numberize the train, dev and test files """ # read the vocab from the entire corpus (train + test + d...
42779e14c824d96664ab4388f5b56131acab7103
3,599,856
def enable_cdc(client): """Utility method to enable Change Data Capture for Contact change events in an org. Args: client (:py:class:`simple_salesforce.Salesforce`): Salesforce client Returns: (:obj:`str`) Event channel Id """ payload = { "FullName": "ChangeEvents_ContactCh...
2c7bc57f33e83029caea542db9daeaa81f6661cc
3,599,857
from typing import OrderedDict def minimal_project_conf_path(tmpdir): """ Write minimal sample annotations and project configuration. """ anns_file = tmpdir.join(ANNOTATIONS_FILENAME).strpath df = pd.DataFrame(OrderedDict([ (SAMPLE_NAME_COLNAME, SAMPLE_NAMES), ("data", DATA_VALUES)])) with ope...
a2d0c5c17b1afb0187811b3cd1bf7aa7c5eb1791
3,599,858
def delete_album(request, album_id): """ Delete an album from the store """ if not request.user.is_superuser: messages.error(request, 'Sorry, only store owners can do that.') return redirect(reverse('home')) album = get_object_or_404(Album, pk=album_id) album.delete() messages.succe...
0bbc5e0c519c327c586ab094ffd8221ba5860ed5
3,599,859
import math def model_SouthKorea(): """ This is a model for South Korea. Due to how much testing they do, it is probably more accurate to try match observations to E instead of I. """ m = 4 # The parameter within the distribution of E n = 7 # The parameter within the distribution of I ...
fda57f911c436800a6e419d6508bc76823e2de20
3,599,860
def _bytes_feature(value): """Returns a bytes_list from a string / bytes.""" if isinstance(value, type(tf.constant(0))): # if value ist tensor value = value.numpy() # get value of tensor return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
1f805b217ee212411da474010043ce881fb75510
3,599,861
def http_destination_exists(site, path): """ """ conn = httplib.HTTPConnection(site) conn.request('HEAD', path) response = conn.getresponse() conn.close() return response.status == 200
a259891360588e6929c8a71a34d6dc7717fe573c
3,599,862
def mobile_start(): """Mobile start page""" listings = Listing.query.order_by(Listing.created.desc()) listings = filter_rejected(listings) listing = listings.order_by(UserListingInfo.score.desc()).first() return redirect(url_for("mobile", identifier=listing.id))
17e368f6cf3baacd9cdfd00d70d46ae30dce414e
3,599,863
def crc_update(crc, a): """ For a character calculate crc """ crc ^= ord(a) for i in range(8): if crc & 1: crc = (crc >> 1) ^ 0xA001 else: crc = crc >> 1 return crc
b3cdf352aaa282c54c0c5f82401b52f5d95dc327
3,599,864
def extract_first_appearance(string, type_, last_possible): """Extract the first appearance of the character in manga or anime Note: the complete list of manga_chapters and anime_episodes seems incorrect on Hokuto Renkitōza. Parameters ---------- string : str entire appearances string ...
baee950b7f3f0cbba2f3dee2e136f7d63b737489
3,599,865
def sitemap_read() -> list: """Load page information from sitemap file. Returns: A list of modules to include in site """ try: with SITEMAP.open() as fp: sitemap = [line.strip() for line in fp if not line.startswith("#")] except FileNotFoundError: sitemap = [] ...
2fcc227f4382e488e1efbb86b1abe3062ded4b15
3,599,866
def get(key: str, dic, default=None): """Gets key even from not a dictionary.""" try: return dict(dic).get(key, default) except TypeError: return default
5302868de0b6b4a94bded35654d6a9ad215d867e
3,599,869
def build_hourglass_mask_branch(rois, feature_maps, use_p2, image_meta, mask_channel, double, pool_size, num_keypoint, train_bn=True, name=''): """ 直接上来就降采样,所以之前要先卷积两次输出也是同样,输出之后还是要卷积融合一下特征。 :param layer: 降采样的次数,直接决定了fm大小和感受野 :param numOut: channel :return: 输出当前的fm和之前...
59206fc62ec2ff17161351edbd3e580af3309556
3,599,870
def href(obj): """Lets the URL to an object be constructed with {{ obj|link }}. This encapsulates our URL-building logic in one single place, in contrast to the usual Django practice of littering every template with {% url %} calls that have to all be hand-edited in the future when a view name chan...
90b2d2ee2c27e3359218d4899e2a15e816970dd0
3,599,872
def get_environment_var(varstr): """Given a string, first determine if it looks like a reference to a single environment variable, like "$FOO" or "${FOO}". If so, return that variable with no decorations ("FOO"). If not, return None.""" mo=_get_env_var.match(to_String(varstr)) if mo: var...
1b4e5fc91ac0eda4a7a3657a46e669326a9dda53
3,599,874
import yaml def load_config_from_yaml(filename='fsm.yaml'): """ Returns the current fsm configuration dictionary, loaded from file. :return: a dict. """ yaml_file = open(filename, 'r') yaml_dict = yaml.safe_load(yaml_file.read()) return yaml_dict
e1ff03a8fcc2a77288d8971cd76fd17e7a30f65a
3,599,876
import torch def atanh(x, eps=1e-2): """ The inverse hyperbolic tangent function, missing in pytorch. :param x: a tensor or a Variable :param eps: used to enhance numeric stability :return: :math:`\\tanh^{-1}{x}`, of the same type as ``x`` """ x = x * (1 - eps) return 0.5 * torch.log(...
27b0e8de0eeceb44d739f686ca22d616bc8f75de
3,599,878
def correct_peaks( sig, peak_inds, search_radius, smooth_window_size, peak_dir="compare" ): """ Adjust a set of detected peaks to coincide with local signal maxima. Parameters ---------- sig : ndarray The 1d signal array. peak_inds : np array Array of the original peak indice...
08f24c806f2ea64a044968196bd8fb0b1833ed0f
3,599,879
import itertools def lower_star_for_image(img_array): """ Compute the lower star weighted simplicial complex from a 2d grid/image. Parameters ---------- img_array, a `numpy.ndarray` of dimension 2. Returns ------- `homology.SimplicialComplex` Examples -------- >>> A = n...
b0d4e6bdad90c15d0e33e0edff61ca83d4015f2c
3,599,881