content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import time def confirm_channel(bitcoind, n1, n2): """ Confirm that a channel is open between two nodes """ assert n1.id() in [p.pub_key for p in n2.list_peers()] assert n2.id() in [p.pub_key for p in n1.list_peers()] for i in range(10): time.sleep(0.5) if n1.check_channel(n2) ...
bcbf895b286b446f7bb0ad2d7890a0fa902cdbd1
4,655
def has_permissions(**perms): """A :func:`check` that is added that checks if the member has any of the permissions necessary. The permissions passed in must be exactly like the properties shown under :class:`discord.Permissions`. Parameters ------------ perms An argument list of p...
bf9432f136db8cd2643fe7d64807194c0479d3cd
4,656
def extend_params(params, more_params): """Extends dictionary with new values. Args: params: A dictionary more_params: A dictionary Returns: A dictionary which combines keys from both dictionaries. Raises: ValueError: if dicts have the same key. """ for yak in more_params: if yak in p...
626db0ae8d8a249b8c0b1721b7a2e0f1d4c084b8
4,657
import logging def __compute_libdeps(node): """ Computes the direct library dependencies for a given SCons library node. the attribute that it uses is populated by the Libdeps.py script """ if getattr(node.attributes, 'libdeps_exploring', False): raise DependencyCycleError(node) env ...
93e44b55bb187ae6123e22845bd4da69b260b107
4,658
def _AccumulatorResultToDict(partition, feature, grads, hessians): """Converts the inputs to a dictionary since the ordering changes.""" return {(partition[i], feature[i, 0], feature[i, 1]): (grads[i], hessians[i]) for i in range(len(partition))}
20cc895cf936749a35c42a1158c9ea6645019e7d
4,659
async def create(payload: ProductIn): """Create new product from sent data.""" product_id = await db.add_product(payload) apm.capture_message(param_message={'message': 'Product with %s id created.', 'params': product_id}) return ProductOut(**payload.dict(), product_id=product_id)
77f9ef1699cba57aa8e0cfd5a09550f6d03b8f72
4,661
def get_glove_info(glove_file_name): """Return the number of vectors and dimensions in a file in GloVe format.""" with smart_open(glove_file_name) as f: num_lines = sum(1 for line in f) with smart_open(glove_file_name) as f: num_dims = len(f.readline().split()) - 1 return num_lines, num_...
4fde6a034197e51e3901b22c46d946330e2e213e
4,662
from typing import Dict from typing import List def retrieve_database_inputs(db_session: Session) -> ( Dict[str, List[RevenueRate]], Dict[str, MergeAddress], List[Driver]): """ Retrieve the static inputs of the model from the database :param db_session: SQLAlchemy Database connection session :...
f5242680576d7e07b87fb8fd31e26efc1b0c30f0
4,663
def _evolve_cx(base_pauli, qctrl, qtrgt): """Update P -> CX.P.CX""" base_pauli._x[:, qtrgt] ^= base_pauli._x[:, qctrl] base_pauli._z[:, qctrl] ^= base_pauli._z[:, qtrgt] return base_pauli
5d0529bc4bfe74a122c24069eccb20fa2b69f153
4,664
def tp_pixel_num_cal(im, gt): """ im is the prediction result; gt is the ground truth labelled by biologists;""" tp = np.logical_and(im, gt) tp_pixel_num = tp.sum() return tp_pixel_num
197c1f64df3430cfbb6f45413b83360a1b9c44bf
4,665
import time def xsg_data(year=None, month=None, retry_count=3, pause=0.001): """ 获取限售股解禁数据 Parameters -------- year:年份,默认为当前年 month:解禁月份,默认为当前月 retry_count : int, 默认 3 如遇网络等问题重复执行的次数 pause : int, 默认 0 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题 ...
0ca7070a63ec9ee58bb590b82d9bcdb8e4801d33
4,666
def crm_ybquery_v2(): """ crm根据用户手机号查询subId :return: """ resp = getJsonResponse() try: jsonStr = request.data # 调用业务逻辑 resp = {"message":"","status":200,"timestamp":1534844188679,"body":{"password":"21232f297a57a5a743894a0e4a801fc3","username":"admin"},"result":{"id"...
02b7ff4e1f44643537b4549376aa637dcdbf5261
4,667
from typing import Dict from typing import List from typing import Union from pathlib import Path from typing import Iterable from typing import Tuple import tqdm import logging def get_split_file_ids_and_pieces( data_dfs: Dict[str, pd.DataFrame] = None, xml_and_csv_paths: Dict[str, List[Union[str, Path]]] = ...
d01768fddcef9428e5dd3a22592dca8dd083fc9c
4,668
def calc_full_dist(row, vert, hor, N, site_collection_SM): """ Calculates full distance matrix. Called once per row. INPUTS: :param vert: integer, number of included rows :param hor: integer, number of columns within radius :param N: integer, number of points in row ...
e332b3b51cf4dadb764865f7c75eb361aa0cc100
4,669
def background_upload_do(): """Handle the upload of a file.""" form = request.form # Is the upload using Ajax, or a direct POST by the form? is_ajax = False if form.get("__ajax", None) == "true": is_ajax = True print form.items() # Target folder for these uploads. # target = o...
267608fa9c93a75ca260eb742fed9023ec350b65
4,670
def load_dict_data(selected_entities=None, path_to_data_folder=None): """Loads up data from .pickle file for the selected entities. Based on the selected entities, loads data from storage, into memory, if respective files exists. Args: selected_entities: A list of string entity names to be loa...
0236d69d6ed6c663c3bba5edabd59ced9755c546
4,673
def cart_del(request, pk): """ remove an experiment from the analysis cart and return""" pk=int(pk) # make integer for lookup within template analyze_list = request.session.get('analyze_list', []) if pk in analyze_list: analyze_list.remove(pk) request.session['analyze_list'] = analyze_list ...
210a0fd58d9470aa365906420f3769b57815839a
4,674
def get_block_devices(bdms=None): """ @type bdms: list """ ret = "" if bdms: for bdm in bdms: ret += "{0}\n".format(bdm.get('DeviceName', '-')) ebs = bdm.get('Ebs') if ebs: ret += " Status: {0}\n".format(ebs.get('Status', '-')) ...
bd375f988b13d8fe5949ebdc994210136acc3405
4,675
from scipy import stats # lazy import from pandas import DataFrame def outlier_test(model_results, method='bonf', alpha=.05, labels=None, order=False, cutoff=None): """ Outlier Tests for RegressionResults instances. Parameters ---------- model_results : RegressionResults instance...
39219cf5ad86f91cf6da15ea66dc2d18f0a371af
4,676
def move(request, content_type_id, obj_id, rank): """View to be used in the django admin for changing a :class:`RankedModel` object's rank. See :func:`admin_link_move_up` and :func:`admin_link_move_down` for helper functions to incoroprate in your admin models. Upon completion this view sends the ...
0a8e73d83d7d7c575a8ed5abe43524b22d701a38
4,677
def test_second_playback_enforcement(mocker, tmp_path): """ Given: - A mockable test When: - The mockable test fails on the second playback Then: - Ensure that it exists in the failed_playbooks set - Ensure that it does not exists in the succeeded_playbooks list """ ...
314cbfb4f659b34adfdafb6b1c1153c8560249b0
4,678
import re def decode_textfield_ncr(content): """ Decodes the contents for CIF textfield from Numeric Character Reference. :param content: a string with contents :return: decoded string """ def match2str(m): return chr(int(m.group(1))) return re.sub('&#(\d+);', match2str, content...
28bf8017869d1ad47dce4362ec2b57131f587bba
4,679
def reflect_or_create_tables(options): """ returns a dict of classes make 'em if they don't exist "tables" is {'wfdisc': mapped table class, ...} """ tables = {} # this list should mirror the command line table options for table in list(mapfns.keys()) + ['lastid']: # if option...
8974f6e6299240c69cf9deffdb3efb7ba9dc771f
4,680
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_grpc_interface] interface_dir=<<path to the parent directory of your Protocol Buffer (pb2) files>> #<<package_name>>=<<communication_ty...
cb26012ff6ad1a2dbccbbcc5ef81c7a91def7906
4,681
def color_print(path: str, color = "white", attrs = []) -> None: """Prints colorized text on terminal""" colored_text = colored( text = read_warfle_text(path), color = color, attrs = attrs ) print(colored_text) return None
c3f587d929f350c86d166e809c9a63995063cf95
4,683
def create_cluster_spec(parameters_server: str, workers: str) -> tf.train.ClusterSpec: """ Creates a ClusterSpec object representing the cluster. :param parameters_server: comma-separated list of hostname:port pairs to which the parameter servers are assigned :param workers: comma-separated list of host...
2b4555b68821327451c48220e64bc92ecd5f3acc
4,684
def bq_client(context): """ Initialize and return BigQueryClient() """ return BigQueryClient( context.resource_config["dataset"], )
839a72d82b29e0e57f5973aee418360ef6b3e2fc
4,685
def longascnode(x, y, z, u, v, w): """Compute value of longitude of ascending node, computed as the angle between x-axis and the vector n = (-hy,hx,0), where hx, hy, are respectively, the x and y components of specific angular momentum vector, h. Args: x (float): x-component of position ...
d108847fa6835bc5e3ff70eb9673f6650ddf795a
4,686
def convert_to_distance(primer_df, tm_opt, gc_opt, gc_clamp_opt=2): """ Convert tm, gc%, and gc_clamp to an absolute distance (tm_dist, gc_dist, gc_clamp_dist) away from optimum range. This makes it so that all features will need to be minimized. """ primer_df['tm_dist'] = get_distance( ...
4d556fd79c2c21877b3cb59712a923d5645b5eba
4,689
import copy def _tmap_error_detect(tmap: TensorMap) -> TensorMap: """Modifies tm so it returns it's mean unless previous tensor from file fails""" new_tm = copy.deepcopy(tmap) new_tm.shape = (1,) new_tm.interpretation = Interpretation.CONTINUOUS new_tm.channel_map = None def tff(_: TensorMap,...
263a16a5cb92e0a9c3d42357280eeb6d15a59773
4,690
def generate_dataset(config, ahead=1, data_path=None): """ Generates the dataset for training, test and validation :param ahead: number of steps ahead for prediction :return: """ dataset = config['dataset'] datanames = config['datanames'] datasize = config['datasize'] testsize = co...
89136efffbbd6e115b1d0b887fe7a3c904405bda
4,691
def search(isamAppliance, name, check_mode=False, force=False): """ Search UUID for named Web Service connection """ ret_obj = get_all(isamAppliance) return_obj = isamAppliance.create_return_object() return_obj["warnings"] = ret_obj["warnings"] for obj in ret_obj['data']: if obj['na...
f642e9e62203b490a347c21899d45968f6258eba
4,692
def flask_app(initialize_configuration) -> Flask: """ Fixture for making a Flask instance, to be able to access application context manager. This is not possible with a FlaskClient, and we need the context manager for creating JWT tokens when is required. @return: A Flask instance. """ fla...
265c912833025d13d06c2470443e68110ce4f60f
4,693
import requests def http_request(method, url_suffix, params=None, data=None, headers=HEADERS, safe=False): """ A wrapper for requests lib to send our requests and handle requests and responses better. :type method: ``str`` :param method: HTTP method for the request. :type url_suf...
9fbd5123e4f1a39f5fa10fbc6a8f41db7ed1775b
4,694
def FP(target, prediction): """ False positives. :param target: target value :param prediction: prediction value :return: """ return ((target == 0).float() * prediction.float().round()).sum()
9c8b21ecbc4f48b737c92fbaf73ef820fe035218
4,696
import math def get_angle(A, B, C): """ Return the angle at C (in radians) for the triangle formed by A, B, C a, b, c are lengths C / \ b / \a / \ A-------B c """ (col_A, row_A) = A (col_B, row_B) = B (col_C, row_C) = C a = pixel_distance(C, ...
30e1681bf2c065c4094b2dd909322158a9968c3c
4,697
def single_labels(interesting_class_id): """ :param interesting_class_id: integer in range [0,2] to specify class :return: number of labels for the "interesting_class" """ def s_l(y_true, y_pred): class_id_true = K.argmax(y_true, axis=-1) accuracy_mask = K.cast(K.equal(class_id_true,...
d137bbd4bba4bcb19e9bc296e4cecdbd7d8effe6
4,698
def get_rdf_lables(obj_list): """Get rdf:labels from a given list of objects.""" rdf_labels = [] for obj in obj_list: rdf_labels.append(obj['rdf:label']) return rdf_labels
2bcf6a6e8922e622de602f5956747955ea39eeda
4,700
import json def _create_model_fn(pipeline_proto, is_chief=True): """Creates a callable that build the model. Args: pipeline_proto: an instance of pipeline_pb2.Pipeline. Returns: model_fn: a callable that takes [features, labels, mode, params] as inputs. """ if not isinstance(pipeline_proto, pipeli...
f29e86a0bc1355a7cf509e57ad0262bc5a9ca1e5
4,701
def boolean_automatic(meshes, operation, **kwargs): """ Automatically pick an engine for booleans based on availability. Parameters -------------- meshes : list of Trimesh Meshes to be booleaned operation : str Type of boolean, i.e. 'union', 'intersection', 'difference' Returns...
7e5b1a483862bb05bb4cd78d21ec22c835f218e6
4,702
from .workflow import WorkSpec def get_context(work=None): """Get a concrete Context object. Args: work (gmx.workflow.WorkSpec): runnable work as a valid gmx.workflow.WorkSpec object Returns: An object implementing the :py:class:`gmx.context.Context` interface, if possible. Raises: ...
838de2ce25dbe44c058f5360a59e48a68fa7dc2a
4,703
def test_data(): """Get the `CIFAR-10` test data.""" global _MEAN # pylint: disable=global-statement _np.random.seed(1) view = _skdc10.view.OfficialImageClassificationTask() permutation = _np.random.permutation(range(10000)) if _MEAN is None: _MEAN = view.train.x.reshape((50000 * 32 * 3...
e20acfc0e46dba2441b03d0d1443fc193c500e62
4,704
def normalize_key_combo(key_combo): """Normalize key combination to make it easily comparable. All aliases are converted and modifier orders are fixed to: Control, Alt, Shift, Meta Letters will always be read as upper-case. Due to the native implementation of the key system, Shift pressed in c...
e242c6d9177d31c60a534e9734917c6fdf2de9f7
4,705
def shape_to_np(shape, dtype="int"): """ Used to convert from a shape object returned by dlib to an np array """ return np.array([[shape.part(i).x, shape.part(i).y] for i in range(68)], dtype=dtype)
6d3d0205a8ac90dc8fb17b844fd5e150e25bdde1
4,706
def inet_pton(space, address): """ Converts a human readable IP address to its packed in_addr representation""" n = rsocket.inet_pton(rsocket.AF_INET, address) return space.newstr(n)
d015f76ab252e8f1f9f8f764bb7a2131f9ca9b92
4,707
def delete_routing_segmentation_maps_from_source_segment( self, segment_id: int, ) -> bool: """Delete D-NAT policies for specific source segment .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - vrf - DELETE - /v...
32064ca159928ccc0802791e161a614f3303555f
4,708
def _identifier(name): """ :param name: string :return: name in lower case and with '_' instead of '-' :rtype: string """ if name.isidentifier(): return name return name.lower().lstrip('0123456789. ').replace('-', '_')
fbbbc9dd3f2bc5b6e43520c0685f63a10ee95f0a
4,710
def roots(p): """ Return the roots of a polynomial with coefficients given in p. The values in the rank-1 array `p` are coefficients of a polynomial. If the length of `p` is n+1 then the polynomial is described by p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters ---------- ...
02e3f37a81c84aac9ac949662ec64b85e24432c9
4,711
from typing import List def calculate_trade_from_swaps( swaps: List[AMMSwap], trade_index: int = 0, ) -> AMMTrade: """Given a list of 1 or more AMMSwap (swap) return an AMMTrade (trade). The trade is calculated using the first swap token (QUOTE) and last swap token (BASE). Be aware that an...
55071041fd0cab3fd2c0cb89f24cd9267a4e164a
4,712
def tokenize(s): """ Tokenize a string. Args: s: String to be tokenized. Returns: A list of words as the result of tokenization. """ #return s.split(" ") return nltk.word_tokenize(s)
8dcc01364b3442539dbcc979d3238492bb7904d1
4,713
from datetime import datetime def evaluate(request): """Eval view that shows how many times each entry was tracked""" # default filter end_date = datetime.date.today() start_date = datetime.date(year=end_date.year, month=end_date.month - 1, day=end_date.day) num_entries = 5 # get custom filte...
44708b65846fd9e21ebc7baf1fe0377054ae2221
4,714
def significant_pc_test(adata, p_cutoff=0.1, update=True, obsm='X_pca', downsample=50000): """ Parameters ---------- adata p_cutoff update obsm downsample Returns ------- """ pcs = adata.obsm[obsm] if pcs.shape[0] > downsample: print(f'Downsample PC matrix ...
c8e367c53330bcb959fb7baba9649d090de91389
4,716
def unique_hurricanes(hurdat): """ Returns header info for each unique hurricanes in HURDAT2-formatted text file hurdat. """ #split on returns if hurdat is not a list if not isinstance(hurdat, list): hurdat = hurdat.split('\n') header_rows = [parse_header( line, line_num ...
c87561b80f6c8b70c33d64834c4d289508a2c120
4,718
def delete_models_shares_groups(id, group_id, client=None): """Revoke the permissions a group has on this object Use this function on both training and scoring jobs. Parameters ---------- id : integer The ID of the resource that is shared. group_id : integer The ID of the group...
59f3391e6e92fe0bf2f4c204a9da7c55a8ac8c6c
4,720
def step1ddiffusionanalytical(q, dt, alpha, beta, prng=np.random, **kwargs): """Analytical time stepping as proposed in Jenkins, Spano arXiv:1506.06998 Uses the asymptotic normality of the death process for small times (see Griffiths, J. Math. Bio, 1984) """ theta = alpha+beta beta_ =...
ae1034488250a7a0afc184878496cd656b239016
4,721
def no_vtk(): """ Checks if VTK is installed and the python wrapper is functional """ global _vtk_version return _vtk_version is None
654dfd0f10a36bbfd3e46c5a93f84a9234e8c0ca
4,722
def get_request_list(flow_list: list) -> list: """ 将flow list转换为request list。在mitmproxy中,flow是对request和response的总称,这个功能只获取request。 :param flow_list: flow的列表 :return: request的列表 """ req_list = [] for flow in flow_list: request = flow.get("request") req_list.append(request) ...
a70e0120ef2be88bd0644b82317a2a0748352c6c
4,723
from typing import Tuple import logging def query_total_production(start_date, end_date) -> Tuple[int]: """Total count of semi production on the given time interval""" semi_count = None fg_count = None try: with stSession() as s: semi_count = ( s.query(ProductionSc...
4ecf7b2e70feaa75456550deca6a5b8a326adc11
4,724
import pytz def add_fields(_, level, event_dict): """ Add custom fields to each record. """ now = dt.datetime.now() event_dict['timestamp'] = TZ.localize(now, True).astimezone(pytz.utc).isoformat() event_dict['level'] = level if session: event_dict['session_id'] = session.get('session_id'...
3efbffc2808a048fde80a3655e28417c39f2ad04
4,725
def Smith_set(A,P,params,election_ID,printing_wanted=False): """ Compute and return a list of the candidates in the Smith set. This is the smallest set of candidates such that every candidate in the Smith set beats every candidate not in the Smith set in one-on-one contests. In this implementation, ...
eb71ee5ae402d732a3bea804aad5b39fe3bd92a2
4,726
from typing import Callable from typing import Coroutine from typing import Any def run_async_from_thread(func: Callable[..., Coroutine[Any, Any, T_Retval]], *args) -> T_Retval: """ Call a coroutine function from a worker thread. :param func: a coroutine function :param args: positional arguments for...
829a9008e8aa058b66cb637db71f8f8eb8499374
4,727
def check_tensor_shape(tensor_tf, target_shape): """ Return a Tensorflow boolean graph that indicates whether sample[features_key] has the specified target shape. Only check not None entries of target_shape. :param tensor_tf: Tensor to check shape for. :param target_shape: Target shape to compare t...
8b9938c67f2e3655f9ff4dac08261fb6e5803af2
4,728
def LabelAddressPlus(ea, name, force=False, append_once=False, unnamed=False, nousername=False, named=False, throw=False): """ Label an address with name (forced) or an alternative_01 :param ea: address :param name: desired name :param force: force name (displace existing name) :param append_onc...
4772fa25c482eb10abdfea6aa9542f50827c9346
4,729
def do_match(station1, station2, latitude, elevation, distance): """ Perform the match between two stations. Do initial latitude check to speed up the test (not longitude as this isn't a constant distance) Return probabilities for elevation, separation and Jaccard Index :param Station Class...
078d04117363087a512449497713c487bc1180e4
4,730
def rotation_matrix_from_vectors(vec1, vec2): """ Find the rotation matrix that aligns vec1 to vec2 Args ---- vec1 (numpy.ndarray): A 3d "source" vector vec2 (numpy.ndarray): A 3d "destination" vector Returns ------- numpy.ndarray: A transform matrix (3x3) which when applie...
9568378e309c5da6e6dffee4788e07eb0c2ea189
4,731
def audio(src, type="audio/ogg", other_attr={}): """ add audio file args: src <str> : source file type <str> : type of audio file other_attr <dict> : other attributes """ return f""" <audio {_parse_attr(other_attr)}> <source src="{src}" type="{type}"> </audi...
3ccd8aea6d7257c46336bb81184cf4b7f379624e
4,733
def test_triangle(dim): """ Tests if dimensions can come from a triangle. dim is a list or tuple of the three dimensions """ dim = [int(x) for x in dim] dim.sort() if dim[0] + dim[1] > dim[2]: return True else: return False
fc5bc8f7d3830da0ae8692d7cf65a72bcfe2ba7d
4,734
from typing import List def arg_parser(data: str): """parse "x[a1, a2, a3], y[k1=a1, a2, k3=a3], z" nested [] are ignored. """ res: List[NameWithAttrs] = _ARG_WITH_ATTR_PARSER.parse(data) return res
fa530584a96829944562d2c08bdfed34bfa3eec4
4,735
def _get_resource(span): """Get resource name for span""" if "http.method" in span.attributes: route = span.attributes.get("http.route") return ( span.attributes["http.method"] + " " + route if route else span.attributes["http.method"] ) return sp...
71b4d2e568350ccfb436bbff6e7a2cff1f3cb251
4,736
def get_draw_title(kdata): """根据typ值,返回相应的标题,如 上证指数(日线) 参数:kdata: KData实例 返回:一个包含stock名称的字符串,可用作绘图时的标题 """ if not kdata: return "" query = kdata.getQuery() stock = kdata.getStock() if stock.isNull(): return "" s1 = '' if query.kType == KQuery.KType.DAY: ...
7c661b63cedb477224d7f5ea9d7c182108f801a5
4,737
def _B(slot): """Convert slot to Byte boundary""" return slot*2
97f13e9fd99989a83e32f635193a0058656df68b
4,738
import torch def nll(perm, true): """ perm: (n, n) or (s, n, n) true: (n) """ n = true.size(-1) # i = torch.arange(n, device=perm.device) # j = true.to(perm.device) # print("perm.nll:", perm.size(), true.size()) elements = perm.cpu()[..., torch.arange(n), true] # elements = per...
a63c95e814529539ecd964f4309ea96f78cfcbb1
4,739
def _peaks_colors_from_points(points, colors=None, points_per_line=2): """ Returns a VTK scalar array containing colors information for each one of the peaks according to the policy defined by the parameter colors. Parameters ---------- points : (N, 3) array or ndarray points coordinate...
7abc5be4739164dc225081ec321d1cb591f74bae
4,740
def epi_reg(epi, t1, t1brain, out='epi_reg', **kwargs): """Wrapper for the ``epi_reg`` command. :arg epi: Input EPI image :arg t1: Input wholehead T1 image :arg t1brain: Input brain extracted T1 image :arg out: Output name """ asrt.assertIsNifti(epi) asrt.assertIsNi...
1d19f0efcfb4fcfc7293f294978d11811861a06b
4,741
import pathlib import json def load_towns(): """Sample of Wikipedia dataset that contains informations about Toulouse, Paris, Lyon and Bordeaux. Examples -------- >>> from pprint import pprint as print >>> from cherche import data >>> towns = data.load_towns() >>> print(towns[:3]) ...
72aa393cfc40db5f254059d78679ea5615f494d2
4,742
def nonce_initialization(params: InitializeNonceParams) -> TransactionInstruction: """Generate an instruction to initialize a Nonce account. Args: params: The nonce initialization params. Returns: The instruction to initialize the nonce account. """ return TransactionInstruction.f...
99fc70fd7965443b508923013a988f96ecf7b222
4,743
def to_weeknr(date=''): """ Transforms a date strings YYYYMMDD to the corresponding week nr (e.g. 20200713 becomes w29) """ week_nr = pd.to_datetime(date).to_pydatetime().isocalendar()[1] return f"w{week_nr}"
f9699e735be8d92e4340a23464ee54247c355ffd
4,744
def build_logisticregression(X_loc, y_loc, args): """finds best parameters for logistic regression""" Printer(colored('(training) ', 'green') + 'searching for best parameters for logistic regression') # specify parameters and distributions to sample from param_dist = {"C": np.logspace(-9, 3, 13), "solver":...
f63f67bc9debd2adccac39910b29ed705498dd4b
4,745
import re def load_data(experiments, remove_outlier=True, peptides=["A5cons", "A6cons", "phage_ctl_0", "phage_ctl_1", "phage_ctl_2", "phage_ctl_4", ...
b9d7c7be8e0bbe5f5aee785cc0b525d9a57acc8b
4,746
def get_lines(clearance): """ Add lines per reference well interval between the closest points on the reference well and the offset well and color them according to the calculated Separation Factor (SF) between the two wells at these points. Parameters ---------- clearance: welleng.clea...
2ec0ef039647b9c72219989d00b3e92092a79c16
4,747
import hashlib def generate_md5_hash(filepath): """Returns md5 hash of file. Args: filepath: str. Absolute path to the file. Returns: str. Hexadecimal hash of specified file. """ m = hashlib.md5() with python_utils.open_file(filepath, 'rb', encoding=None) as f: while ...
d615d9ec14b79eac72168db616664f5878ca8e21
4,748
def status(): """Return status.""" return jsonify(STATUS)
de396fdf35e42a36ed40b294a26645efba29c27a
4,749
from typing import Optional def get_entitlement(account_id: Optional[str] = None, customer_id: Optional[str] = None, entitlement_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEntitlementResult: """ Returns the ...
8cc10901b90a05a4bc0089758ce297c54af48569
4,750
def skip_to_home(fxn): """ Skips past page straight to home page if logged in """ @wraps(fxn) def skipped_page_fxn(*arg, **kwargs): if session.get('logged_in'): return redirect(url_for('home')) else: return fxn(*arg, **kwargs) return skipped_page_fxn
9edbbc186caa93046d17c179610a9c1309f281db
4,751
from pathlib import Path def get_all_paths_from_directory(directory: Path, recursive: bool, paths: [str] = [], ) -> [Path]: """ Gets a list of file paths for all files in the given directory (and its subdirectories if recursive is true) :param directory: The starting directory to get file paths from :...
95f26d94ff1656fa5e4c656ecf3e424bf29f21b0
4,752
def check_contigs_for_dupes(matches): """check for contigs that match more than 1 UCE locus""" node_dupes = defaultdict(list) for node in matches: node_dupes[node] = len(set(matches[node])) dupe_set = set([node for node in node_dupes if node_dupes[node] > 1]) return dupe_set
f20ab684388e38b51e193567b14a2a610d87f227
4,753
def substitute(P, x0, x1, V=0): """ Substitute a variable in a polynomial array. Args: P (Poly) : Input data. x0 (Poly, int) : The variable to substitute. Indicated with either unit variable, e.g. `x`, `y`, `z`, etc. or through an integer matching the unit va...
dd176877f8663e7efb3ae99babf29726dbda025b
4,754
def munkres(costs): """ Entry method to solve the assignment problem. costs: list of non-infinite values entries of the cost matrix [(i,j,value)...] """ solver = Munkres(costs) return solver.munkres()
583dfc977c8f97fd5a3c4c82e21ae6626f4a763b
4,755
import torch def compute_mean_std(dataset): """ https://stats.stackexchange.com/questions/25848/how-to-sum-a-standard-deviation """ # global_mean = np.zeros((3 * 64), dtype=np.float64) # global_var = np.zeros((3 * 64), dtype=np.float64) n_items = 0 s = RunningStatistics() for image_...
83f10fc58e83b41a542fbd088895304b0d0521b5
4,756
def test_clean_connections_p0(monkeypatch): """Add a connection, fake a closed thread and make sure it is removed.""" db_disconnect_all() class mock_connection(): def __init__(self) -> None: self.value = _MOCK_VALUE_1 def close(self): self.value = None def mock_connect(*args, **kwargs)...
9c8c7155566170a3598edcb8a9d7441630545522
4,757
def add(request): """ Add contact information. **Templates:** * ``rolodex/add.html`` **Template Variables:** * form * results: the list of similar names to allow user to check for dupes * name: the new name that is submitted """ results = [] name = None if request.m...
b0fdb73f2362dc0a82d46529727cfb3b0093b8e0
4,758
def convert_total (letter1,number1, letter2, number2): """ Description ----------- Converting the letter of a column and the number of a line from an exceldata to a range Context ---------- is called in wrapp_ProcessUnits and wrapp_SystemData Parameters ---------- le...
51cf6480d92fa1d23841dd5605d024548837df5c
4,759
def scale_facet_list(facet_list, scale): """ Scale list of facets by the given scaling factor """ new_facet_list = [] for facet in facet_list: new_facet_list.append(scale_facet(facet, scale)) return new_facet_list
1b1d34803db191b94fc082685718c08895e2ba28
4,760
def move_lines_to_index(uwline_index_to, lineno, uwlines, lines): """Method moves all lines in the list to the proper index of uwlines and update lineno on these lines. This is useful when you want to change the order of code lines. But note: it is not updating lineno on other lines @:returns positi...
e96f3b9da77468a31275e6255cd08ffa9309fc60
4,761
def birch(V, E0, B0, BP, V0): """ From Intermetallic compounds: Principles and Practice, Vol. I: Principles Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos paper downloaded from Web case where n=0 """ E = (E0 + 9.0/8.0*B0*V0*((V0/V)**(2.0/3.0) - 1.0)**2 +...
6515e2b0b78dfcdc1d7743f3d5a7010fce920aea
4,762
from typing import Set from typing import Tuple def debloat(edges: set, nodes: int, threshold: tuple = (0.95, 0.95)) -> Set[Tuple[str, str]]: """Remove nodes with inflow and/or ourflow > threshold""" df = pd.DataFrame(list(edges), columns=["source", "target"]) checkpoint_shape = df.shape[0] df_inflow ...
5be2dec388086b10409a3de008f357540019c5cf
4,763
def result(jid): """ Displays a job result. Args: jid (str): The job id. """ job = q.fetch_job(jid) statuses = { 'queued': 202, 'started': 202, 'finished': 200, 'failed': 500, 'job not found': 404, } if job: job_status = job.get_statu...
2919be693949dd4e873834530565fd28aefcf5d5
4,764
from typing import Callable def fd_nabla_1( x: np.ndarray, fun: Callable, delta_vec: np.ndarray, ) -> np.ndarray: """Calculate FD approximation to 1st order derivative (Jacobian/gradient). Parameters ---------- x: Parameter vector, shape (n_par,). fun: Function returning function valu...
32363e04bbd22627c7e5c21e02b48154dbfc030a
4,765
def get_ref_len_from_bam(bam_path, target_contig): """ Fetch the length of a given reference sequence from a :py:class:`pysam.AlignmentFile`. Parameters ---------- bam_path : str Path to the BAM alignment target_contig : str The name of the contig for which to recover haplotype...
e80cb3c50f4408b2a614621ff3d688852931e75b
4,766
def vstd(df, n=10): """ 成交量标准差 vstd(10) VSTD=STD(Volume,N)=[∑(Volume-MA(Volume,N))^2/N]^0.5 """ _vstd = pd.DataFrame() _vstd['date'] = df.date _vstd['vstd'] = df.volume.rolling(n).std(ddof=1) return _vstd
97b448d00bcbe89d17339f9ed1155786d9ccd0ab
4,767