content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import base64 def int_to_base64(i: int) -> str: """ Returns a 12 char length representation of i in base64 """ return base64.b64encode(i.to_bytes(8, 'big'))
5bd7bb032926a8f429d766632c2ef2af9ee01edc
16,514
def payment_provider(provider_base_config): """When it doesn't matter if request is contained within provider the fixture can still be used""" return TurkuPaymentProviderV3(config=provider_base_config)
d6439a5ef097350682a2e17ccc41aeba1310a78a
16,515
import re def gradle_extract_data(build_gradle): """ Extract the project name and dependencies from a build.gradle file. :param Path build_gradle: The path of the build.gradle file :rtype: dict """ # Content for dependencies content_build_gradle = extract_content(build_gradle) match =...
dd802b8fedb682493a1978ae6cd60be9706580ff
16,516
from typing import Sequence import torch def stack_batch_img( img_tensors: Sequence[torch.Tensor], divisible: int = 0, pad_value: float = 0 ) -> torch.Tensor: """ Args :param img_tensors (Sequence[torch.Tensor]): :param divisible (int): :param pad_value (float): value to pad :return: ...
9952965a89688d742a3342804062cb8051f47f54
16,517
from evo.core import lie_algebra as lie def convert_rel_traj_to_abs_traj(traj): """ Converts a relative pose trajectory to an absolute-pose trajectory. The incoming trajectory is processed elemente-wise. Poses at each timestamp are appended to the absolute pose from the previous timestamp. ...
57e4972f5bc4ea67bf62b88ea87fc5df8dda0d7c
16,518
def remove(handle): """The remove action allows users to remove a roommate.""" user_id = session['user'] roommate = model.roommate.get_roommate(user_id, handle) # Check if roommate exists if not roommate: return abort(404) if request.method == 'POST': model.roommate.delete_roo...
b1a279989d3cb463d54c8559352f2ae67f198b40
16,519
def maxsubarray(list): """ Find a maximum subarray following this idea: Knowing a maximum subarray of list[0..j] find a maximum subarray of list[0..j+1] which is either (I) the maximum subarray of list[0..j] (II) or is a maximum subarray list[i..j+1] for some 0 <= i <= j ...
a991ca09c0594b0d47eb4dd8be44d093d593cd36
16,520
def get_merged_threadlocal(bound_logger: BindableLogger) -> Context: """ Return a copy of the current thread-local context merged with the context from *bound_logger*. .. versionadded:: 21.2.0 """ ctx = _get_context().copy() ctx.update(structlog.get_context(bound_logger)) return ctx
03c2689fd71542c7c007512fb4c2bf76a841a7bc
16,521
def sort_cipher_suites(cipher_suites, ordering): """Sorts the given list of CipherSuite instances in a specific order.""" if ordering == 'asc': return cipher_suites.order_by('name') elif ordering == 'desc': return cipher_suites.order_by('-name') else: return cipher_suites
5a554ba1e2e4d82f53f29c5a1c2f4d311f538889
16,522
def make_1D_distributions(lims, n_points, all_shifts, all_errs, norm=None, max_shifts=None, seed=None): """ Generate 1D distributions of chemical shifts from arrays of shifts and errors of each distribution Inputs: - lims Limits of the distributions - n_points Number o...
87c48b80dc395b4423b88fcbb3307dd53655333e
16,523
def fill_column_values(df, icol=0): """ Fills empty values in the targeted column with the value above it. Parameters ---------- df: pandas.DataFrame icol: int Returns ------- pandas.DataFrame """ v = df.iloc[:,icol].fillna('').values.tolist() vnew = fill_gaps(v) d...
158939f6436a4c9b5a13a18567ee6061e71df51c
16,524
import torch def reward(static, tour_indices): """ Euclidean distance between all cities / nodes given by tour_indices """ # Convert the indices back into a tour idx = tour_indices.unsqueeze(1).expand(-1, static.size(1), -1) tour = torch.gather(static.data, 2, idx).permute(0, 2, 1) # Ens...
f7197bcfb3699cafa4df3c1430b4f9ee1bf53242
16,525
def valid_review_queue_name(request): """ Given a name for a queue, validates the correctness for our review system :param request: :return: """ queue = request.matchdict.get('queue') if queue in all_queues: request.validated['queue'] = queue return True else: _t...
fc6ef2fb728b18ce84669736f0e4ec1f020ea2bf
16,526
def get_best_straight(possible_straights, hand): """ get list of indices of hands that make the strongest straight if no one makes a straight, return empty list :param possible_straights: ({tuple(str): int}) map tuple of connecting cards --> best straight value they make :param hand: (set(s...
f2a470ef3033cac27cb406702daead42d59683aa
16,528
from django.shortcuts import render_to_response, RequestContext def stats(request): """ Display statistics for the web site """ views = list(View.objects.all().only('internal_url', 'browser')) urls = {} mob_vs_desk = { 'desktop': 0, 'mobile': 0 } for view in views: if is_mobi...
3b63250e6ce3c9ddd09ec8d19c9961b22bfab62a
16,529
def build_argparser(): """ Builds argument parser. :return argparse.ArgumentParser """ banner = "%(prog)s - generate a static file representation of a PEP data repository." additional_description = "\n..." parser = _VersionInHelpParser( description=banner, epilog=a...
f33679c82a1499db83caf3473b0e5403ebfa52fe
16,530
def abc19(): """Solution to exercise C-1.19. Demonstrate how to use Python’s list comprehension syntax to produce the list [ a , b , c , ..., z ], but without having to type all 26 such characters literally. """ a_idx = 97 return [chr(a_idx + x) for x in range(26)]
c9bb948ad57ddbc138dfbc0c481fabb45de620ba
16,531
def filter_words(data: TD_Data_Dictionary): """This function removes all instances of Key.ctrl from the list of keys and any repeats because of Press and Realese events""" # NOTE: We may just want to remove all instances of Key.ctrl from the list and anything that follows that keys = data.get_letters() ...
fb34e1758c83af0e30b5ae807a3f852ab7e3be29
16,533
from typing import Dict def check_url_secure( docker_ip: str, public_port: int, *, auth_header: Dict[str, str], ssl_context: SSLContext, ) -> bool: """ Secure form of lovey/pytest/docker/compose.py::check_url() that checks when the secure docker registry service is operational. Ar...
ebdc8f4d175f3be70000022424382f71d9fd73b5
16,534
def ResNet101(pretrained=False, use_ssld=False, **kwargs): """ ResNet101 Args: pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. If str, means the path of the pretrained model. use_ssld: bool=False. Whether using distillation pretrain...
0277c59f9b60d5c6127fb1021eb71b10691bd0f8
16,535
def LineTextInCurrentBuffer( line_number ): """ Returns the text on the 1-indexed line (NOT 0-indexed) """ return vim.current.buffer[ line_number - 1 ]
8c3b51a48e25e8955a00d89619da9e191612861a
16,536
def imported_instrumentor(library): """ Convert a library name to that of the correlated auto-instrumentor in the libraries package. """ instrumentor_lib = "signalfx_tracing.libraries.{}_".format(library) return get_module(instrumentor_lib)
db26277b23f989d8d5323c7c6bde0905b1e2f5ef
16,537
from datetime import datetime def parse_runtime(log_file): """ Parse the job run-time from a log-file """ with open(log_file, 'r') as f: for line in f: l0 = line.rstrip("\n") break l1 = tail(log_file, 1)[0].rstrip("\n") l0 = l0.split()[:2] l1 = l1.split()[:2] ...
75a5a80409918779173eb1e80d6b3f95abf242cb
16,539
def calculateEMA(coin_pair, period, unit): """ Returns the Exponential Moving Average for a coin pair """ closing_prices = getClosingPrices(coin_pair, period, unit) previous_EMA = calculateSMA(coin_pair, period, unit) constant = (2 / (period + 1)) current_EMA = (closing_prices[-1] * (2 / (1...
ec884f89c2e8e64ada4384767251d6722c7b63c8
16,540
def euler_method(r0, N): """ euler_method function description: This method computes the vector r(t)'s using Euler's method. Args: r0 - the initial r-value N - the number of steps in each period """ delta_t = (2*np.pi)/N # delta t r = np.zeros((5*N, 2)) # 5Nx...
6ac3deae5cdb5ce84fa19433b55de80bf04ddf47
16,541
def main_menu(found_exists): """prints main menu and asks for user input returns task that is chosen by user input""" show_main_menu(found_exists) inp = input(">> ") if inp == "1": return "update" elif inp == "2": return "show_all" elif inp == "3": return "s...
61d0bda6a1ddf8bf70a79ff6e7488601d781c5fc
16,542
def fromPsl(psl, qCdsRange=None, inclUnaln=False, projectCds=False, contained=False): """generate a PairAlign from a PSL. cdsRange is None or a tuple. In inclUnaln is True, then include Block objects for unaligned regions""" qCds = _getCds(qCdsRange, psl.qStrand, psl.qSize) qSeq = _mkPslSeq(psl.qName, p...
f1da225d53f36abf5d10589077de934f13c1ca2a
16,543
from typing import Optional def get_graph(identifier: str, *, rows: Optional[int] = None) -> pybel.BELGraph: """Get the graph surrounding a given GO term and its descendants.""" graph = pybel.BELGraph() enrich_graph(graph, identifier, rows=rows) return graph
fc004ebd3cdfa70edd01b611987dfd48306ceb80
16,545
def root_histogram_shape(root_hist, use_matrix_indexing=True): """ Return a tuple corresponding to the shape of the histogram. If use_matrix_indexing is true, the tuple is in 'reversed' zyx order. Matrix-order is the layout used in the internal buffer of the root histogram - keep True if reshaping t...
8df83a84f0a3b12bab248949042cd2df5df6f53e
16,548
from typing import Union def get_weather_sensor_by( weather_sensor_type_name: str, latitude: float = 0, longitude: float = 0 ) -> Union[WeatherSensor, ResponseTuple]: """ Search a weather sensor by type and location. Can create a weather sensor if needed (depends on API mode) and then inform the r...
b4feb0a75709d1bf27378df6d90420c74e36646c
16,550
import six def _npy_loads(data): """ Deserializes npy-formatted bytes into a numpy array """ logger.info("Inside _npy_loads fn") stream = six.BytesIO(data) return np.load(stream,allow_pickle=True)
5e9ee0a0d41403af0a8e1ed41f6d15a677d82c44
16,551
import dateutil def parse_string(string): """Parse the string to a datetime object. :param str string: The string to parse :rtype: `datetime.datetime` :raises: :exc:`InvalidDateFormat` when date format is invalid """ try: # Try to parse string as a date value = dateutil.parser...
6db2edad31f1febced496c92bfb2d7d76761850a
16,552
def get_elfs_oriented(atoms, density, basis, mode, view = serial_view()): """ Outdated, use get_elfs() with "mode='elf'/'nn'" instead. Like get_elfs, but returns real, oriented elfs mode = {'elf': Use the ElF algorithm to orient fingerprint, 'nn': Use nearest neighbor algorithm} """ ...
36b5abe66e9054ab49a25eca753d4a61148a1b1c
16,553
def error_logger(param=None): """ Function to get an error logger, object of Logger class. @param param : Custom parameter that can be passed to the logger. @return: custom logger """ logger = Logger('ERROR_LOGGER', param) return logger.get_logger()
ca6449c2e63ebdccbd7bd3993dc1d11375e66e29
16,555
def get_iou(mask, label): """ :param mask: predicted mask with 0 for background and 1 for object :param label: label :return: iou """ # mask = mask.numpy() # label = labels.numpy() size = mask.shape mask = mask.flatten() label = label.flatten() m = mask + label i = len(np...
9322d0184a3e28bdd1d5bf3214b7fbe8936d6a21
16,557
from typing import List from typing import Set from typing import Any def mean_jaccard_distance(sets: List[Set[Any]]) -> float: """ Compute the mean Jaccard distance for sets A_1, \dots A_n: d = \frac{1}{n} \sum_{i=1}^{n-1} \sum_{j=i+1}^n (1 - J(A_i, A_j)) where J(A, B) is the Jaccard index betwee...
efbfce8092e2e3a9b5b076c46a636dfa17e2d266
16,558
def nx_find_connected(graph, start_set, end_set, cutoff=np.inf): """Return the nodes in end_set connected to start_set.""" reachable = [] for end in end_set: if nx_is_reachable(graph, end, start_set): reachable.append(end) if len(reachable) >= cutoff: break ...
a3feb8a172bb610fa4416c6f4a4c0558540d2190
16,559
def svn_client_proplist(*args): """ svn_client_proplist(char target, svn_opt_revision_t revision, svn_boolean_t recurse, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return _client.svn_client_proplist(*args)
1cc82161292df7b9ba284397a0dcd55da9d0d7c1
16,560
def dev_transform(signal, input_path='../data/', is_denoised=True): """ normalization function that transforms each fature based on the scaling of the trainning set. This transformation should be done on test set(developmental set), or any new input for a trained neural network. Due to existence of ...
ce6dfe780bb724ae8036502d2b1d1828fce675dc
16,561
def moveTo(self, parent): """Move this element to new parent, as last child""" self.getParent().removeChild(self) parent.addChild(self) return self
40caa9681346db9a6cfb5c95fdb761a9f98e607a
16,562
from datetime import datetime def coerce_to_end_of_day_datetime(value): """ gets the end of day datetime equivalent of given date object. if the value is not a date, it returns the same input. :param date value: value to be coerced. :rtype: datetime | object """ if not isinstance(value...
374e7decf543e5fb40fb7714d4472cf4cfa48cb1
16,563
def greybody(nu, temperature, beta, A=1.0, logscale=0.0, units='cgs', frequency_units='Hz', kappa0=4.0, nu0=3000e9, normalize=max): """ Same as modified blackbody... not sure why I have it at all, though the normalization constants are different. """ h,k,c = unitdict[units]...
89cca39acf5659e8ab7b403c5747b19c119d0e51
16,564
import copy def GCLarsen_v0(WF, WS, WD, TI, pars=[0.435449861, 0.797853685, -0.124807893, 0.136821858, 15.6298, 1.0]): """Computes the WindFarm flow and Power using GCLarsen [Larsen, 2009, A simple Stationary...] Inputs ---------- WF: WindFarm Windfarm instance WS: list Ro...
a075074b0cee9b36fdf3411804ff4eff2f5fe63b
16,565
def guess_table_address(*args): """ guess_table_address(insn) -> ea_t Guess the jump table address (ibm pc specific) @param insn (C++: const insn_t &) """ return _ida_ua.guess_table_address(*args)
073773e33b5cf4c59f3a3c892d5a53320c2c1f4b
16,566
def get_elbs(account, region): """ Get elastic load balancers """ elb_data = [] aws_accounts = AwsAccounts() if not account: session = boto3.session.Session(region_name=region) for account_rec in aws_accounts.all(): elb_data.extend( query_elbs_for_account(acc...
32b059c7929b0adae3df7b8393fd062f5a281cc3
16,568
def likelihood_params(ll_mode, mode, behav_tuple, num_induc, inner_dims, inv_link, tbin, jitter, J, cutoff, neurons, mapping_net, C): """ Create the likelihood object. """ if mode is not None: kernel_tuples_, ind_list = kernel_used(mode, behav_tuple, num_induc, inner_dims)...
2e817c4fdfdd9a65d138f61166ef8fbb3154460b
16,570
def is_num_idx(k): """This key corresponds to """ return k.endswith("_x") and (k.startswith("tap_x") or k.startswith("sig"))
bd4ed2c9c4a24ae423ec6c738d99b31ace6ec267
16,571
def convert_to_boolarr(int_arr, cluster_id): """ :param int_arr: array of integers which relate to no, one or multiple clusters cluster_id: 0=Pleiades, 1=Meingast 1, 2=Hyades, 3=Alpha Per, 4=Coma Ber """ return np.array((np.floor(int_arr/2**cluster_id) % 2), dtype=bool)
c769ca07ea32a9e0ab0d230cd3574e5b71434de4
16,572
def serialize(root): # """Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Des...
a2bec43b384302d5218e8c62c83bc069be3bcbd3
16,573
def ensure_daemon(f): """A decorator for running an integration test with and without the daemon enabled.""" def wrapper(self, *args, **kwargs): for enable_daemon in [False, True]: enable_daemon_str = str(enable_daemon) env = { "HERMETIC_ENV": "PANTS_PANTSD,PANTS...
d9005c48d489b8b5da1f9687b78d1f455aaf3d62
16,574
from adaptivefiltering.pdal import execute_pdal_pipeline from adaptivefiltering.pdal import PDALInMemoryDataSet import json def reproject_dataset(dataset, out_srs, in_srs=None): """Standalone function to reproject a given dataset with the option of forcing an input reference system :param out_srs: Th...
0380442a837f89bbf06d0d1b5e9917e7309876ad
16,575
def conditional(condition, decorator): """ Decorator for a conditionally applied decorator. Example: @conditional(get_config('use_cache'), ormcache) def fn(): pass """ if condition: return decorator else: return lambda fn: fn
7c17ad3aaacffd0008ec1cf66871ea6755f7869a
16,576
import statistics def variance(data, mu=None): """Compute variance over a list.""" if mu is None: mu = statistics.mean(data) return sum([(x - mu) ** 2 for x in data]) / len(data)
92f89d35c2ae5abf742b10ba838a381d6f74e92c
16,577
def make_note(outfile, headers, paragraphs, **kw): """Builds a pdf file named outfile based on headers and paragraphs, formatted according to parameters in kw. :param outfile: outfile name :param headers: <OrderedDict> of headers :param paragraphs: <OrderedDict> of paragraphs :param kw: keyword...
d9bc331167649210cf18e76bcff4099817c28458
16,578
import stat def output_file_exists(filename): """Check if a file exists and its size is > 0""" if not file_exists(filename): return False st = stat(filename) if st[stat_module.ST_SIZE] == 0: return False return True
ad2f3a7451feefd32fe98da7fc3bfca9852b080c
16,579
def IMF_N(m,a=.241367,b=.241367,c=.497056): """ returns number of stars with mass m """ # a,b,c = (.241367,.241367,.497056) # a=b=c=1/3.6631098624 if .1 <= m <= .3: res = c*( m**(-1.2) ) elif .3 < m <= 1.: res = b*( m**(-1.8) ) elif 1. < m <= 100.: # res = a*( m*...
4d120af2840a793468335cddd867f6d29940d415
16,580
def features_disable(partial_name, partial_name_field, force, **kwargs): """Disable a feature""" mode = "disable" params = {"mode": "force"} if force else None feature = _okta_get("features", partial_name, selector=_selector_field_find(partial_name_field, partial_name)) featu...
5477a43ad2f849669a6a209abfc835f0f4ee453a
16,581
def _get_images(): """Get the official AWS public AMIs created by Flambe that have tag 'Creator: [email protected]' ATTENTION: why not just search the tags? We need to make sure the AMIs we pick were created by the Flambe team. Because of tags values not being unique, anyone can create a public AMI ...
975596ff9eb1c9c0864cadb41edc2b1a4d009790
16,582
def ar_coefficient(x, param): """ This feature calculator fits the unconditional maximum likelihood of an autoregressive AR(k) process. The k parameter is the maximum lag of the process .. math:: X_{t}=\\varphi_0 +\\sum _{{i=1}}^{k}\\varphi_{i}X_{{t-i}}+\\varepsilon_{t} For the config...
a7a7171a44055d23457fd622d7e893f839f17bcf
16,583
from faker import Faker import random def address_factory(sqla): """Create a fake address.""" fake = Faker() # Use a generic one; others may not have all methods. addresslines = fake.address().splitlines() areas = sqla.query(Area).all() if not areas: create_multiple_areas(sqla, random.ran...
91f4558887025841d99ab6e65795111bbc804238
16,585
from pm4py.util import constants from pm4py.algo.discovery.dfg.adapters.pandas.df_statistics import get_dfg_graph from pm4py.statistics.start_activities.pandas import get as start_activities_module from pm4py.statistics.end_activities.pandas import get as end_activities_module from pm4py.algo.discovery.dfg.variants imp...
df8d9669c7e2a4cd3170cb1c5a1ecc7e7811649e
16,586
import warnings def mifs(data, target_variable, prev_variables_index, candidate_variable_index, **kwargs): """ This estimator computes the Mutual Information Feature Selection criterion. Parameters ---------- data : np.array matrix Matrix of data set. Columns are variables, rows are obser...
058ebdbb831d7fb52c4b5f053ba7bb8a1ce7f144
16,587
def input_thing(): """输入物品信息""" name_str, price_str, weight_str = input('请输入物品信息(名称 价格 重量):').split() return name_str, int(price_str), int(weight_str)
2a986e9479e8e4262cfab89f258af3536c5fefe3
16,588
def extract_features_mask(img, mask): """Computes law texture features for masked area of image.""" preprocessed_img = laws_texture.preprocess_image(img, size=15) law_images = laws_texture.filter_image(preprocessed_img, LAW_MASKS) law_energy = laws_texture.compute_energy(law_images, 10) energy_feat...
e184695fb2879cf9fd418e7110498717585b4878
16,589
def construct_grid_with_k_connectivity(n1,n2,k,figu = False): """Constructs directed grid graph with side lengths n1 and n2 and neighborhood connectivity k""" """For plotting the adjacency matrix give fig = true""" def feuclidhorz(u , v): return np.sqrt((u[0] - (v[0]-n2))**2+(u[1] - v[...
46b690f02c4f025719424582acecff43580543da
16,590
import array def _optimal_shift(pos, r_pad, log): """ Find the shift for the periodic unit cube that would minimise the padding. """ npts, ndim = pos.shape # +1 whenever a region starts, -1 when it finishes start_end = empty(npts*2, dtype=np.int32) start_end[:npts] = 1 start_end[...
cac3c56307ea3d240ebe838ea4d26bb38c62dc3c
16,592
def ShowActStack(cmd_args=None): """ Routine to print out the stack of a specific thread. usage: showactstack <activation> """ if cmd_args == None or len(cmd_args) < 1: print "No arguments passed" print ShowAct.__doc__.strip() return False threadval = kern.GetValueFromA...
43b0eca326465fe9dc7b0207ba448d75da7e9889
16,593
import json def load_request(possible_keys): """Given list of possible keys, return any matching post data""" pdata = request.json if pdata is None: pdata = json.loads(request.body.getvalue().decode('utf-8')) for k in possible_keys: if k not in pdata: pdata[k] = None # ...
b21c503fac56398be6745a10fb95889128c6e2b2
16,595
import random def get_random_tcp_start_pos(): """ reachability area: x = [-0.2; 0.4] y = [-0.28; -0.1] """ z_up = 0.6 tcp_x = round(random.uniform(-0.2, 0.4), 4) tcp_y = round(random.uniform(-0.28, -0.1), 4) start_tcp_pos = (tcp_x, tcp_y, z_up) # start_tcp_pos = (-0.2, -0.28, ...
adf87dec45bf5a81c321f94c93d45a67f0aeff0d
16,596
def CalculateChiv3p(mol): """ ################################################################# Calculation of valence molecular connectivity chi index for path order 3 ---->Chiv3 Usage: result=CalculateChiv3p(mol) Input: mol is a molecule object...
27405fce52540a0de9c4c1c2d5a35454681554fa
16,597
from typing import Tuple from typing import Optional def coerce(version: str) -> Tuple[Version, Optional[str]]: """ Convert an incomplete version string into a semver-compatible Version object * Tries to detect a "basic" version string (``major.minor.patch``). * If not enough components can be fou...
e712533aa05444ad47403fc10e7f2ec29b8132ec
16,598
def choose_wyckoff(wyckoffs, number): """ choose the wyckoff sites based on the current number of atoms rules 1, the newly added sites is equal/less than the required number. 2, prefer the sites with large multiplicity """ for wyckoff in wyckoffs: if len(wyckoff[0]) <= number: ...
14b276d8aa50e84f47d77f6796e193cc96ddd0a9
16,599
def _to_system(abbreviation): """Converts an abbreviation to a system identifier. Args: abbreviation: a `pronto.Term.id` Returns: a system identifier """ try: return { 'HP': 'http://www.human-phenotype-ontology.org/' }[abbreviation] except KeyError: ...
f43942b242e67866028a385e6614133dc25b31b0
16,600
from typing import Union def apply_gate(circ: QuantumCircuit, qreg: QuantumRegister, gate: GateObj, parameterise: bool = False, param: Union[Parameter, tuple] = None): """Applies a gate to a quantum circuit. More complicated gates such as RXX gates should be decomposed into single qubit ga...
0babd68efb8bae67c5f610bcca3eb9f3b67630ad
16,601
from typing import Tuple import codecs def preprocess_datasets(data: str, seed: int = 0) -> Tuple: """Load and preprocess raw datasets (Yahoo! R3 or Coat).""" if data == 'yahoo': with codecs.open(f'../data/{data}/train.txt', 'r', 'utf-8', errors='ignore') as f: data_train = pd.read_csv(f, ...
78a7bfe7968ad47f797728ffb43c804ab8af6298
16,602
def loadSentimentVector(file_name): """ Load sentiment vector [Surprise, Sorrow, Love, Joy, Hate, Expect, Anxiety, Anger] """ contents = [ line.strip('\n').split() for line in open(file_name, 'r').readlines() ] sentiment_dict = { line[0].decode('utf-8'): [float(w) for w in li...
5d0d1f4598eeed455d080236720adcae357b6485
16,603
def unique_boxes(boxes, scale=1.0): """Return indices of unique boxes.""" v = np.array([1, 1e3, 1e6, 1e9]) hashes = np.round(boxes * scale).dot(v) _, index = np.unique(hashes, return_index=True) return np.sort(index)
fc9ab64356192828659f025af6aa112205fc838c
16,604
def HEX2DEC(*args) -> Function: """ Converts a signed hexadecimal number to decimal format. Learn more: https//support.google.com/docs/answer/3093192 """ return Function("HEX2DEC", args)
b4741d02acae7169854d1193ae5b43f6736257dc
16,606
def find_edges(mesh, key): """ Temp replacement for mesh.findEdges(). This is painfully slow. """ for edge in mesh.edges: v = edge.vertices if key[0] == v[0] and key[1] == v[1]: return edge.index
98247b64a0e5671a7dbbf314f314cef2c5c8aae3
16,607
def thumbnail(link): """ Returns the URL to a thumbnail for a given identifier. """ targetid, service = _targetid(link), _service(link) if targetid: if service in _OEMBED_MAP: try: return _embed_json(service, targetid)["thumbnail_url"] except (ValueEr...
9ca78af2a65a41a70fef73c35383ae9214fb2d96
16,608
def valve_gas_cv(m_dot, p_1, p_2, m_molar, T): """Find the required valve Cv for a given mass flow and pressure drop. Assumes that a compressible gas is flowing through the valve. Arguments: m_dot (scalar): Mass flow rate [units: kilogram second**-1]. p_1 (scalar): Inlet pressure [units: p...
07bd3f45392e03eb6744b98a3fde022aa517c4fc
16,609
def frequency_based_dissim(record, modes): """ Frequency-based dissimilarity function inspired by "Improving K-Modes Algorithm Considering Frequencies of Attribute Values in Mode" by He et al. """ list_dissim = [] for cluster_mode in modes: sum_dissim = 0 for i in range(len(recor...
80e21763d6f90ddc5a448f46247fd12253de5dbb
16,610
def _process_create_group(event: dict) -> list: """ Process CreateGroup event. This function doesn't set tags. """ return [event['responseElements']['group']['groupName']]
978b3ffc3c4aa72165914b79dc06cb7691c5c5a5
16,611
from typing import Any from typing import List def tree_labels(t: Node): """Collect all labels of a tree into a list.""" def f(label: Any, folded_subtrees: List) -> List: return [label] + folded_subtrees def g(folded_first: List, folded_rest: List) -> List: return folded_first + folded_r...
7ad1703a090cd761a99cd5323c9258e8d2d551b8
16,612
def find_best_split(rows): """Find the best question to ask by iterating over every feature / value and calculating the information gain.""" best_gain = 0 # keep track of the best information gain best_question = None # keep train of the feature / value that produced it current_uncertainty = gini(...
9b197c99b41e64e37b499b5d4b3c7758cda3b56e
16,613
def pad_data(data, context_size, target_size, pad_at_begin= False): """ Performs data padding for both target and aggregate consumption :param data: The aggregate power :type data: np.array :param context_size: The input sequence length :type context_size: int :param target_size: The target...
1b698a849a4ca82d87ce6c5711220b61cd21252b
16,614
def egg_translator(cell): """If the cell has the DNA for harboring its offspring inside it, granting it additional food and protection at the risk of the parent cell, it is an egg. Active DNA: x,A,(C/D),x,x,x """ dna = cell.dna.split(',') if dna[1] == 'A' and dna[2] == 'C': return True ...
af0d9097c8a0b5002722c79d6ec8262a66cc375d
16,617
def all_different_cst(xs, cst): """ all_different_cst(xs, cst) Ensure that all elements in xs + cst are distinct """ return [AllDifferent([(x + c) for (x,c) in zip(xs,cst)])]
dfc75a54a92a4c8c2ef76af74250b9125c9bb647
16,618
def processing(task, region: dict, raster: str, parameters: dict): """ Cuts the raster according to given region and applies some filters in order to find the district heating potentials and related indicators. Inputs : * region : selected zone where the district heating potential is studi...
63a5548e886b575011e716e05a589715f027c316
16,619
import random def randbit(): """Returns a random bit.""" return random.randrange(2)
4b47101df7368b7cb423920e6a5338b76ab4ecaa
16,620
def calc_points(goals, assists): """ Calculate the total traditional and weighted points for all players, grouped by player id. Author: Rasmus Säfvenberg Parameters ---------- goals : pandas.DataFrame A data frame with total goals and weighted assists per player. assist...
1801cf2602a473bdf532e1c0ee58b883dc3e79d1
16,621
import io import base64 def file_to_base64(path): """ Convert specified file to base64 string Args: path (string): path to file Return: string: base64 encoded file content """ with io.open(path, 'rb') as file_to_convert: return base64.b64encode(file_to_convert.read())
0c942f8f4d29943c5a3aac6c954d9e2b1b2898a3
16,623
def get_simverb(subset=None): """ Get SimVerb-3500 data :return: (pairs, scores) """ simverb = [] if subset == 'dev': name = '500-dev' elif subset == 'test': name = '3000-test' else: name = '3500' with open('../data/SimVerb-3500/SimVerb-{}.txt'.format(name)) a...
5cec49bd232a883836029b8b011f09f360176910
16,624
def sample_image(size, min_r, max_r, circles, squares, pixel_value): """Generate image with geometrical shapes (circles and squares). """ img = np.zeros((size, size, 2)) loc = [] if pixel_value is None: vals = np.random.randint(0, 256, circles + squares) else: vals = [pixel_value...
25ab1afcd7256bc07ee55ac2e12cf9d834cb798c
16,625
def host_allocations(auth): """Retrieve host allocations""" response = API.get(auth, '/os-hosts/allocations') return response.json()['allocations']
505eeb0502f6480445ec5dff1cd3203eda96d475
16,626
def rosenbrock_grad(x, y): """Gradient of Rosenbrock function.""" return (-400 * x * (-(x ** 2) + y) + 2 * x - 2, -200 * x ** 2 + 200 * y)
c7acf0bbe11a6d1cbb38b6853eb1b508e3846657
16,627
def extractYoujinsite(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if '[God & Devil World]' in item['tags'] and (chp or vol): return buildReleaseMessageWithType(item, 'Shenmo Xitong', vol, chp, frag=frag, postfix=postfix) if '[LBD&A]' in item['tags'] and (chp or vol):...
11463288cdcc7268b0b4657934dd8872a7d36580
16,629
def get_logger() -> Logger: """ This function returns the logger for this project """ return getLogger(LOGGER_NAME)
33e11a06c357552c35f9ef089fd303ad15db0884
16,632
import json def write_guess_json(guesser, filename, fold, run_length=200, censor_features=["id", "label"], num_guesses=5): """ Returns the vocab, which is a list of all features. """ vocab = [kBIAS] print("Writing guesses to %s" % filename) num = 0 with open(filename, 'w') as outfil...
9f0055289ff462b0b3c067ea1e0a68c66a74136c
16,633
def upgrade_to_4g(region, strategy, costs, global_parameters, core_lut, country_parameters): """ Reflects the baseline scenario of needing to build a single dedicated network. """ backhaul = '{}_backhaul'.format(strategy.split('_')[2]) sharing = strategy.split('_')[3] geotype = region['...
947afef6d550b9022109c665fc311511f428e9f8
16,634