content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import glob import tokenize import os def open_files(path): """ Open many files. Return delayed objects. See Also -------- dask.bytes.core.open_files: User function """ myopen = delayed(open) filenames = sorted(glob(path)) return [myopen(fn, mode='rb', dask_key_name='open-%s' % ...
c3bbf7c4a10ff73c36de3e6c4596a599950b3542
3,599,800
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 os def create_dummy_data(): """Create small cardiac data based on patches for demo. Note that in practice, at test time the method will need to be applied to the whole volume. In addition, one would need more data to prevent overfitting. """ data = loadmat(os.path.join(project_root, './...
e8acaf4968971c687c2543b939eccfc3436f49c4
3,599,825
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
from typing import List import subprocess def run_command(cmd: List[str]) -> str: """Execute a command in the shell. Args: cmd: :obj:`List[str]`. The command with its arguments to execute. Returns: The standard output of the command. Raises: :obj:`OSError`: if the standard e...
5e4025b232c87e52608ea394c782bae0039d15d5
3,599,828
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
import time import logging from datetime import datetime def send_command(device, cmd, status_validation=False, response_validation=False, repeat_cnt=1, wait_after_command=1.5): """ Send command to device, wait for answer and return response. Return dictionary with response and other information (should be object)...
feffbc82620c22c8016a89619f433705ae8e59bd
3,599,842
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 __get_haproxy_socket_mapping(args): """ Get a mapping of configured sockets and certificate directories. From: haproxy config, stapled config and command line arguments. :param Namespace args: Argparser argument list. :return dict Of cert-paths and sockets for inform of changes. """ # ...
1a54374e8f1febda32ddd531568a800bf775e023
3,599,852
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
import pwd import os def get_owner(path): """Get the object owner.""" if IS_WINDOWS: return win32security.LookupAccountSid(None, win_get_owner_sid(path)) return pwd.getpwuid(os.stat(path).st_uid).pw_name
a3615f67c9f7014c80734b64a144283f627b731a
3,599,867
import os def relative_path_to_image(outfile, image): """Convert image file path relative to the html file (Wrapper). """ opath = os.path.normpath(outfile) if type(image) == list: image = [trim_path_to_image(opath, im) for im in image] else: image = trim_path_to_image(opath, image)...
87b94f25de3abc50da430312244dca05b550f5c6
3,599,868
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
import logging import os def main(dl_event=None, api_client: deep_lynx.ApiClient = None, container_id: str = '', data_source_id: str = ''): """ Main entry point for script Args api_client (ApiClient): deep lynx api client container_id (str): deep lynx container id data_source_id (s...
9e8c56f2ce3bbbd5fdddef6882aadc3207da7c91
3,599,871
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 select_best_from_tree(tree, best_per_taxid_df): """Select the best genome from a TreeNode instance""" genome_id = np.nan # Edge case for species-level tree if tree.is_leaf(): taxids = [tree.name] else: taxids = [d.name for d in tree.iter_descendants()] subset_df = best_per_...
9f3de8a2bfc81ed46e57b306291730f6f51169cc
3,599,873
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 argparse def get_arguments(): """ Parse input arguments """ parser = argparse.ArgumentParser(description="Code for domain adaptation (DA) training") parser.add_argument('--cfg', type=str, default=None, help='optional config file', ) parser.add_argument("--random-...
c1d52553350100ae8a9722d95a88fd87b7af62af
3,599,875
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 PIL import os def readGif(filename): """ """ # Check PIL if PIL is None: raise RuntimeError("Need PIL to read animated gif files.") # Check whether it exists if not os.path.isfile(filename): raise IOError('File not found: '+str(filename)) # Load file using PIL ...
6637c48906d0d41c0a55c06f5701ea7971cb3fd3
3,599,877
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
def combine_vertically(H: list): """ combine trees verically, by detecting cycles on their `tau`s """ V_prime = list() H = sorted(H, key=lambda e: e.tau) # TODO : use Forest class and no need for this while H: # for each distinc tree Tc = H[0] C = [t for t in H if Node.__eq__(t...
0fda3b455b109c1fc8291d3065dd627011d57294
3,599,880
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
def preprocess(inputs, output_keys=None, is_training=False, input_field_mapping_fn=None, image_preprocess_fn_dic=None, images_points_correspondence_fn=None, points_pad_or_clip_size=None, voxels_pad_or_clip_size=None...
f41b93fa10aaaeca081d9af25e16e52b8d4655f6
3,599,882
import os import regex import itertools def convert_toc_to_ncx(epub_root_absolute_path: str, toc_filename: str, xsl_filename: str) -> se.easy_xml.EasyXmlTree: """ Take an epub3 HTML5 ToC file and convert it to an epub2 NCX file. NCX output is written to the same directory as the ToC file, in a file named "toc.ncx"....
19da46c90adef8a5777c36ea4d71aab04500d74e
3,599,883
def _get_dataset_from_files(file_name_pattern: str, label: int, test_set_pct: int, shuffle: bool): """Create train and test sets from the images in the directory, given the pattern. Args: file_name_pattern (str): The file name pattern that identifies one set of images. label (int): The label to...
99072b210f62646db45968adbcc537748455c8ae
3,599,884
def BD_BldGag(BD): """ Returns the radial position of BeamDyn blade gages INPUTS: - BD: either: - a filename of a BeamDyn input file - an instance of FileCl, as returned by reading the file, BD = weio.read(BD_filename) OUTPUTS: - r_gag: The radial positions of the gages,...
ef5d721186319bc3c9800645e7245bae78578cb2
3,599,885
def multiply(matrix1, matrix2): """ Multiply 2 matrices by first filling them up with zeros to become of size 2^n x 2^n matrices and then multiplying them recursively Complexity (n = matrix rows/cols) Time complexity: O(n^3) """ m1 = matrix1 m1.fillToSquare() m2 = matrix2 m2.fil...
5f589d0b8a2bd602a3f9ff0a8376ddfefd6bc1b8
3,599,886
from typing import Union from typing import cast def check_task_existence( task_type: TaskType, dataset_id: int, target_name: str, **kwargs ) -> Union[int, None]: """Checks if any task with exists on test server that matches the meta data. Parameter --------- task_type : openml.tasks.TaskType ...
449f7a422fcc2999d0c550f20faba50fb9775c38
3,599,887
def clean_data(df): """ This functions cleans the data by a. converting categories into columns and their values into binary b. duplicates removal Arguments: df (pandas dataframe): Merged categories and messages dataframe Returns: df (pandas dataframe): Cleaned data...
bffe90ea03931f64f28c68d67b27ffda02098387
3,599,888
def product_detail(request, pk): """商品详情""" prod_obj = get_object_or_404(Product, uid=pk, is_valid=True) # 用户的默认地址 user = request.user default_addr = None if user.is_authenticated: default_addr = user.default_addr return render(request, 'product_detail.html', { 'prod_obj': pr...
1362d36ec100a8b0af7aa5b558a56fe403f9c63b
3,599,889
def dynamic_unroll(cell, inputs, begin_state, drop_inputs=0, drop_outputs=0, layout='TNC', valid_length=None): """Unrolls an RNN cell across time steps. Currently, 'TNC' is a preferred layout. unroll on the input of this layout runs much faster. Parameters ---------- cell : ...
391a9fa4cb80a90d298f71ca10f5fa5c06461561
3,599,890
def ldap_auth_login(user): """" Authenticate as a test LDAP user and create a new entry in auth RethinkDB table. Args: user: dict: User table entry for imported LDAP user Returns: token: str: Bearer token upon user's successful authentication """ env = E...
891e8b1c96065f7e74804b2c03264b76ff9444a8
3,599,891
def BGR2Gray(set_x): """ This method takes input in cv2 BGR format and converts it to grayscale Parameters: ------------- set_x: is expected to be a 4D tensor of shape (#sampels, #rows, #cols, 3) or an image (a 3D tensor) of shape (#rows, #cols, 3) ...
5bcdc9c6fc99539fe84808de6cf70ca815bf5ba2
3,599,892
def index_names_from_symbol(symbol): """ Return the domain names of a GAMS symbol, except ['*'] cases are replaced by the name of the symbol and ['*',..,'*'] cases are replaced with ['index_0',..'index_n'] """ index_names = list(symbol.domains_as_strings) if index_names == ["*"]: return [symbol.name] ...
dc4acc473eaf13d18f553abd722384bf4fe3115a
3,599,893
def _getsortargs(x): """Parse sort options into (set, [(key, reverse)], opts)""" args = getargsdict(x, b'sort', b'set keys topo.firstbranch') if b'set' not in args: # i18n: "sort" is a keyword raise error.ParseError(_(b'sort requires one or two arguments')) keys = b"rev" if b'keys' i...
8f22b3735b786fb6efc0dff107617ac41386f910
3,599,894
import os import shutil import warnings import glob import sys def read_flowcell_info(config): """ Check the flowcell path to find the info needed for base calling """ input = config["input"]["name"] info_dict = dict() base_path = os.path.join(config["paths"]["baseDir"]+input) if not os.pa...
eb4645eb65d88b02acb9768ae80fe9afc09f475d
3,599,895
def flights_as_json(flights_qs, limit): """ Given a queryset of flights, return it as JSON with the from/to airports grafted onto it since Django's serializer can't follow relationships. We also need to call values() on both the airports and flights since simplejson doesn't understand models. ...
c6ad0673743c190ec7ca37ab58e07791a182ef27
3,599,896
import numpy def _get_vil_colour_scheme(): """Returns colour scheme for VIL (vertically integrated liquid). :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`. :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`. """ colour_list = [ [16, 71, ...
6547d071fe8a441db78c052684db35e381642804
3,599,897
def _extract(printer, archives, output_dir): """Implementation of the extract function""" if not output_dir.is_dir(): printer("creating output dir {}...".format(output_dir)) output_dir.mkdir() printer("reading archives from {}...".format(__file__)) archive_paths = {} archive_path = N...
ce2ece3f315075ec77f33a0f265042c20daeb9d7
3,599,898
def softmax_accuracy(logits, ids): """Computes accuracy of class logits and ids marginalizing over samples.""" softmax_probs = np.mean(softmax(logits, axis=2), axis=1) correct = np.argmax(softmax_probs, axis=1) == ids acc = np.sum(correct) / float(len(ids)) return (acc, softmax_probs)
2a54e9a5786cacd516bdfae8ab0816d06d870600
3,599,899