content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def fetch_synthetic_2d(lags=0): """ Build synthetic 2d data. Parameters ---------- lags : int, optional If greater than 0 it's added time dependence. The default is 0. Returns ------- data : numpy.ndarray, shape=(3000, 2) Synthetic data. """ seed = 98 ...
006f1dc900d88c45d16eb518403bb576167bcae1
22,610
from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import train_test_split def prepare_data() -> tuple: """Do the whole data preparation - incl. data conversion and test/train split. Returns: tuple: (X_train, y_train, X_test, y_test) """ (data, labels) = get_da...
a2a31f09858393d5fbcd5be80fd61b2e69df3cdf
22,611
def current_url_name(request): """ Adds the name for the matched url pattern for the current request to the request context. """ try: match = resolve(request.path) url_name = match.url_name except Http404: url_name = None return { 'current_url_name':...
9ec6ea26a503e0969400a85a0df7491f6aefc064
22,612
import click def get_crypto_key(): """Shows your crypto key""" key = load_key() if key: click.secho("your actual crypto key:", fg = "blue") return click.echo(load_key())
7078f5fd0fe099ef49a3d702111aae9ee5e23387
22,613
def get_entropies(data: pd.DataFrame): """ Compute entropies for words in wide-format df """ counts = pd.DataFrame(apply_count_values( data.to_numpy(copy=True)), columns=data.columns) probs = (counts / counts.sum(axis=0)).replace(0, np.nan) nplogp = -probs * np.log2(probs) return npl...
49a0a52194472a4285e60a05dab8a83dfaa7eec0
22,614
def _numeric_adjust_widgets(caption: str, min: float, max: float) -> HBox: """Return a HBox with a label, a text box and a linked slider.""" label = Label(value=caption) text = BoundedFloatText(min=min, max=max, layout=wealth.plot.text_layout) slider = FloatSlider(readout=False, min=min, max=max) wi...
b45aaa069f425a888bf54281c6324509eac783c6
22,616
def where_handle(tokens): """Process where statements.""" internal_assert(len(tokens) == 2, "invalid where statement tokens", tokens) final_stmt, init_stmts = tokens return "".join(init_stmts) + final_stmt + "\n"
8377a1b62ffbca31a6b6fa42a125e3b16387a665
22,618
def nltk_ngram_pos_tagger(input_dict): """ A tagger that chooses a token's tag based on its word string and on the preceding n word's tags. In particular, a tuple (tags[i-n:i-1], words[i]) is looked up in a table, and the corresponding tag is returned. N-gram taggers are typically trained on a...
ab6d1f48590042b1efe0a9c7e741e7a5ccbcdb34
22,619
def remove_app(INSTALLED_APPS, app): """ remove app from installed_apps """ if app in INSTALLED_APPS: apps = list(INSTALLED_APPS) apps.remove(app) return tuple(apps) return INSTALLED_APPS
7386b6f38b73abf25e94d9c8368aaac6255d2cee
22,621
from typing import OrderedDict def get_feature(cluster, sample, i): """Turn a cluster into a biopython SeqFeature.""" qualifiers = OrderedDict(ID="%s_%d" % (sample, i)) for attr in cluster.exportable: qualifiers[attr] = getattr(cluster, attr.lower()) feature = SeqFeature(FeatureLocation(cluste...
4ec3cb0757db9b884d3bce3d4406f1824a6c62dd
22,622
def loss(Y, spectra, beta, Yval, val_spec): """ Description ----------- Calculate the loss for a specfic set of beta values Parameters ---------- Y: labels (0 or 1) spectra: flux values beta: beta values Yval: validation set labels (0 or 1) val_spec: validation flux values Returns ------- ...
5be2675d14062834bc0f8c9cd83551a60b528668
22,623
def video_detail_except(): """取得channelPlayListItem/videoDetail兩表video_id的差集 Returns: [list]: [目前尚未儲存詳細資料的影片ID] """ playlist_id = get_db_ChannelPlayListItem_video_id() video_detail_id = get_db_VideoDetail_video_id() if video_detail_id and playlist_id: filter_video = list(set(pla...
efe9f151c6689cf6a71584cf988d0af8bb1c0c2a
22,624
def nodes(xmrs): """Return the list of Nodes for *xmrs*.""" nodes = [] _props = xmrs.properties varsplit = sort_vid_split for p in xmrs.eps(): sortinfo = None iv = p.intrinsic_variable if iv is not None: sort, _ = varsplit(iv) sortinfo = _props(iv) ...
0e081648e6b30ec6cc230218c346384624d2ade6
22,625
import torch def get_data_loader(transformed_data, is_training_data=True): """ Creates and returns a data loader from transformed_data """ return torch.utils.data.DataLoader(transformed_data, batch_size=50, shuffle=True) if is_training_data else torch.utils.data.DataLoader(transformed_data, batch_size...
7f7dfdc83abc0ab261fde7be2216b4e130761f7e
22,627
def structured_rand_arr(size, sample_func=np.random.random, ltfac=None, utfac=None, fill_diag=None): """Make a structured random 2-d array of shape (size,size). If no optional arguments are given, a symmetric array is returned. Parameters ---------- size : int Determi...
4463f62bef1feff23019cc35439545b52461ee40
22,629
def append_empty_args(func): """To use to transform an ingress function that only returns kwargs to one that returns the normal form of ingress functions: ((), kwargs)""" @wraps(func) def _func(*args, **kwargs): return (), func(*args, **kwargs) return _func
ec2bf4c30eddb418ade57e50ce8a4a233a8f0f9d
22,630
def gateway(job, app, tool, user, user_email): """ Function to specify the destination for a job. At present this is exactly the same as using dynamic_dtd with tool_destinations.yml but can be extended to more complex mapping such as limiting resources based on user group or selecting destinations ...
b51cd288b638469d054191be0c1423d0c637ce9a
22,631
def pprint(matrix: list) -> str: """ Preety print matrix string Parameters ---------- matrix : list Square matrix. Returns ------- str Preety string form of matrix. """ matrix_string = str(matrix) matrix_string = matrix_string.replace('],', '],\n') retu...
5c0ffa2b0a9c237b65b5ad7c4e17c2456195c088
22,633
def sigmoid(x : np.ndarray, a : float, b : float, c : float) -> np.ndarray : """ A parameterized sigmoid curve Args: x (np.ndarray or float): x values to evaluate the sigmoid a (float): vertical stretch parameter b (float): horizontal shift parameter c (float): horizontal st...
dacb80ca958bf9f0a007fe6d50970f444fd9b4e7
22,634
def merge_testcase_data(leaf, statsname, x_axis): """ statsname might be a function. It will be given the folder path of the test case and should return one line. """ res = get_leaf_tests_stats(leaf, statsname) return merge_testcase_data_set_x(res, x_axis)
5b8829377d9249630a9261e7ee27533cce72542c
22,635
def dashed_word(answer): """ :param answer: str, from random_word :return: str, the number of '-' as per the length of answer """ ans = "" for i in answer: ans += '-' return ans
358be047bfad956afef27c0665b02a2a233fefbf
22,637
def merge_overpass_jsons(jsons): """Merge a list of overpass JSONs into a single JSON. Parameters ---------- jsons : :obj:`list` List of dictionaries representing Overpass JSONs. Returns ------- :obj:`dict` Dictionary containing all elements from input JSONS. """ el...
c68fde0ddbdf22a34377e1e865be36aaabaa47be
22,638
from admin.get_session_info import run as _get_session_info from admin.login import run as _login from admin.logout import run as _logout from admin.recover_otp import run as _recover_otp from admin.register import run as _register from admin.request_login import run as _request_login from admin.handler import MissingF...
1885705099ce67e806a6cc9a461f92c659bbf0bb
22,639
def load_template(tmpl): """ Loads the default template file. """ with open(tmpl, "r") as stream: return Template(stream.read())
a37a74cf37a05142bcddac870a81ee44531004f3
22,640
def get_total_cases(): """全国の現在の感染者数""" return col_ref.document(n).get().to_dict()["total"]["total_cases"]
1e933fd86cde49edbb5d78591fb513cb9633c080
22,642
from typing import Optional def _find_db_team(team_id: OrgaTeamID) -> Optional[DbOrgaTeam]: """Return the team with that id, or `None` if not found.""" return db.session.query(DbOrgaTeam).get(team_id)
9c0709c8b601a1910ed1e6b08f16970c976b7310
22,643
from typing import Optional from contextlib import suppress def make_number( num: Optional[str], repr: str = None, speak: str = None, literal: bool = False, special: dict = None, ) -> Optional[Number]: """Returns a Number or Fraction dataclass for a number string If literal, spoken string...
0fdbd9610355cfceb2ee5ab0fd04b694ca8da9af
22,644
import plotly.graph_objs as go def gif_jtfs_3d(Scx, jtfs=None, preset='spinned', savedir='', base_name='jtfs3d', images_ext='.png', cmap='turbo', cmap_norm=.5, axes_labels=('xi2', 'xi1_fr', 'xi1'), overwrite=False, save_images=False, width=800, height=800, surface_count...
0d34878378e463a55655be29bd6b3d665adc05c6
22,646
def _serialize_account(project): """Generate several useful fields related to a project's account""" account = project.account return {'goal': account.goal, 'community_contribution': account.community_contribution, 'total_donated': account.total_donated(), 'total_raised':...
dea20df5db1ae37f61d6c661f957432b7cb72158
22,648
def neighbor_smoothing_binary(data_3d, neighbors): """ takes a 3d binary (0/1) input, returns a "neighbor" smoothed 3d matrix Input: ------ data_3d: a 3d np.array (with 0s and 1s) -> 1s are "on", 0s are "off" neighbors: the value that indicates the number of neighbors around voxel to check Returns: -------...
22f503e9843a1a0864e3a66c4ed05070712defa3
22,650
def registrymixin_models(): """Fixtures for RegistryMixin tests.""" # We have two sample models and two registered items to test that # the registry is unique to each model and is not a global registry # in the base RegistryMixin class. # Sample model 1 class RegistryTest1(BaseMixin, db.Model):...
420ecaea78780524ac0a889af1d584d0bbced8f3
22,653
def is_test_input_output_file(file_name: str) -> bool: """ Return whether a file is used as input or output in a unit test. """ ret = is_under_test_dir(file_name) ret &= file_name.endswith(".txt") return ret
961c2dcda2cb848a1880b36ca06c01a8bf091704
22,654
import csv def generate_csv_from_queryset(queryset, csv_name = "query_csv"): """ Genera un file csv a partire da un oggetto di tipo QuerySet :param queryset: oggetto di tipo QuerySet :param csv_name: campo opzionale per indicare il nome di output del csv :return: oggetto response """ try: ...
ba4fab63e40cf791d7ac148ca804f0f60173d395
22,655
def get(isamAppliance, id, check_mode=False, force=False, ignore_error=False): """ Retrieving the current runtime template files directory contents """ return isamAppliance.invoke_get("Retrieving the current runtime template files directory contents", "/mga/template_f...
252bf635445af134772e8e762508ec9eb32d974e
22,656
def update(contxt, vsmapp_id, attach_status=None, is_terminate=False): """update storage pool usage""" if contxt is None: contxt = context.get_admin_context() if not vsmapp_id: raise exception.StoragePoolUsageInvalid() is_terminate = utils.bool_from_str(is_terminate) kargs = { ...
1015a7387cb264e9f8ce611d1b2de531aabb249e
22,657
import tqdm def adsgan(orig_data, params): """Generate synthetic data for ADSGAN framework. Args: orig_data: original data params: Network parameters mb_size: mini-batch size z_dim: random state dimension h_dim: hidden state dimension lamda: identifiability parameter itera...
f0e4f85f93d116c75c82a1aba524bed89beb4f14
22,658
import requests def unemployed(year,manu, key,state='*'): #ex manu= 54 is professional, scientific, and technical service industries, year= 2017 """Yearly data on self-employed manufacturing sectors for all counties. Returns all receipts in thousands of dollars for all counties for the specified state for certain...
1ee03a5a0ee1faf2101b8785aadda688b722a96e
22,659
def stack_bricks(top_brick, bottom_brick): """Stacks two Duplo bricks, returns the attachment frame of the top brick.""" arena = composer.Arena() # Bottom brick is fixed in place, top brick has a freejoint. arena.attach(bottom_brick) attachment_frame = arena.add_free_entity(top_brick) # Attachment frame is ...
64b096bc77dfcd62c39cccdfad10241a1574a1ec
22,660
def trigger(name): """ @trigger decorator allow to register a function as a trigger with a given name Parameters ---------- name : str Name of the trigger """ _app = get_app_instance() return _app.trigger(name)
3af727c206565346b69ea5eb6735d9237cefeaf3
22,661
from typing import Dict from typing import List def get_components_to_remove(component_dict: Dict[str, ComponentImport]) -> List[str]: """Gets a list of components to remove from the dictionary using console input. Args: component_dict (Dict[str, ComponentImport]): The custom component dictionary. ...
fd423b0de58ef2e8d5db1a63d334f034a729f2f4
22,662
import requests def list_data_objects(): """ This endpoint translates DOS List requests into requests against indexd and converts the responses into GA4GH messages. :return: """ req_body = app.current_request.json_body if req_body: page_token = req_body.get('page_token', None) ...
0eae49f4e559a4d640ce304cfaa17ef3806b2937
22,663
from typing import Union def get_include_file_start_line(block: Block) -> Union[int, None]: """ >>> block = lib_test.get_test_block_ok() >>> # test start-line set to 10 >>> get_include_file_start_line(block) 10 >>> assert block.include_file_start_line == 10 >>> # test start-line not set ...
5e9ddeed83192f8a53acaca1a6ac4493a7dcbe36
22,664
def get_wcets(utils, periods): """ Returns WCET """ return [ui * ti for ui, ti in zip(utils, periods)] # return [math.ceil(ui * ti) for ui, ti in zip(utils, periods)]
f853459b2463fc75b91f5effe3357b9c4ec5c4f9
22,665
def aws_get_dynamodb_table_names(profile_name: str) -> list: """ get all DynamoDB tables :param profile_name: AWS IAM profile name :return: a list of DynamoDB table names """ dynamodb_client = aws_get_client("dynamodb", profile_name) table_names = [] more_to_evaluate = True last_ev...
fddc574e8f4f6a798e5fe0b339c898b09f18b527
22,666
from typing import Any def stack_images_vertical( image_0: NDArray[(Any, ...), Any], image_1: NDArray[(Any, ...), Any] ) -> NDArray[(Any, ...), Any]: """ Stack two images vertically. Args: image_0: The image to place on the top. image_1: The image to place on the bottom. Returns:...
bb83cc6246bef5df370b45ac0ce7ed5b58a974f7
22,667
def simulate_ids(num): """ 模拟生成一定数量的身份证号 """ ids = [] if num > 0: for i in range(1, num+1): id_raw = digit_1to6() + digit_7to10() + digit_11to14() + digit_15to17() id = id_raw + digit_18(id_raw) ids.append(id) else: return False return ids
2e74fb150f01b8d43eefffdab2d95790cad6f334
22,668
def geomean(x): """computes geometric mean """ return exp(sum(log(i) for i in x) / len(x))
7c5ad27938a6d6da7f304d7ac66fcc1a179162c2
22,669
from typing import Tuple def _get_mean_traces_for_iteration_line_plot( scenario_df: pd.DataFrame, ) -> Tuple[go.Scatter, go.Scatter, go.Scatter]: """Returns the traces for the mean of the success rate. Parameters ---------- scenario_df : pd.DataFrame DataFrame containing the columns "n_it...
04542d1b1f76173e8fa2431a5a6bd3b8e8627026
22,670
def create_graph_of_words(words, database, filename, window_size = 4): """ Function that creates a Graph of Words that contains all nodes from each document for easy comparison, inside the neo4j database, using the appropriate cypher queries. """ # Files that have word length < window size, are ski...
89560a26d2ab624a28b07bf2ff826a8eb34564e8
22,671
from pathlib import Path def get_dir(path): """ Функция возвращает директорию файла, если он является файлом, иначе возвращает объект Path из указанного пути """ if not isinstance(path, Path): path = Path(path) return path.parent if path.is_file() else path
b7ca7f60d88c06bc3181bd93039c13a13e2684a4
22,672
import hashlib def get_file_sha(fname): """ Calculates the SHA1 of a given file. `fname`: the file path return: the calculated SHA1 as hex """ result = '' if isfile(fname): sha1 = hashlib.sha1() with open(fname, 'rb') as f: while True: data = f....
c328f8c5b65a018016a02d39a54b753c33cd3217
22,673
def graphtool_to_gjgf(graph): """Convert a graph-tool graph object to gJGF. Parameters ---------- graph : graph object from graph-tool Returns ------- gjgf : dict Dictionary adhering to :doc:`gravis JSON Graph Format (gJGF) <../../format_specification>` Caution ---...
73ceca04270aaa1f754001d446dba9c796ef6822
22,674
def forbidden_error(error): """ 418 I'm a teapot """ return engine.get_template('errors/417.html').render({}), 418
43319b9aa95c970e75e392e584dd8af78199ceb0
22,675
def green(s: str) -> str: """green(s) color s with green. This function exists to encapsulate the coloring methods only in utils.py. """ return colorama.Fore.GREEN + s + colorama.Fore.RESET
56f12d56257d0728d7d71cba61256bede5c3a064
22,676
import pickle def cache_fun(fname_cache, fun): """Check whether cached data exists, otherwise call fun and return Parameters ---------- fname_cache: string name of cache to look for fun: function function to call in case cache doesn't exist probably a lambda function ...
0387f611ab12aeb8a2d7dfca664e08b0438b1905
22,677
def find_server_storage_UUIDs(serveruuid): """ @rtype : list @return: """ storageuuids = [] db = dbconnect() cursor = db.cursor() cursor.execute("SELECT UUID, ServerUUID FROM Storage WHERE ServerUUID = '%s'" % serveruuid) results = cursor.fetchall() for row in results: ...
48abd3e3a9dc49cef5f9eb52d7327e79a61602a4
22,678
import torch def unpack_bidirectional_lstm_state(state, num_directions=2): """ Unpack the packed hidden state of a BiLSTM s.t. the first dimension equals to the number of layers multiplied by the number of directions. """ batch_size = state.size(1) new_hidden_dim = int(state.size(2) / num_dire...
fa58ed9bcf2e9e95aa62b3d18110abe6abce6b1b
22,679
def macd_diff(close, window_slow=26, window_fast=12, window_sign=9, fillna=False): """Moving Average Convergence Divergence (MACD Diff) Shows the relationship between MACD and MACD Signal. https://en.wikipedia.org/wiki/MACD Args: close(pandas.Series): dataset 'Close' column. window_fa...
ef5b222c688026a25121b35d4354967e4f5c93fc
22,680
def spike_histogram(series, merge_spikes=True, window_duration=60, n_bins=8): """ Args: * series (pd.Series): watts * merge_spikes (bool): Default = True * window_duration (float): Width of each window in seconds * n_bins (int): number of bins per window. Returns: sp...
fc401d8c2b4aabde646a3570397f8fdb8087bf6b
22,681
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_information_rate_post(uuid, local_id, tapi_common_capacity_value=None): # noqa: E501 """data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_infor...
92cefba50ff813e2fd1797d383ae2df7e02a99da
22,682
def any(*args, span=None): """Create a new experssion of the union of all conditions in the arguments Parameters ---------- args : list List of symbolic boolean expressions span : Optional[Span] The location of this operator in the source code. Returns ------- expr: Ex...
697eb7e44d0fb9a0b9b947eea9fe4e8f68b78210
22,683
from typing import List from typing import Any def firstOrNone(list: List[Any]) -> Any: """ Return the first element of a list or None if it is not set """ return nthOrNone(list, 0)
9c51a2f72fe5f516258f2fd20210bd83a3cfbf2d
22,684
def ellipse_points( xy=[0,-5.], ex=254., ez=190., n=1000 ): """ :param ec: center of ellipse :param ex: xy radius of ellipse :param ez: z radius of ellipse :param n: number of points :return e: array of shape (n,2) of points on the ellipse """ t = np.linspace( 0, 2*np.pi, n ) e = np...
93b3aeccf6ab04ad8b0e96cdad80a52d9a6c46c4
22,685
def ion_list(): """List of ions with pre-computed CLOUDY ionization fraction""" ions = np.array(['al2','c2','c3','c4','fe2','h1','mg2', 'n1','n2','n3','n4','n5','ne8','o1','o6', 'o7','o8','si2','si3','si4']) return ions
4fae0b3cf7956349a30807d4975b1d72cf10c9ec
22,687
def is_valid_filename(filename): """Determines if a filename is valid (with extension).""" valid_extensions = ['mp4', 'webm', 'ogg'] extension = get_extension(filename) return bool(extension and extension in valid_extensions)
6a493fac59fca900e5d3bf55075e897bf36528f7
22,688
import re def read(line_str, line_pos, pattern='[0-9a-zA-Z_:?!><=&]'): """ Read all tokens from a code line matching specific characters, starting at a specified position. Args: line_str (str): The code line. line_pos (int): The code line position to start reading. pattern (st...
95ece37e927ff3f8ea9579a7d78251b10b1ed0e6
22,689
from typing import Dict import random def demographic(population: int, highest_lvl_ratio: int = ONE_MILLION, num_levels: int = NUM_LEVELS) -> Dict[int, int]: """ Calculate the number of levelled NPCs in a given population. Args: population: The population to consider these levelled NP...
b45b26c7add41c85cf526789ba26f7c877db685a
22,690
def gencpppxd(env, exceptions=True, ts=None): """Generates all cpp_*.pxd Cython header files for an environment of modules. Parameters ---------- env : dict Environment dictonary mapping target module names to module description dictionaries. exceptions : bool or str, optional ...
627828bfc01c8282b0bf53f5e3cef234d0bdc816
22,691
import requests def configure_mongo_connection( key: str, host: str, port: int, dbname: str, username: str, password: str ): """ Configure the connection with the given `key` in fidesops with your PostgreSQL database credentials. Returns the response JSON if successful, or throws an error otherwise. ...
72746eb7bcebb747b4821f453e8f0f4543abc060
22,692
import random def fully_random(entries, count): """Choose completely at random from all entries""" return random.sample(entries, count)
a1f494f6b3cc635bc109378305bf547d48f29019
22,693
def _get_sets_grp(grpName="controllers_grp"): """Get set group Args: grpName (str, optional): group name Returns: PyNode: Set """ rig = _get_simple_rig_root() sets = rig.listConnections(type="objectSet") controllersGrp = None for oSet in sets: if grpName in oSe...
ec65ab91b69cb1c509412258b517f78f9e124f24
22,694
import re def clean_text(text, cvt_to_lowercase=True, norm_whitespaces=True): """ Cleans a text for language detection by transforming it to lowercase, removing unwanted characters and replacing whitespace characters for a simple space. :rtype : string :param text: Text to clean :param c...
7586112429f529d21f5d7a992bf40d3604dfe52a
22,695
def print(*args, **kwargs) -> None: """Proxy for Console print.""" console = get_console() return console.print(*args, **kwargs)
49b96ae3df30bf09e742f8355f0867341396bc44
22,696
import yaml def _yaml_to_dict(yaml_string): """ Converts a yaml string to dictionary Args: yaml_string: String containing YAML Returns: Dictionary containing the same object """ return yaml.safe_load(yaml_string)
c7de0c860028d17302cd4d07e20c3215503b977b
22,698
import urllib from bs4 import BeautifulSoup def room_urls_for_search_url(url): """ the urls of all rooms that are yieled in a search url """ with urllib.request.urlopen(url) as response: html = response.read() soup = BeautifulSoup(html, 'html.parser') room_urls = {erg_list_entry.find('a...
8945b55e7379860defa0f4229690e53196acbe4d
22,699
import time import hmac import hashlib import requests import json def bittrex_get_balance(api_key, api_secret): """Get your total balances for your bittrex account args: required: api_key (str) api_secret (str) return: results (DataFrame) of balance informatio...
a90979a495fe9410d76996006063ca01fdcfe04c
22,700
def evaluate_functions(payload, context, get_node_instances_method, get_node_instance_method, get_node_method): """ Evaluate functions in payload. :param payload: The payload to evaluate. :param context: Context used during evaluation. :param get_node_instances_method: A method for getting node ins...
2cac04f35ac6032ec0d06ff5c25da9b64c700f7c
22,702
import torch def rollout(render=False): """ Execute a rollout and returns minus cumulative reward. Load :params: into the controller and execute a single rollout. This is the main API of this class. :args params: parameters as a single 1D np array :returns: minus cumulative reward # Why is ...
9165642f37ef1ea6882c6be0a6fe493d2aff342c
22,703
import requests import json def get_request(url, access_token, origin_address: str = None): """ Create a HTTP get request. """ api_headers = { 'Authorization': 'Bearer {0}'.format(access_token), 'X-Forwarded-For': origin_address } response = requests.get( url, ...
0c7f577132b1fb92a8ea9073cb68e9b7bf3cd2a5
22,704
def join_metadata(df: pd.DataFrame) -> pd.DataFrame: """Joins data including 'agent_id' to work out agent settings.""" assert 'agent_id' in df.columns sweep = make_agent_sweep() data = [] for agent_id, agent_ctor_config in enumerate(sweep): agent_params = {'agent_id': agent_id} agent_params.update(ag...
c09a524484424fb0fdf329fd73e3ea489b8ae523
22,705
def mocked_get_release_by_id(id_, includes=[], release_status=[], release_type=[]): """Mimic musicbrainzngs.get_release_by_id, accepting only a restricted list of MB ids (ID_RELEASE_0, ID_RELEASE_1). The returned dict differs only in the release title and artist name, so that ID...
647b9bf54f27353834a30ec907ecc5114a782b93
22,706
def get_name_with_template_specialization(node): """ node is a class returns the name, possibly added with the <..> of the specialisation """ if not node.kind in ( CursorKind.CLASS_DECL, CursorKind.STRUCT_DECL, CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION): return None tokens = get_token...
4cf19f9f383174789c7ff3003bc1144167d3e84d
22,710
from typing import Optional from typing import Union def linear_timeseries( start_value: float = 0, end_value: float = 1, start: Optional[Union[pd.Timestamp, int]] = pd.Timestamp("2000-01-01"), end: Optional[Union[pd.Timestamp, int]] = None, length: Optional[int] = None, freq: str = "D", c...
ae8ef8252beee1e799182d0aaa499167c1abb78d
22,711
from typing import Dict def outlierBySd(X: Matrix, max_iterations: int, **kwargs: Dict[str, VALID_INPUT_TYPES]): """ Builtin function for detecting and repairing outliers using standard deviation :param X: Matrix X :param k: threshold values 1, 2, 3 for ...
eda872a6dd6f8de22620ecf599381d186641a772
22,712
from typing import Dict def encode_address(address: Dict) -> bytes: """ Creates bytes representation of address data. args: address: Dictionary containing the address data. returns: Bytes to be saved as address value in DB. """ address_str = '' address_str += address['bal...
fcf05da104551561e44b7ab9c2bf54a9bfcf801e
22,713
def analyze_image(image_url, tag_limit=10): """ Given an image_url and a tag_limit, make requests to both the Clarifai API and the Microsoft Congnitive Services API to return two things: (1) A list of tags, limited by tag_limit, (2) A description of the image """ clarifai_tags = clarifai_analysis(im...
8d3337c34369d69c9ae48f43100ecb2b930f8a15
22,714
def _decision_function(scope, operator, container, model, proto_type): """Predict for linear model. score = X * coefficient + intercept """ coef_name = scope.get_unique_variable_name('coef') intercept_name = scope.get_unique_variable_name('intercept') matmul_result_name = scope.get_unique_variab...
e5f105bfb09ac0b5aba0c7adcfd6cb6538911040
22,715
def create_mapping(dico): """ Create a mapping (item to ID / ID to item) from a dictionary. Items are ordered by decreasing frequency. """ sorted_items = sorted(list(dico.items()), key=lambda x: (-x[1], x[0])) id_to_item = {i: v[0] for i, v in enumerate(sorted_items)} item_to_id = {v: k for ...
cdfb0bd9ffa047e0214486a1b2e63b45e437cf22
22,716
def read_library(args): """Read in a haplotype library. Returns a HaplotypeLibrary() and allele coding array""" assert args.library or args.libphase filename = args.library if args.library else args.libphase print(f'Reading haplotype library from: {filename}') library = Pedigree.Pedigree() if ar...
e96b156db9cdcf0b70dfcdb2ba155f26a59f8d44
22,718
import sympy def get_symbolic_quaternion_from_axis_angle(axis, angle, convention='xyzw'): """Get the symbolic quaternion associated from the axis/angle representation. Args: axis (np.array[float[3]], np.array[sympy.Symbol[3]]): 3d axis vector. angle (float, sympy.Symbol): angle. conve...
8d753c72fc775de38b349e2bf77e3a61a84b07e9
22,720
def get_session(role_arn, session_name, duration_seconds=900): """ Returns a boto3 session for the specified role. """ response = sts_client.assume_role( RoleArn=role_arn, RoleSessionName=session_name, DurationSeconds=duration_seconds, ) creds = response["Credentials"] ...
d60b0b1c6288a8a594e0a1fe4175c69da80ffe29
22,721
import traceback def base_kinesis_role(construct, resource_name: str, principal_resource: str, **kwargs): """ Function that generates an IAM Role with a Policy for SQS Send Message. :param construct: Custom construct that will use this function. From the external construct is usually 'self'. :param re...
82c2d7b7b32857baa619ed7891956930e206bf78
22,722
def set_age_distribution_default(dic, value=None, drop=False): """ Set the ages_distribution key of dictionary to the given value or to the World's age distribution. """ ages = dic.pop("age_distribution", None) if ages is None: ages = world_age_distribution() if value is None else valu...
98ca6e784b240ee76ddb4a9d77b691ef08fa7057
22,723
def home(): """Home page""" return render_template('home.html')
dc63ced89e5176de1f77ea995678c2f5c37c2593
22,724
import copy def csv2dict(file_csv, delimiter=','): """ This function is used to load the csv file and return a dict which contains the information of the csv file. The first row of the csv file contains the column names. Parameters ---------- file_csv : str The input filename incl...
d971941b7c5f0bbf021c64cf7c30d1dcee710b9d
22,725
def make_bb_coord_l(contour_l, img, IMG_HEIGHT): """ Take in a list of contour arrays and return a list of four coordinates of a bounding box for each contour array. """ assert isinstance(contour_l, list) coord_l = [] for i in range(len(contour_l)): c = contour_l[i] ...
4f30c95db8a7d2ef81376aa0fa77d7cedc0a913c
22,726
def calc_pair_scale(seqs, obs1, obs2, weights1, weights2): """Return entropies and weights for comparable alignment. A comparable alignment is one in which, for each paired state ij, all alternate observable paired symbols are created. For instance, let the symbols {A,C} be observed at position i and {A...
6781b86719d669970d67753eabc91c60bc258dcc
22,727
def distance_to_line(pt, line_pt_pair): """ Returns perpendicular distance of point 'pt' to a line given by the pair of points in second argument """ x = pt[0] y = pt[1] p, q = line_pt_pair q0_m_p0 = q[0]-p[0] q1_m_p1 = q[1]-p[1] denom = sqrt(q0_m_p0*q0_m_p0 + q1_m_p1*q1_m_p1) ...
93500c0f8a4d8d11435647e1868fb929128d1273
22,728
def define_wfr(ekev): """ defines the wavefront in the plane prior to the mirror ie., after d1 :param ekev: energy of the source """ spb = Instrument() spb.build_elements(focus = 'nano') spb.build_beamline(focus = 'nano') spb.crop_beamline(element1 = "d1") bl = spb.get_beamline(...
8ccf7880ff22dc13f979b45c288a58bbb4e3c5c9
22,729
def ratlab(top="K+", bottom="H+", molality=False): """ Python wrapper for the ratlab() function in CHNOSZ. Produces a expression for the activity ratio between the ions in the top and bottom arguments. The default is a ratio with H+, i.e. (activity of the ion) / [(activity of H+) ^ (charge of t...
69c6a5fbbb344e5b0e063ea438994c3ce7e6cafb
22,730