content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def prep_data_for_feature_gen(data): """Restructure OANDA data to use it for TA-Lib feature generation""" inputs = { 'open': np.array([x['openMid'] for x in data]), 'high': np.array([x['highMid'] for x in data]), 'low': np.array([x['lowMid'] for x in data]), 'close': np.array([x[...
a9666a24486e19196c2c13ebd198675207fc8d32
3,635,885
def matriz_krylov(A, x, n_iters=None): """Genera una matriz de krylov dada una matriz A y un vector x. Cada columna de la matriz es la iteración i de A^i*x. Args: A (matriz): Matriz de aplicación x (vector): Vector base n_iters (int, optional): Número de iteraciones. Por defecto es el n...
5463ca2db8d1d638f5ef7ab0ee258416dceccd62
3,635,886
def test_case_result_score(answers, user_test_id): """ Calculate result score for test. Check every user's answer (check_answer), calculate number of correct answers. @param answers: dict of pairs question_id and list of answers. @param user_test_id: UserTestCase object id --> int @return: res...
1d4efae6f50a5d9cc4ed655e47056d066c53abac
3,635,887
def AtensDeltaV(df): """Delta V calculation for Atens asteroids, where a < 1.""" df['ut2'] = 2 - 2*np.cos(df.i/2)*np.sqrt(2*df.Q - df.Q**2) df['uc2'] = 3/df.Q - 1 - (2/df.Q)*np.sqrt(2 - df.Q) df['ur2'] = 3/df.Q - 1/df.a - ( (2/df.Q)*np.cos(df.i/2)*np.sqrt(df.a*(1-df.e**2)/df.Q)) return df
6996a921020b8474dc119c0384062288d1d138b7
3,635,888
from pypy.interpreter import gateway def init__builtin__(space): """NOT_RPYTHON""" ##SECTION## ## filename '<codegen /Users/steve/Documents/MIT TPP/2009-2010/6.893/project/pypy-dist/pypy/interpreter/gateway.py:824>' ## function 'pypy_init' ## firstlineno 2 ##SECTION## # global declarations # global object g3...
c583fd15c33aeefddf67116aff63b30d26edb366
3,635,889
import scipy import numpy def CalculateXuIndex(mol): """ ################################################################# Calculation of Xu index ---->Xu Usage: result=CalculateXuIndex(mol) Input: mol is a molecule object Output: resul...
0123f3ea82bb89ef7923e7f1638aafd8fbfe9fb0
3,635,890
def register_dataclass(registry: ServiceRegistry, target, for_, context=None): """ Generic injectory factory for dataclasses """ # Note: This function could be a decorator which already knows # the registry, has all the targets, and can do them in one # container that it makes. For example: # from ...
50453755c6c132cf4cf38fd727935c306dc7082d
3,635,891
async def async_setup_entry(hass, config_entry): """Set up the UniFi component.""" if DOMAIN not in hass.data: hass.data[DOMAIN] = {} controller = UniFiController(hass, config_entry) controller_id = get_controller_id_from_config_entry(config_entry) hass.data[DOMAIN][controller_id] = contr...
52c4409532c10899a9b9b621b762bf92b3a58b59
3,635,892
from typing import Union from typing import Optional import warnings def dataset_to_xy( dataset: Dataset, target_columns: Union[str, list], qid_column: Optional[str], ): """Convert Merlin Dataset to XGBoost DMatrix""" df = dataset.to_ddf() qid = None if qid_column: df = df.sort_va...
201e5bf5513f35bd683bfad7bcf4ecb8b255cd93
3,635,894
def clean_data(df): """Clean data included in the DataFrame and transform categories part INPUT df -- type pandas DataFrame OUTPUT df -- cleaned pandas DataFrame """ categories = df['categories'].str.split(pat=';', expand=True) row = categories.loc[0] colnames = [] for entry in r...
40319f0f739e532bd559f14c70d988b7257c6fa3
3,635,895
def compute_timeline(agents, ts_tuple, dep_ivs): """ Compute the timeline of events that can occur in the field. Given the departure intervals of the agents, this function computes a common timeline of events that captures all possible occurances of events in the field. Parameters ---------- agents: A list ...
12d99be139a4327552231dc2802d165d114139fe
3,635,896
import unittest def test_suite(): """Test suite including all test suites""" testSuite = unittest.TestSuite() testSuite.addTest(test_randomdata.test_suite()) return testSuite
8ac9cfcfebf9255f2cab01db9d4a1a53a3d24871
3,635,897
def eHealthClass_setupPulsioximeterForNextReading(): """eHealthClass_setupPulsioximeterForNextReading()""" return _ehealth.eHealthClass_setupPulsioximeterForNextReading()
d48cfd85752a75ca27e33794e18058a89f03a291
3,635,898
from typing import Type def meet_types(s: Type, t: Type) -> ProperType: """Return the greatest lower bound of two types.""" if is_recursive_pair(s, t): # This case can trigger an infinite recursion, general support for this will be # tricky so we use a trivial meet (like for protocols). ...
627920538076f3e15bec341bd32035940f61013c
3,635,900
def delete_context(id): """ Delete the requested context object. This WILL delete the index, but any alias of the same name. :param id: str, the unique ID of the requested Context :return: aknowledge message as JSON """ # get the object ctx = Context.get(id) ctx.delete(delete_index=...
d14c21a5ba09794c32df331e629d0b3ee9c9f5da
3,635,901
def get_relative_percentage(new, last): """ :param new: float New value :param last: float Last value :return: float in [0, 100] Percentage (with errors handling) """ ratio = get_ratio(new, last) relative_ratio = ratio - 1.0 return 100.0 * relative_ratio
c563ec1406469acdf76d6052c2187fa20efe5bf2
3,635,903
def parse_data_name(line): """ Parses the name of a data item line, which will be used as an attribute name """ first = line.index("<") + 1 last = line.rindex(">") return line[first:last]
53a9c7e89f5fa5f47dad6bfc211d3de713c15c67
3,635,904
def api_error(api, error): """format error message for api error, if error is present""" if error is not None: return "calling: %s: got %s" % (api, error) return None
a9269a93d51e3203646886a893998ffec6488c95
3,635,905
from datetime import datetime import time import re def dailyImage(request,date=None): """ returns daily image html page for date """ today = datetime.datetime.today() earliest = Image.pub_dates.earliest() if date is None: this_date = datetime.datetime.strftime(today,'%F') else: ...
9562fca76317614830f9940031c42efa6fa99e14
3,635,906
def get_depolarizing_channel(T, t_gate=10e-9): """Get the depolarizing channel Args: T (float): Decoherence parameter (seconds) """ assert T > 0 assert t_gate > 0 gamma = 1 - pow(np.e, -1 / T * t_gate) noise_model = depolarize(gamma) return noise_model
22a42a2f72f1a0dc1a1c828d755b37148517302f
3,635,907
import numpy def censor_signal(signal, filtered_signal, fold, left_trim, right_trim_percent): """Finds points where residual is greater than the given fold, and trims given number of point from the left, and some multiple of that from the right. """ ltrim = int(left_trim) rtrim = int(left_trim * right_trim_perce...
79c9c6f64d22c075b054aae9cb95102d89d77531
3,635,908
def get_choices(state, attribute_name): """ Return a list of the choices (excluding separators) in the SelectionCallbackProperty. """ choices = [] labels = [] display_func = getattr(type(state), attribute_name).get_display_func(state) if display_func is None: display_func = str ...
2716e3d850d62cf9018e9ec68e6db9cfe1fe721b
3,635,909
def compatibility_factors_to_coo(ncf: dict, nreg: dict): """ ncf : nodal_compatibility_factors """ nN = len(ncf) widths = np.zeros(nN, dtype=np.int32) for iN in prange(nN): widths[iN] = len(nreg[iN]) shapes = (widths**2).astype(np.int64) N = np.sum(shapes) data = np.zeros(N, ...
92995712ff559c0b44f362c0c2c56b7a6891afeb
3,635,910
from typing import Type def combine_complex(output_arr_t): """ Returns a transformation that joins two real inputs into complex output (1 output, 2 inputs): ``output = real + 1j * imag``. """ input_t = Type(dtypes.real_for(output_arr_t.dtype), shape=output_arr_t.shape) return Transformation( ...
7bb5b0c2ad840487983afe8e0574bdce4cdf8774
3,635,911
def quantity_unwrapped(units, multiplier=1.0): """ A decorator for setters to extract the plain device value from the quantity. """ def wrap(f): @wraps(f) def wrapped(self, value): value.assert_dimensions(units) return f(self, value.value * multiplier) return wrapped return wrap
8fcbdcd52ed2538d6ec7fcc8f8986e0047909b7e
3,635,912
import torch def displacement_error(pred_fut_traj, fut_traj, consider_ped=None, mode="sum"): """ Compute ADE Input: - pred_fut_traj: Tensor of shape (seq_len, batch, 2). Predicted trajectory. [12, person_num, 2] - fut_traj: Tensor of shape (seq_len, batch, 2). Groud truth future trajectory. -...
8ae4c0d9b10b7f0f45b9716a86f02b2b0e66ea71
3,635,913
import _json def __json(informations: _Dict[int, ErrorInfo]) -> str: """制作 json 格式的数据""" errcodes: _Dict[int, _Dict[str, str]] = dict() for code, info in informations.items(): errcodes[code] = dict(info._asdict()) return _json.dumps(errcodes, indent=4, sort_keys=True, ensure_ascii=False)
8f3c31a978d27e1874d1082b7458cabbe0764251
3,635,914
import random def get_average_pairwise_distance(df, n=1000): """Get average pairwise distance for a group of embeddings. Smaller number means closer together. With n=1000, this function is generally precise within 0.01 Parameters ---------- df: DataFrame input data n: int ...
70f7c547c87718fee03aa6a413dc0c4b0072ab19
3,635,915
def thorpe_scales(S, T, p, lat, lon, axis=-1): """ Thorpe scales simplified for estimating dissipation rates Parameters ---------- S : Practical Salinity T : Practical Temperature P : Pressure Measurements -- NOT A NORMALIZED PRESSURE GRID lat : Latitude lon : Longitude Returns...
7d8f8d711e081e3fe58b25508a1b62c576eb4062
3,635,916
from typing import Dict def v() -> Dict[TState, float]: """Initial state values for use in tests.""" return {"A": 3.0, "B": 1.0, "C": 0.0}
5bcda636a3b94e5204e2ed5adde641862b87a240
3,635,917
def iter_listeners(event): """Return an iterator for all the listeners for the event provided.""" ctx = stack.top return ctx.app.extensions.get('plugin_manager')._event_manager.iter(event)
1774062c69647beb703a5a4a087c362703515eb7
3,635,919
def _compute_box_size(topology, density): """ Lookup the masses in the `topology` and compute a cubic box that matches the `density` given the number of molecules defined in the topology. Units are nm Parameters: ----------- topology: :class:`polyply.src.topology` density: float ...
f4ae82e174b2d0673c331a521b2caec91f94af8f
3,635,920
def build_template(ranges, template, build_date, use_proxy=False, redir_target=""): """ Input: output of process_<provider>_ranges(), output of get_template() Output: Rendered template string ready to write to disk """ return template.render( ranges=ranges["ranges"], header_comments=...
ec10897cb6f92e2b927f4ef84511a7deab8cd37d
3,635,921
def _get_named_value(obj, name): """ Utility function that returns the value of the given copasi object :param obj: a copasi object, that could be a compartment, species, parameter, reaction :param name: the reference name to return :return: """ is_metab = isinstance(obj, COPASI.CMetab) is_...
a69bf15a9ed78da02687172e5e4cc38adbf4415c
3,635,922
def lang_add(cursor, lang, trust): """Adds language for db""" if trust: query = 'CREATE TRUSTED LANGUAGE "%s"' % lang else: query = 'CREATE LANGUAGE "%s"' % lang executed_queries.append(query) cursor.execute(query) return True
c7157d83aab143b4628dc38f64abcfb84cbacbf1
3,635,923
import textwrap def _strip_and_dedent(s): """For triple-quote strings""" return textwrap.dedent(s.lstrip('\n').rstrip())
8d392daede103cb2a871b94d415c705fa51d7cef
3,635,924
def calculate_stress_by_matrix_rotation(wlsq_strain, U): """ Calculate the intra-granular stresses by applying the sample system stiffnes matrix for a given grain and z-slice to the corresponding strains. :param wlsq_strain: Strains as a list of numpy arrays, where each list contains a strain component...
88a570dcae97de0ac0ee746af805f2b90a1a7c7c
3,635,925
def fundamentals_dataframe( timeframe: Timeframe, stock: str, ld: LazyDictionary ) -> pd.DataFrame: """Return a dict of the fundamentals plots for the current django template render to use""" df = ld["stock_df"] # print(df) df["change_in_percent_cumulative"] = df[ "change_in_percent" ].c...
52883783049c3f0e097f61334b67ec6aa085c8cc
3,635,926
def returns_normally(expr): """For use inside `test[]` and its sisters. Assert that `expr` runs to completion without raising or signaling. Usage:: test[returns_normally(myfunc())] """ # The magic is, `test[]` lifts its expr into a lambda. When the test runs, # our arg gets evaluated ...
469447c704247f46a0cebf1b582c08d36f53383f
3,635,927
from datetime import datetime def verify_presentation_state_content(presentation_state): """Helper function to verify that the content in presentation_state is appropriate to create a basic text SR object ---------- Parameters """ if not isinstance(presentation_state, dict): print("in...
e495ff51854a18a5c87be3a3734aac0f6a671cf7
3,635,928
def getProfile(request): """ Return MY profile for editing. """ profile = UserProfile.objects.get( user=request.user ) return profile.ajax()
fbb6859b3448387e96f698148899d24e1d7fb20d
3,635,929
import re def finder(input, collection, fuzzy=False, accessor=lambda x: x): """ Args: input (str): A partial string which is typically entered by a user. collection (iterable): A collection of strings which will be filtered based on the `input`. fuzzy (bool): perform a fuz...
1bbe22f6b38f447f20071bd810cfee6e4e491f5f
3,635,930
def calc_rets(returns, weights): """ Calculate continuous return series for futures instruments. These consist of weighted underlying instrument returns, who's weights can vary over time. Parameters ---------- returns: pandas.Series or dict A Series of instrument returns with a Mult...
2974b02c82038d20982a6bb974912913ece61e89
3,635,931
def testMaze(n_training_trials, n_navigation_trials): """ No comments here. Look at single_maze_learning_agent.py for more details! """ ValueLearning.DBG_LVL = 0 move_distance = 0.29 nx = 6 ny = 6 n_fields = round(1.0 * (nx + 3) * (ny+3)) Hippocampus.N_CELLS_PER_FIELD = 4 n_cel...
f35093e5ee7f00aa547ce9a377f7d6d399070d76
3,635,932
def group_calc(df, single_group_func, group_col, sort_col=None, exclude_groups=None): """Performs a general function on a dataframe with distinct subsets. In a tidy, time series dataframe with multiple groups, say states, age groups, etc. there is often a need to perform an operation on each...
b33708e5d704b0de526ef27032aeaedc700f5bd5
3,635,933
def str2int(video_path): """ argparse returns and string althout webcam uses int (0, 1 ...) Cast to int if needed """ try: return int(video_path) except ValueError: return video_path
2d4714ec53304fb6cafabd5255a838b478780f8a
3,635,934
def describe_inheritance_rule(rule): """ Given a dictionary representing a koji inheritance rule (i.e., one of the elements of getInheritanceData()'s result), return a tuple of strings to be appended to a module's stdout_lines array conforming to the output of koji's taginfo CLI command, e.g.: ...
32eae010365d8fd5b253f23acf8104932773c7c1
3,635,935
def plot_cv_indices(cv, X, y, ax, lw=50): """Create a sample plot for indices of a cross-validation object.""" splits = list(cv.split(X=X, y=y)) n_splits = len(splits) # Generate the training/testing visualizations for each CV split for ii, (train, test) in enumerate(splits): # Fill in indi...
96102c6e886cecdd3b16380c58cb2596119c59f2
3,635,936
def find_colour(rgb): """Compare given rgb triplet to predefined colours to find the closest one""" # this cannot normally happen to an image that is processed automatically, since colours # are rbg by default, but it can happen if the function is called with invalid values if rgb[0] < 0 or rgb[0] > 25...
f2c6e2b7daa7fd45411376cfc64409486c18e252
3,635,937
def log_sum_exp(input, dim=None, keepdim=False): """Numerically stable LogSumExp. Args: input (Tensor) dim (int): Dimension along with the sum is performed keepdim (bool): Whether to retain the last dimension on summing Returns: Equivalent of log(sum(exp(inputs), dim=dim, k...
c9c867d9d81191922a56716dab128ea71821a638
3,635,938
import torch def train_epoch_ch3(net, train_iter, loss, updater): # @save """训练模型一个迭代周期(定义见第3章)""" # 将模型设置为训练模式 if isinstance(net, torch.nn.Module): net.train() # 训练损失总和、训练准确度总和、样本数 metric = Accumulator(3) for X, y in train_iter: # 计算梯度并更新参数 y_hat = net(X) l = ...
2c25a4e1e48e867c51d395deb58436df981b6d77
3,635,939
def get_defined_names_for_position(scope, position=None, start_scope=None): """ Return filtered version of ``scope.get_defined_names()``. This function basically does what :meth:`scope.get_defined_names <parsing_representation.Scope.get_defined_names>` does. - If `position` is given, delete all na...
82bb80c271cfe450ca3aa67bb3ccfbff73ae5212
3,635,940
def make_screen_hicolor(screen): """returns a screen to pass to MainLoop init with 256 colors. """ screen.set_terminal_properties(256) screen.reset_default_terminal_palette() return screen
1fa4ee36825ca9672af58332001463e5b804d171
3,635,942
def cached_object_arg_test(x): """takes a MyTestClass instance and returns a string""" return str(x)
5880976f0c74dc588b1b4e93cee349fee06473ee
3,635,943
from functools import reduce import logging def calculate_news_id(title: str = "", description: str = "") -> hex: """ Calculate an idempotency ID of a piece of news, by taking and summing the unicode values of each character (in lower case if applicable) in title and description and representing the f...
d46520430d8b5d77c4d52c7c99574ed600576048
3,635,944
import configparser def retrieve_artifact(artifact_id): """ Allows the client side API call to "retrieve" the artifact. Returns: type: str String representing JSON object which contains the result of the "artifact retrieve {uuid}" if the call was a success; else, JSON ...
2a53985aaab42d9873ddb27156195744d7a40c3c
3,635,945
import ipaddress def ip_network(addr): """Wrapper for ipaddress.ip_network which supports scoped addresses""" idx = addr.find('/') if idx >= 0: addr, mask = addr[:idx], addr[idx:] else: mask = '' return ipaddress.ip_network(_normalize_scoped_ip(addr) + mask)
c15718cc9b39129901937c4de5b73a7a33649a3d
3,635,946
def evaluate(env, agent, n_games=1, greedy=False, t_max=10000): """ Plays n_games full games. If greedy, picks actions as argmax(qvalues). Returns mean reward. """ rewards = [] for _ in range(n_games): s = env.reset() reward = 0 for _ in range(t_max): qvalues = agent.get_...
2fa4880c612f8c9cdf95d71ebe64236def345fbf
3,635,947
def kabsch(query, target, operator=True): """Compute the RMSD between two structures with he Kabsch algorithm Parameters ---------- query : np.ndarray, ndim=2, shape=[n_atoms, 3] The set of query points target : np.ndarray, ndim=2, shape=[n_atoms, 3] The set of reference points to a...
c3753f7a2b726908bedb9cd8ae562c8be664d0f0
3,635,948
def GetConfig(user_config): """Load and return benchmark config. Args: user_config: user supplied configuration (flags and config file) Returns: loaded benchmark configuration """ return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME)
cf6f63bdb4eba1dfdf61965a074fbaf4fe0be89b
3,635,949
def get_postgres_data(): """ reads in movie and ratings data for all users using the postgres database Parameters: - Returns: dataframe with movie IDs, ratings, user IDs; number of unique movies in database """ engine = create_engine(CONN, encoding='latin1', echo=False) df_ratings_proxy...
6a7642eaabd8bad9903af127bdb967fd2c60031c
3,635,950
def adriatic_name(p, i, j, a): """ Return the name for given parameters of Adriatic indices""" #(j) name1 = {1:'Randic type ',\ 2:'sum ',\ 3:'inverse sum ', \ 4:'misbalance ', \ 5:'inverse misbalance ', \ 6:'min-max ', \ 7:'max-mi...
d08ed926d80aa19326ab4548288a0b9cb02737e4
3,635,951
def add_certificate(cluster_name, data): """ Add a certificate to a cluster reference in the Asperathos section. Normal response codes: 202 Error response codes: 400, 401 """ return u.render(api.add_certificate(cluster_name, data))
3e9db7c5c6cc5deb5e3128e1be0041b1f3cf680f
3,635,952
def _make_histogram(values, bins): """Converts values into a histogram proto using logic from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/lib/histogram/histogram.cc""" values = values.reshape(-1) counts, limits = np.histogram(values, bins=bins) limits = limits[1:] sum_s...
b3801888d7d0225f159ff02b7593cb6287ae76a7
3,635,953
def generate_spec(nu1, nu2, dist): """ Generate a fake spectrum under the assumptions of the standard accretion disk model. dist needs to be in cm returns spectrum with luminosity at the source of the object """ freq = np.linspace(nu1, nu2, 1e3) return [freq, (freq**(1./3.))]
a53faed11196c17c5ce6b89c24ff8283cd9c21cb
3,635,954
def dearomatize(): """ Dearomatize structure --- tags: - indigo parameters: - name: json_request in: body required: true schema: id: IndigoDearomatizeRequest properties: struct: type: string required: tru...
e7a11519f712bbc36de93fe2ab24c3e128682b00
3,635,955
def isTree(rootFile,pathSplit): """ Return True if the object, corresponding to (rootFile,pathSplit), inherits from TTree """ if pathSplit == []: return False # the object is the rootFile itself else: return isTreeKey(getKey(rootFile,pathSplit))
002790cd2087ea40f77b27e9fe7fe51db1566761
3,635,956
def create_server(host="localhost", remote_port=22, local_port=2222): """ Creates and returns a TCP Server thread :param str host: the host to open the port forwarding from :param int remote_port: the remote ort to be forward to locally :param int local_port: the local port to open to forward to ...
dbd18d57da57aaa375a4f7f29957c6e98e450e72
3,635,957
def output_to_df(record): """Converts list of records to DataFrame""" df = pd.DataFrame(record, columns=["line_count_python", "author_name"]) return df
5486abf0a4a57fa96582c4a0a8417b0836a943f0
3,635,958
def sanitize_tx_data( unspents, outputs, fee, leftover, combine=True, message=None, compressed=True, absolute_fee=False, min_change=0, version='main', message_is_hex=False, ): """ sanitize_tx_data() fee is in satoshis per byte. """ outputs = outputs.copy...
778b94b495993daa1f9f1573d85a7dac868473b1
3,635,959
def create_csrf_disabled_registrationform(): """Create a registration form with CSRF disabled.""" return create_registrationform(**_get_csrf_disabled_param())
ff258d35b8ba793ffb5e64a3b99065da1561f2de
3,635,960
def calc_a_lzc(ts, norm_factor=None): """ Calculates lempel-ziv complexity of a single time series. :param ts: a time-series: nx1 :param norm_factor: the normalization factor. If none, the output will not be normalized :return: the lempel-ziv complexity """ bin_ts = np.char.mod('%i', ts >= n...
6827b44dc5f533df0ce41361164d68636d5fa4a4
3,635,961
def rbd_command(command_args, pool_name=None): """ Run a rbd CLI operation directly. This is a fallback to allow manual execution of arbitrary commands in case the user wants to do something that is absent or broken in Calamari proper. :param pool_name: Ceph pool name, or None to run without --poo...
447432fe8c2a0b03f073a5471aa1d52610e7529e
3,635,963
from typing import Counter def aggregate_roles_iteration(roles, parameters=None): """ Single iteration of the roles aggregation algorithm Parameters -------------- roles Roles parameters Parameters of the algorithm Returns -------------- agg_roles (Partial...
44ce1310683f798f4cdc04ec5a9725c1d3c0f260
3,635,965
def convertToOneHot(vector, num_classes=None): """ Converts an input 1-D vector of integers into an output 2-D array of one-hot vectors, where an i'th input value of j will set a '1' in the i'th row, j'th column of the output array. Example: v = np.array((1, 0, 4)) one_hot_v = c...
949370fb73416253266d00649d4ecc1075293f63
3,635,966
def open_signal(file, sr): """ Open a txt file where the signal is Parameters: file: Address where the file is located sr: Sampling rate Return: signal: The numpy-shaped signal t: Time vector """ signal = np.loadtxt(file, comm...
9604783450d70aa16648b933dbf12890efea22de
3,635,967
def flops_elu(module: nn.ELU, input: Tensor, output: Tensor) -> int: """FLOPs estimation for `torch.nn.ELU`""" # For each element, compare it to 0, exp it, sub 1, mul by alpha, compare it to 0 and sum both return input.numel() * 6
d22d5a60c46e74b4cfc92ffd55b027c199b914e7
3,635,968
import copy def gen_DFSC_MitEx(backend: Backend, **kwargs) -> MitEx: """ Produces a MitEx object that applies DFSC characteriastion to all experiment results. :param backend: Backend experiments are run through. :type backend: Backend :key experiment_mitex: MitEx object observable experiments are...
ff250e8f8319ba5ceca6b035741d7c896f460268
3,635,969
import json def dumps(pif, **kwargs): """ Convert a single Physical Information Object, or a list of such objects, into a JSON-encoded string. :param pif: Object or list of objects to serialize. :param kwargs: Any options available to json.dumps(). """ return json.dumps(pif, cls=PifEncoder, *...
9b3c1712bc094a9ff4aed32edad6ffc6db718e66
3,635,970
def replace_digits_with_zero(data): """Follow the paper's implementation """ new_data = [] for words, tags in data: new_words = [] for w in words: new_w = "0" if is_number(w) else w new_words.append(new_w) new_tags = list(tags) new_data.append((new...
a92a604a2146ac9a4f6de7f5ee96bb3b9eaf18ea
3,635,971
def gcd(number1: int, number2: int) -> int: """Counts a greatest common divisor of two numbers. :param number1: a first number :param number2: a second number :return: greatest common divisor""" number_pair = (min(abs(number1), abs(number2)), max(abs(number1), abs(number2))) while number_pair[...
9f22c315cc23e2bbf954f06d416a2c44f95ddbb7
3,635,972
import time def message_counter_down_timer(strMsg="Calling ClointFusion Function in (seconds)",start_value=5): """ Function to show count-down timer. Default is 5 seconds. Ex: message_counter_down_timer() """ CONTINUE = True layout = [[sg.Text(strMsg,justification='c')],[sg.Text('',size=(10, 0...
064f995aa27298414f83398facbfbfa449c67dd1
3,635,973
def get_overlapping_timestamps(timestamps: list, starttime: int, endtime: int): """ Find the timestamps in the provided list of timestamps that fall between starttime/endtime. Return these timestamps as a list. First timestamp in the list is always the nearest to the starttime without going over. Par...
0ad6836d43d670f811b436e34887e159462c9ec1
3,635,974
def calc_war_battingfactor(oba,mlb,league,parkfactor,batting): """ oba: instance of wOBAWeightSim mlb: instance of BattingSim league: DataFrame parkfactor: DataFrame batting: DataFrame ----------------------------------------- returns: DataFrame with column [BattingFactor] """ # ...
40f07a7ea1fab67bb982d3292d51784990fa8d2d
3,635,976
def get_forward_backward_walk_union_ops(forward_seed_ops, backward_seed_ops, forward_inclusive=True, backward_inclusive=True, within_ops=None, ...
c99d621024a832caaff3f915cd792e5c46e11c95
3,635,978
def random_crop(*arrays, height, width=None): """Random crop. Args: *arrays: Input arrays that are to be cropped. None values accepted. The shape of the first element is used as reference. height: Output height. width: Output width. Default is same as height. Returns: ...
466acb422499f26c971fcb55ea8d7ac595a45660
3,635,979
from re import T def block_amplitudes(name, block_spec, t, hrfs=(glover,), convolution_padding=5., convolution_dt=0.02, hrf_interval=(0.,30.)): """ Design matrix at times `t` for blocks specification `block_spec` Create design matrix for linear m...
3b8e30b5a08ba016c4ebd286b7735e6b5f7c18f9
3,635,980
def get_embedding(param_list, meta): """ Get the USE embeddings of the input text. (non-qa USE) Param 1 - either string or list of strings Return - Embeddings """ data = { 'op': 'encode', 'text': param_list[0] } ret = USE_ENCODER_API.post(data) return ret['encoded']
dbfe9cf039fbbe059cded8646479019f30d96c0b
3,635,981
import json def ticket(request, key): """ 提供查询接口,让客户拿到 result key 之后查询用户的信息 """ wxuser = ResultTicket.fetch_user(key) if not wxuser: return HttpResponse(status=404) return HttpResponse(json.dumps(wxuser.serialize()))
ebe7c6511f8a95b2c6cdaaec7c080e8e8eb70c83
3,635,982
def is_sequence(arg): """Check if an object is iterable (you can loop over it) and not a string.""" return not hasattr(arg, "strip") and hasattr(arg, "__iter__")
466154b8ef9d19b53744187d44dc6cd172a70f62
3,635,983
def _sig_figs(x): """ Wrapper around `utils.sigFig` (n=3, tex=True) requiring only argument for the purpose of easily "apply"-ing it to a pandas dataframe. """ return numutils.sigFigs(x, n=3, tex=True)
b91ae5dca83d0b40362a7087dfda7788a59604a0
3,635,984
from typing import List from typing import Optional from typing import Tuple def stackbar( y: np.ndarray, type_names: List[str], title: str, level_names: List[str], figsize: Optional[Tuple[int, int]] = None, dpi: Optional[int] = 100, cmap: Optional[ListedColorma...
328de6e4f91d3e2014432e20e476cd8833ed3f4c
3,635,985
def get_mempool_transaction_ids(): """ Request the full list of transactions IDs currently in the mempool, as an array :return list: a list of transaction IDs """ resource = 'mempool/txids' return call_api(resource)
770039eacf42fe6bc14c3571a5b907f7e9d02f3a
3,635,986
def zsplits(ds, flds=['density'], npts=21): """Return a lineout of a yt dataset, along z, through X=Y=0 but averaged over X,Y within a cube edge length Splits region into a series of cubes and takes their averages Expects multiple fields; returns dict of field grid vectors. Also, outputs YT ar...
4a3c4d004c5b84f9996c2e7702468a8ca63b1a62
3,635,987
def get_ma15(ticker): """15일 이동 평균선 조회""" df = pyupbit.get_ohlcv(ticker, interval="day", count=15) ma15 = df['close'].rolling(15).mean().iloc[-1] return ma15
c9ce795bc2d71a427d14d2123b3c99f51fd3ba82
3,635,988
def distance_at_t(points, t): """ Determine the sum of all the distances of the Points at time t using the easy-to-calculate Manhattan metric. We could use the Euclidean metric but the extra computation is entirely unnecessary. :param points: the list of Points :param t: the time t :return: the ...
f113622e0b655515686e81895633adfbc0617612
3,635,991
def fixed_from_persian(p_date): """Return fixed date of Astronomical Persian date, p_date.""" month = standard_month(p_date) day = standard_day(p_date) year = standard_year(p_date) temp = (year - 1) if (0 < year) else year new_year = persian_new_year_on_or_before(PERSIAN_EPOCH + 180 + ...
fcd5fa44cae344658cf0377642e1f20bd1199c38
3,635,992
def fix_stddev_function_name(self, compiler, connection): """ Fix function names to 'STDEV' or 'STDEVP' as used by mssql """ function = 'STDEV' if self.function == 'STDDEV_POP': function = 'STDEVP' return self.as_sql(compiler, connection, function=function)
b1fa48801fb397590ad5fb249d928906e7c21c8a
3,635,993
import functools import inspect def argdispatch(argument=None): """ Type dispatch decorator that allows dispatching on a custom argument. Parameters ---------- argument : str The symbolic name of the argument to be considered for type dispatching. Defaults to ``None``. When ``None``, ...
70f2680c92dd2f2efedfb5a78cef25ad66c35f7d
3,635,994
def yaepblur(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#yaepblur""" return filter(stream, yaepblur.__name__, *args, **kwargs)
379cee07637cbfb7aef6ec67fbca5b97477d6936
3,635,996