content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def test3(): """test 3 Returns: str: transportation plan """ a = [20, 11, 18, 27] b = [11, 4, 10, 12, 8, 9, 10, 4] c = [[-3, 6, 7, 12, 6, -3, 2, 16], [4, 3, 7, 10, 0, 1, -3, 7], [19, 3, 2, 7, 3, 7, 8, 15], [1, 4, -7, -3, 9, 13, 17, 22]] return matrix_tran...
0bb86ffb8477453665eef346c0fa0c76f190758c
65,866
import torch def cfg_sample(model, steps, eta, method="ddim", batchsize=1): """Draws samples from a model given starting noise.""" _, side_y, side_x = model.shape zero_embed = torch.zeros([1, model.clip_model.visual.output_dim], device=model.device) target_embeds, weights = [zero_embed], [] def...
750cb34e088cbe1daa4ff08b79e41ecc02853e0f
65,867
def intro_binary_logic( masks, ): """ Mask to dilated intro-channel binary or-logic. Dilate mask -> compute or-logic """ def _mask_or_logic( dilated_mask ): c, h, w = dilated_mask.shape or_logic = [ [ ( (dilated_mask[i]*...
1ab7738a34814768d3ec14cd1ca2129f77624747
65,868
def add_user_db(user: User) -> bool: """ Adds a new user to the database. :param user: User object to add to database :return: True if added, else False if error. """ # If request didn't specify permissions, ensure that none are stored in the database. if user.roles is None: roles ...
a657abf98efcab5ee646be244107fa6f143afccb
65,869
import statistics def ping_statistics(data): """ Render result statistics :return: str result string """ TEMPLATE = """--- {hostname} ping statistics --- {packet} packets transmitted, {packet_received} packets received, {packet_lost:.1f}% packet loss""" RTT_TEMPLATE = """\nround-trip min/avg/m...
1ba4977f6c70dd0719bb5b1d5301795b3ca0ad6a
65,871
from typing import Optional def inverse_from_cholesky_band( lower_band: LowerTriangularBandedMatrixTensor, result_lower_bandwidth: Optional[int] = None ) -> LowerTriangularBandedMatrixTensor: """ Given a lower-banded matrix L that is assumed to be the Cholesky decomposition of a (symmetric, Positive D...
208f62bc747ee0fd2444ea62f456e0f3572afe5f
65,872
import requests def webhook_post(url, event_dict): """Posts an event to the supplied URL. The request body is a JSON dictionary of: * type: webhook message type (currently always 'event') * event_dict: webhook data (the event payload) Event payloads are in the same format as the /api/events/...
a8bdcce66cf272835e3b77b659c8b063eab51ebd
65,873
import json def process_settings(default_settings, user_settings_string=""): """Combine the default settings with any user settings. Process the user settings and override the default if a corresponding user setting exists. Print a warning if a there is a missing user setting. Parameters -------...
8bfc0de7fd61f77cccdffe3101699b9a8ee0f264
65,874
def dot_s(inputa,inputb): """Dot product for space vectors""" return inputa[:,0]*inputb[:,0] + inputa[:,1]*inputb[:,1] + inputa[:,2]*inputb[:,2]
7991192fa07b953cd2e8e3d5439769eebf0e1608
65,875
import time def utc2datetime(_utc, _format="%Y-%m-%d %H:%M:%S"): """ UTC转datetime """ return time.strftime(_format, time.localtime(int(_utc)))
992304ee88c99bf81734b8bf473fe8359810a843
65,876
def pla(args, random_seeds, train_data, test_data): """ Perceptron Learning Algorithm :param args: :param train_data: :param test_data: """ err = np.zeros((int(args['n_epochs']), 1)) train_loss = np.zeros_like(err) test_loss = np.zeros_like(err) for seed in random_seeds: ...
14224d2e2eb0de0b71622792b08c31b7b49bd070
65,877
import pickle def pickle_serialize(data): """ Serialize the data into bytes using pickle Args: data: a value Returns: Returns a bytes object serialized with pickle data. """ return pickle.dumps(data)
9c8809ab7bbd0375e9d94d6baae95e26166e6c56
65,878
def _open_close_position_condition(df): """ 找出开、平仓的K线 """ hold_pos_cond = df[POSITION_COLUMN] != 0 # 持仓 open_pos_cond = df[POSITION_COLUMN] != df[POSITION_COLUMN].shift(1) # 当前周期和上个周期持仓发生变化为开仓 open_pos_cond = hold_pos_cond & open_pos_cond close_pos_cond = df[POSITION_COLUMN] != df[POSITION...
547ce81c439f8d2c0db793fc767cdd05bd6221de
65,880
import json from datetime import datetime from typing import Counter def update_personalchat(dropdown_users, start_date_str, end_date_str, interval1, interval2, datasets): """Update displayed data and chart at first and when filter apply.""" datasets = json.loads(datasets) df = pd.read_json(datasets['data...
42c5222bc9704ea753bc02f5ce0228f5a2257922
65,881
def edit_profile_processing(request: object, profile_change_form: object) -> object: """Change user data in profile.""" user = User.objects.get(email=request.user.email) user.email = profile_change_form.cleaned_data.get('email') if profile_change_form.cleaned_data.get('avatar') != 'images/profiles/anon...
9c446353d007c4fd517c1758adbb41f36b669c9c
65,883
def _find_serving_with_name(serving_name, servings): """ Finds a serving with a given name from a list of servings (O(N)) Args: :serving_name: name of the serving to look for :servings: the list of servings to look through Returns: serving with the given name Raises: ...
ad881783a8a3605878c5a1ae28c37a60367e90f9
65,884
def blurred_images_of_images_and_planes_from_1d_images_and_convolver(total_planes, image_plane_images_1d_of_planes, image_plane_blurring_images_1d_of_planes, convolvers, map_to_scale...
1a9f898916a282e8ccfb356d22ff7fae21d04907
65,886
def parse_protein(seq): """Return a list of protein numbers that are human proteins. Example ------- "PROTEIN\nPR\t#8# Homo sapiens\n<10,11,273>\nPR\t#9# Rattus norvegicus <10,49,50,51,142,167,224,228>" -> ["8"] """ seq = seq.split("\nPR\t") # PR is the identifier for proteins ...
b694b8711e86d5501f9d1623a063abd1c9a4da84
65,887
def significance(size_a, successes_a, size_b, successes_b): """ Calculates the significance for an A/B test. :param size_a: Sample size of the experiment A :param successes_a: Successes of the experiment A :param size_b: Sample size fo the experiment B :param successes_b: Successes of the e...
67b0ed642a339c076457c3e0b659769ddac1210c
65,888
def update_api_release(instance, notes=None): """Updates the details of the release of the API specified by its identifier.""" instance.notes = notes return instance
0aada7780ad9f9d492dbb4611a79cee8538be279
65,889
def edit_diff(start, goal, limit): """A diff function that computes the edit distance from START to GOAL. >>> edit_diff("ash", "hash") 1 >>> edit_diff("roses", "arose") # roses -> aroses -> arose 2 >>> edit_diff("tesng", "testing") # tesng -> testng -> testing 2 >>> edit_diff("rlog...
4016eca481c208fd39b028a4d267d5afb014bbe0
65,890
def time2milliseconds(the_time): """ Converts the time part of a datetime to milliseconds. """ result = 0 if the_time: result += the_time.hour result *= 60 result += the_time.minute result *= 60 result += the_time.second result *= 1000 return 0
5825fed1c9d64db5f145a73a158a5cb79d6065f7
65,891
def strip_cstring(data: bytes) -> str: """Strip strings to the first null, and convert to ascii. The CmdSeq files appear to often have junk data in the unused sections after the null byte, where C code doesn't touch. """ if b'\0' in data: return data[:data.index(b'\0')].decode('ascii') ...
c315e84debe7eef239afd4c856d45f4d2a776af2
65,892
def model_format_args(model, pars): """Format the model and parameter args to save in output file. Change to int, str and float. model in [temp, logg, fe/h, alpha] pars in order (R, band, vsini, sample). Can now also optionally handle a 5th parameter RV. """ temp = int(model[0]) logg ...
118a10c3670399c365c608d9ebfce7d48edb84fb
65,893
def outlet_map(da_flw, ftype="infer"): """Returns a mask of basin outlets/pits from a flow direction raster. Parameters ---------- da_flw: xr.DataArray Flow direction data array ftype : {'d8', 'ldd', 'nextxy', 'nextidx', 'infer'}, optional name of flow direction type, infer from dat...
0e64a214141ff6f82e3ee6295b2339d0ad92b29a
65,894
from bs4 import BeautifulSoup from typing import List from datetime import datetime def _get_novels_from_category_page(category_page: BeautifulSoup) -> List[ShortNovel]: """ Given a beautiful soup which correspond to a page of favorit return a list of novels :param category_page: :return: """ ...
0b63671c7a40cfcd452cef161e1b0af2ccf6618b
65,895
import requests import json def install_geolocation_update(uri, token, zip_file): """ Makes a temp directory, copies zip, unzips archive and installs each of the geolocation RPMs Parameters ---------- uri : str Base URL to call api token : str Valid access token for this API end...
2e0f544d9d640e443ac2d834cad142ffb1f22b40
65,896
from typing import Optional from typing import Union import types def set_bandit_policy_type( info: Optional[Union[PolicyInfo, PerArmPolicyInfo]], bandit_policy_type: types.Tensor) -> Union[PolicyInfo, PerArmPolicyInfo]: """Sets the InfoFields.BANDIT_POLICY_TYPE on info to bandit_policy_type. If policy `...
7c7cbc4795556512605da5ac0f4736b4d4aa4c00
65,897
def pos_record_generate(d: dict): """持仓记录生成器""" pos_record = PosRecord( code=d['code'], exchange=d['exchange'], account_id=d['account_id'], first_buy_date=d['first_buy_date'], last_sell_date=d['last_sell_date'], max_vol=d['max_vol'], buy_price_mean=d['buy_...
e38e87e4e43ba144cad4c1bc79c3149879a68cc4
65,898
def FlatArrow(line1, line2, c="r4", alpha=1, tipSize=1, tipWidth=1): """Build a 2D arrow in 3D space by joining two close lines. |flatarrow| |flatarrow.py|_ """ if isinstance(line1, Points): line1 = line1.points() if isinstance(line2, Points): line2 = line2.points() sm1, sm2 = np.array(line1[-...
864524846214ce009b26f236d7fa70a438d65a56
65,899
import logging import time from datetime import datetime import pytz def get_raw_temperature(request, pymortar_client, weather_mapping): """Returns temperatures for a given request or None. Guarantees that no Nan values in returned data exist.""" logging.info("received request: %s %s %s %s %s", request.bu...
fd7005911058d70481405e5c82b2bee6d18adff7
65,900
def abs_diff(a, b, base=0): """Absolute value of difference between scalars. abs_diff is symmetric, i.e. `a` and `b` are interchangeable. Args: a: First argument. An int. b: Seconds argument. An int. base: Dummy argument so that the argument signature matches other scalar d...
77d4d4231cd50a6e4cc527979fa806e139759d8f
65,901
def model_name(model): """Return model name given model class.""" # Django supports model._meta -> pylint: disable=W0212 return force_text(model._meta)
62a5e3a2ae757ebad6c8af911d492e44b1f359ec
65,902
def getTitles(db): """ Gets all the books titles in the whole database :param db: database object :return: sorted books titles """ data = [] for book in db.find('books'): data.append(book['Title']) return sorted(data)
f63d2138cef4d2ad51767ad62abacce5169bb3a2
65,903
def mse(x: np.ndarray, y: np.ndarray) -> float: """Mean squared error.""" return float(np.mean((x - y) ** 2))
b72f8717650953c1204319d15952a64c3a9c9b16
65,904
def plot_title(df, title, save_figure=False): """ Plots the skill frequencies of all skill categories for a given title. Params: df: (pandas df) the frequency df title: (str) one of the three job titles: 'data scientist', 'machine learning engineer', 'data engineer' ...
a8e69c6cbb6b7878adddcb843ce80091818392ae
65,905
def overlap(a: Pos, b: Pos, exact: bool = False) -> bool: """Calculate if two positions have overlap.""" if a == b: return True elif exact: return False s0, e0 = a s1, e1 = b if in_interval(s1, s0, e0): return True if in_interval(e1, s0, e0): return True i...
5860d7be034116a3c0017f4bb0221501f8948386
65,906
import string import random def random_string(string_length=10): """Generate a random string of fixed length """ letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length))
b3b13b593f7818e85f836086b1ea6f445a414c38
65,907
from typing import Dict def get_dataset_labeling( dataframe: pd.DataFrame, tag_column: str ) -> Dict[str, int]: """Prepares a mapping using unique values from ``tag_column``. .. code-block:: javascript { "class_name_0": 0, "class_name_1": 1, ... "c...
6a968aa16a0cd3b50607d81162a354c8a3f0538e
65,909
def compute_misalignment_matrix_from_bam(bam_fp, bin_size=None, i_know_what_i_am_doing=False): """Create a matrix of binned mis-alignments :param bam_fp: input BAM :param bin_size: size of bin in mega bases :param i_know_what_i_am_doing: Set this to override the runtime warning of too many bins """ def bi...
f0e92ee274c5a8139ca7183fd8c9b8843725fd34
65,910
def calc_auc(scored_labels, true_label): """Calculates area under the (precision-recall) curve.""" tp = 0 total = 0 for ( _, l, ) in scored_labels: if l == true_label: tp += 1 else: total += tp return float(total) / (tp * (len(scored_labels...
f1e907548d3f5897197e97f7340cf3d7f6645e89
65,911
def give_coordinates(data): """ Get ground-truth coordinates (X,Y,Z, room label) where the measurement was taken, given the JSOn structure as an input. """ message = {} message['true_coordinate_x'] = data['raw_measurement'][1]['receiver_location']['coordinate_x'] message['true_coordinate_y'] = data['raw_m...
d412afbe08d4b1660ab9a12d1e567e4c4e4258fc
65,912
def activate_int8_int8_matrix_multiplications(spec, selector=None): """ Utility function that takes in either a full precision (float) spec or an nbit quantized spec to selectively enable int8 activation + weight quantization of matrix multiplication operations where the second matrix represents a const...
af94b9e737ea222e85f3c12de698e74fbcd4d420
65,913
def filter_comment_lines(line): """Filter variable comment lines.""" if line.startswith(b"#"): return True
6f0441adb79ddf7aebb6466cb6dfdb74c74e1d24
65,914
def update_shipping_profile(profile_id, shipping_profile_id, shipping_form_data): """ Update a customer shipping profile and return the CIMResponse. Arguments: profile_id -- unique gateway-assigned profile identifier shipping_profile_id -- uni...
0d4f180760d0d2628f330128691ad98e3c81d85e
65,915
def orders_by_dow(data_frame): """ Gives orders_count by day of week. :param data_frame: DataFrame containing orders data. :return: DataFrame of order_ids count by day of week. """ grouped = data_frame.groupby(['order_dow'], as_index=False) # count by column: 'order_id' count = grouped.agg(...
bfca97ced614fb8c309f8edc482fc2136914759b
65,916
def is_user_logged(app): """Check for auth_tkt cookies beeing set to see if user is logged in.""" cookies = app.cookies if 'auth_tkt' in cookies and cookies['auth_tkt']: return True return False
67e670fd70787b35bc9b8d9a724512bfc4e7bac8
65,917
from pathlib import Path import numpy as np import nibabel as nb def _fix_topup_fieldcoeff(in_coeff, fmap_ref, refpe_reversed=False, out_file=None): """Read in a coefficients file generated by TOPUP and fix x-form headers.""" if out_file is None: out_file = Path("coefficients.nii.gz").absolute() ...
3a62133034d9e23b4593c5f10f8d048a32a63b8d
65,918
def create_get_service_interface_point_list_by_id(): # noqa: E501 """Create get-service-interface-point-list by ID Create operation of resource: get-service-interface-point-list # noqa: E501 :rtype: GetServiceInterfacePointListRPCOutputSchema """ return 'do some magic!'
2f54434f1ecfe77d50034e50b2c4333f24371a08
65,919
def map_reduce_partitions_nb(a, map_func_nb, map_args, reduce_func_nb, reduce_args): """Map using `map_func_nb` and reduce using `reduce_func_nb` each partition of signals in `a`. `map_func_nb` and `reduce_func_nb` are same as for `map_reduce_between_nb`.""" out = np.full(a.shape[1], np.nan, dtype=np.float...
c424f7fd7b22280fd4ba5df86a2f16a1c55948be
65,920
def lookup(name_in_data, language, metalookup=True, openrefine=False): """ Parameters ---------- name_in_data : str Search string. Returns ------- list = [WDdf, how_matched] WDdf is a dataframe with SPARQL-request how_matched shows how the string was matched ...
866180191de041936f3bf9bae4efb7629eaff62a
65,921
import torch def generate_predictions(model, test_dict): """ Function that is used to obtain the test predictions and metrics """ test_data = test_dict.map( lambda batch: batch_tokenize_preprocess( batch, tokenizer, max_input_length, max_output_length ), batched=Tr...
34074065595bf07db3c0d965235a2a8ef1036f25
65,922
from typing import Dict from typing import Optional def issm_likelihood_computations( precomputed: Dict, issm_params: Dict, r_min: int, r_max: int, skip_c_d: bool = False, profiler: Optional[SimpleProfiler] = None, ) -> Dict: """ Given `precomputed` from `issm_likelihood_precomputation...
5f56b547826abbd096f9d4925aab002586f9621f
65,923
def convert_nodata_to_nans(xarr): """ Args: xarr: Returns: """ nodata_attr = [k for k in xarr.attrs.keys() if k.lower().startswith('nodata')][0] nodata = xarr.attrs[nodata_attr] if nodata: if str(xarr.dtype).startswith('int') or str(xarr.dtype).startswith('uint'): ...
f052c4b34141b0823631a61c1f35f163f84d6ddc
65,924
def Main(operation, args): """ :param operation: :param args: :return: """ # 'init' has to be invokded first after deploying the contract to store the necessary and important info in the blockchain if operation == 'init': return init() if operation == 'name': return name(...
1d69d5b0f05774d9ea1540b55ceff5a0020a8b66
65,925
def test_cache_memoize(cache): """ Test that cache.memoize() caches the return value of a function using a key based on function arguments used. """ marker = 1 @cache.memoize() def func(a, b, c, d): return ((a, b, c, d), marker) args, markx = func(1, 2, 3, 4) assert args ==...
5b93bcab00b334b1c38114f8b700b6ef0d9c3178
65,926
def get_settings_text(poll): """Compile the options text for this poll.""" text = [] locale = poll.user.locale text.append( i18n.t( "settings.poll_type", locale=locale, poll_type=translate_poll_type(poll.poll_type, locale), ) ) text.append(i18...
34ad92078b0d440d5706ce0f8486a0770900dc10
65,927
def static(): """ Returns the live STATIC_ROOT directory. """ return python("from django.conf import settings;" "print(settings.STATIC_ROOT)", show=False).split("\n")[-1]
d6fbb06ed26240881d80189d4f758e3f64902011
65,928
import json def parse_osm_streets(fpath): """ Parses the API response from *fpath* and converts it to a dataframe. Args: fpath (str): File path to read Returns: pandas.DataFrame: Contains all streets as well as their geometries """ # Helper function def convert_to_wkt_geo...
429df1f5015dd2b1c1f0c87a9fe01394b44fa688
65,929
def setpgid(space, pid, pgrp): """ setpgid(pid, pgrp) Call the system call setpgid(). """ try: os.setpgid(pid, pgrp) except OSError, e: raise wrap_oserror(space, e) return space.w_None
c4bdfa143b90a57cf941fe0cc5ef442912708a01
65,930
def obey_reporting_preference(function): """ Do not execute this method if report_errors is disabled, even if someone tells you to! """ def inner(self, *args, **kwargs): if not self.reporting_enabled: return None else: return function(self, *args, **kwargs) ...
c0b38babc999b7bf1ace6821d6079f1afb53e540
65,931
def get_number_of_pages(url): """Function that will scrape for the number of pages with listed apartments available. This number will then be used to generate urls that will be scraped for individual apartments. Args: url (str): Url to first page of listings. Returns: int: The ...
a4ac15e798304d6dd0dd92a30d864426186f6cec
65,932
def paths_edges(random_graph): """Fixture for generating path census data frames for edges and node/global counts based `random_graph` fixture. """ _, P = random_graph E = P.census("edges") return E, P
238dfdc767dccd3b048ca7a2781cc692d289554e
65,933
def interpolate_epsilon(teff, dnu, dnu_threshold=30, epsilon_offset=0.601, epsilon_slope=0.632): """ Calculate the asymptotic phase term. This function computes the value of epsilon for either a main-sequence, subgiant star or a red giant star by exploiting empirical relations linking epsilon with...
d8df11b9be137a650adf4ce65ba337b4356d346c
65,934
def make_celery(app): """ Configure celery for app :param app: flask application instance """ # Create and configure celery celery = Celery(app.import_name) celery.config_from_object('config.CeleryConfig') # Celery task using app context BaseTask = celery.Task class ContextTask...
68e8834d431b734f0d0386ff9cfa7af93f7968a7
65,935
import warnings def cycle_matrix(signals, ampl_bins=10, mean_bins=10, rainflow_func=rainflow_windap): """Markow load cycle matrix Calculate the Markow load cycle matrix Parameters ---------- Signals : array-like or list of tuples - if array-like, the raw signal\n - if list of tup...
bef538efa77a5a704effc07ed32e27e90d9f80c7
65,936
def compare(isamAppliance1, isamAppliance2): """ Compare kerberos configuration realms between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) return tools.json_compare(ret_obj1, ret_obj2, deleted_keys=[])
09e5322ef408ac1d86857a4f3bcc4d48ca0fcef7
65,937
def logout_view(request): """ 注销 :param request: :return: """ logout(request) return redirect('system:login')
d6174cefbfab31d31e72387f6c2577e0399dd93f
65,938
def logout(): """ Logout Route The route to log a user out of the portal Args: None Returns: redirect to the public index page """ logout_user() return redirect(url_for('main.public'))
b75f6cabd8766602d868e09cfff98d1491ea04ce
65,939
def get_nx_graph(sdp_lines, remove_singletons = False): """ Return a networkx graph representation of the conll input. @param remove_singletons: Indicates whether to remove nodes which aren't connected to any other node. """ graph = nx.MultiDiGraph() words, pred...
c3ed5c1765eec6b9e829f3eda3bd27f3f3a1bf79
65,940
def is_in_manifest(dynamodb_client, table_name, run_id): """Check if run_id is stored in DynamoDB table. Return True if run_id is stored or False otherwise. Arguments: dynamodb_client - boto3 DynamoDB client (not service) table_name - string representing existing table name run_id - string repr...
5709dd0ffac71bac29d8b585f43f4ea4d4c190c5
65,941
def audio_slip(signal, delay, overlap=0.5): """ # Audio Slip Args: signal (numpy.ndarray): audio signal. delay (int): value of delay size. overlap (float, optional): overlap rate. Defaults to 0.5. Returns: tuple: list of energy and list of zero crossing rate list. """ ...
35da37bd968052e1cfb33d35e81c23fe25dfc59f
65,942
import json def break_bot(): """[Slash command for break punch]""" # break payload blocks = json.loads(""" [ { "type": "header", "text": { "type": "plain_text", "text": "Select your status below:", "emoji": true } }, { "type": "divider" }, { "type": "actions", ...
4664ea206b425a74b2add71b870a9ed904a284dc
65,944
import tqdm def count_destiantions_from_hex( feed: gk.Feed, hex_resolution: int = 8, include_sum: bool = True ) -> pd.DataFrame: """Calculates available directions aggregated to hex. Args: feed (gk.Feed): gtfs feed hex_resolution (int, optional): Defaults to 8. Returns: ...
b41284f9a7b1c8da1f39c9da24af584a9cabdf16
65,945
def extract_gloss(phrase, log=None): """Extract IGT from example.""" if not phrase.find('words'): if log: log.warn("No words in phrase '{}'".format(phrase.attrib.get('guid', '???'))) return {} morph_glosses = list(map(_parse_morph, _find_morphemes(phrase))) gloss = {k: [] f...
fde649961bfdddf961ad8e647af1366c02134685
65,946
def forward_sample(bn, n=1000): """ Approximate marginal probabilities from forward sampling algorithm on a BayesNet object. This algorithm works by repeatedly sampling from the BN and taking the ratio of observations as their marginal probabilities. One sample is done by first sampling from any prior random ...
cd00006c9149b5db504d567f40a931ae49167dfc
65,947
import re def mqtt_wildcard(topic, wildcard): """Returns True if topic matches the wildcard string. """ regex = wildcard.replace('.', r'\.').replace('#', '.*').replace('+', '[^/]*') if re.fullmatch(regex, topic): return True return False
fd7a3a5e8af1e6172decd62f2ba8294dfe07124c
65,948
import _struct def parse_atp_packet(pkt): """Parse a raw ATP packet. pkt -- raw packet data to be parsed. Returns: (kind, flags, seqno, tid, udata, pdata) """ if len(pkt) < ATP_HEADER_LEN + 1: raise ValueError("Invalid packet data: Truncated header") (ddp_tag, kfl, seq, ti...
a14c71006df869ebdc9cc8c5dc475f544385facc
65,949
def make_connection_url(config): """ Returns an SqlAlchemy connection URL based upon values in config dict. Args: config: dict-like object with keys: type, username, password, host, and database. Returns: str URL which SqlAlchemy can use to connect to a database. """...
d7dbd16184efe17355230b59e1157c7dfe164351
65,950
def make_df_from_csv(fname): """Make df""" df = pd.read_csv(fname) df.index = pd.to_datetime(df['DateTime']) df.drop(columns=['DateTime'], inplace=True) return df
8084bd47938d42abbf7a34b016180f0b35deda02
65,951
from datetime import datetime from typing import List def get_obsnums(h5file: h5py.File, start_date: datetime.datetime = None, end_date: datetime.datetime = None, rcu_modes: List[int] = None, station_name: str = None, subband: int = None,...
124ba13a82baf01f502b3fca46e19b66fa46713d
65,952
def build_table_row(obj,admin_class): """生成一条记录的html element""" ele = "" for column_name in admin_class.list_display: column_obj = admin_class.model._meta.get_field(column_name) if column_obj.choices: #get_xxx_display column_data = getattr(obj,'get_%s_display'% column_name)() ...
1aaa614cd3a118b3d5d5a55d311f9cf55e222706
65,953
import re import string def sanitize_name(name): """ Sanitizes the given name such that it conforms to unix policy. Args: name: the name to sanitize. Returns: The sanitized form of name. """ if len(name) == 0: raise Exception("Can not sanitize an empty field.") ...
5b85146c529e37924dd045cc52014cd2c05b9aaa
65,954
from re import T import functools def deco_factory_retry(retry_exceptions=None, max_retries: int = 3, enable_default=False, default=None, exception_predicate: T.Callable[[Exception], bool] = None, exception_queue: T.QueueType = None) -> T.Decorator:...
5bd03aef00de70438915745204d0d61800953204
65,956
import pickle def run_ns( dd_s: DynamicDress, base_path: str, rho_6T_min, rho_6T_max, dM_chirp_abs, gamma_s, rho_6T, ) -> Results: """ Runs nested sampling for a dark dress system given a signal system dd_s. Saves results and posterior plots. """ # Setup gamma_s_ran...
7e8aa245a25f5b2fccf44145e00b3342d5b77b34
65,957
import tempfile import shutil def process_nxml(nxml_filename, pmid=None, extra_annotations=None, **kwargs): """Process an NXML file using the ISI reader First converts NXML to plain text and preprocesses it, then runs the ISI reader, and processes the output to extract INDRA Statements. Parameters ...
620c9b972642e095f9d9ad4ae9f4b51092468283
65,958
def distinct_brightness(dictionary): """Given the brightness dictionary returns the dictionary that has no items with the same brightness.""" distinct, unique_values = {}, set() for char, brightness in dictionary.items(): if brightness not in unique_values: distinct[char] = brightnes...
7f7bb5dba9bab113e15cc4f90ddd4dfda7bb5f01
65,959
def start(start): """Start""" # Create the Session session = Session(engine) # Query the data results = session.query(func.min(Measurement.tobs), func.max(Measurement.tobs), func.avg(Measurement.tobs))\ .filter(Measurement.date >= start)\ .all() # Convert the tuples into a normal list...
a82b675f72fe8ebf91e1f569e933868405ce53df
65,962
def _cc_library_func(ctx, name, hdrs, srcs, copts, dep_ccinfos): """Like cc_library(), but callable from rules. Args: ctx: Rule context. name: Unique name used to generate output files. hdrs: Public headers that can be #included from other rules. srcs: C/C++ source files. dep_ccin...
b4372ce07ae967f9bb1011e6c3fa9922fa68a568
65,963
def get_interaction_extension_pos(frame, primary): """Get the maximum extension position of the interaction/cascade of the first interaction of the primary particle. Parameters ---------- frame : current frame Needed to retrieve I3MCTree primary : I3Particle The particle for whi...
f6ae4023bd2b7d48fc83f70a803a555bb217b3ca
65,964
import re def clean_str(string): """ Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py """ string = re.sub(r"[^A-Za-z0-9(),\+!?\'\`]", " ", string) string = re.sub(r"\'s", " \'s", string) st...
7151767d754ebf4591f30762f8708fe464954ba6
65,965
def import_string(dotted_path): """ Stolen approximately from django. Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import fails. """ try: module_path, class_name = dotted_path.strip(' ').rsplit('.', 1) except...
3f8ed0fca9c56fcb11458a4a76fd31593cf2fc0a
65,966
def get(cmd, resource_group_name=None, workspace_name=None): """ Get the details of the given (or current) Azure Quantum workspace. """ client = cf_workspaces(cmd.cli_ctx) info = WorkspaceInfo(cmd, resource_group_name, workspace_name, None) if (not info.resource_group) or (not info.name): ...
076c382cee4ced54e206513c54663fd00603cef6
65,968
def get_HNet_D(reactions, compounds): """Representing a metabolic pathway as a bipartite graph and returns the graph resulting from the projection of the bipartite graph on its set of reactions. :param reactions: dict of dicts storing reaction information (obtained by parsing a KGML file) :...
f2db776a2ff99b6b8da928da98f331b51d8172cb
65,969
def transition(input_tensor, nb_filter, dropout_rate=None, weight_decay=1e-4): """Apply BatchNorm, Relu 1x1Conv2D, optional dropout and Maxpooling2D. :param input_tensor: keras model :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weig...
e2264b36a5caf2e15e69262b8d7df8979dff2815
65,972
import math def weight_variable(shape, name): """Initializes a tensorflow weight variable with random values centered around 0. """ initial = tf.truncated_normal(shape, stddev=1.0 / math.sqrt(float(shape[0])), dtype=tf.float32) return tf.Variable(initial, name=name)
9f8cf6e4e06cf35c5d0fb32ca465b6c3a34b0faf
65,973
from typing import List def get_nouns(spacy_doc: spacy.tokens.Doc) -> List[spacy.tokens.Token]: """Return a list of noun tokens within a given document. Parameters ---------- spacy_doc : spacy.tokens.Doc spaCy document to parse Returns ------- List[spacy.tokens.Token] A l...
b6cb2a5f3c10f18fc5418db241688132e9400a18
65,974
def _matmul_flops_compute(input, other, *, out=None): """ Count flops for the matmul operation. """ macs = _prod(input.shape) * other.shape[-1] return 2 * macs, macs
20a21bbd75d863a47ad273fde866c4749358ab9c
65,975
def render(content, for_link_cb=None): """ render the content, which is wiki markup. :param for_link_cb: takes a link and returns the wiki content for it. """ # if content is None or content is '': # return '' if content is None or content is '': return '' return render_pq(conte...
9482fdd3a744378dc9cc5f83137212049c53a85a
65,977
import torch def norm(x): """ Normalize a tensor to a tensor with unit norm (treating first dim as batch dim) :param x: :return: """ b = x.size()[0] n = torch.norm(x.view(b, -1), p=2, dim=1) while len(n.size()) < len(x.size()): n = n.unsqueeze(1) n.expand_as(x) retu...
b40ba939c80db85e2ac8377b21ea7a17589b1c0f
65,978