content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_in_system_by_id( system_id, stop_id, return_only_stations=True, earliest_time=None, latest_time=None, minimum_number_of_trips=None, include_all_trips_within=None, exclude_trips_before=None, alerts_detail=None, ): """ Get information about a specific stop. """ ...
8601c0d5788bad73c7db959f962828b8e7e45bf7
3,616,125
def required_input(message, method=input): """ Collect input from user and repeat until they answer. """ result = method(message) while len(result) < 1: result = method(message) return result
c9a21d6e63ab6bdde081db471cf0d2420f9047ea
3,616,126
from typing import Callable from typing import List from typing import Any def worker_map(worker: WorkerPool, fn: Callable[..., List[Any]], input_objects: List[Any]) -> List[Any]: """ Maps a list of objects through a worker. :param worker: Worker pool to use for parallelization. :param fn: Function to...
1e3f4d7a4c367e9323f4dd399164998292323301
3,616,127
def _generate_normals(polygons): """Takes a list of polygons and return an array of their normals. Normals point towards the viewer for a face with its vertices in counterclockwise order, following the right hand rule. Uses three points equally spaced around the polygon. This normal of course might...
4d43d2f8b868c89238be165930c956e7032bcf21
3,616,128
def initSeedSolutions() : """ This function should do any initialization needed to make generating individual solutions fast. It will get called before any solutions are generated. The value returned will be passed into generateSolution, so this is a good place to read in files or initializ...
a18a3099dc957a1195267a5eb742e7db0b026ac4
3,616,129
from operator import ge def gen_courses(): """ Helper function to populate the course dropdown. Creates a list of every course in every degree necessary for a CIS student. Currently static since this app only supports CIS students. Can be changed later to create a dropdown list for a different type of student i...
346cd1e90b684d708c26316d4f247811683b4477
3,616,130
def message( val: ArrayLike, src: int, sgroup: int, dest: int, dgroup: int) -> np.void: """Creates a message used for passing information between objects. Args: val: A numpy structured array. src: A 64-bit int that represents the source of the message. ...
32c343a8d427bc15bea725871e7fc395b5b33938
3,616,131
import requests import joblib import json def classify(): """ Make a POST to this endpint and pass in an URL to an image in the body of the request. Swap out the model.pkl with another trained model to classify new objects. """ try: body = request.get_json() print(body) img_ur...
501a97d1c9a2e56e9fee64f689bc624cab5b96b5
3,616,132
def list_nmmr_tris_bitfield(fp, child, sfrname, offset): """ Format a single bitfield of NMMR TRIS pseudo register Input: - index in .pic - register node Notes: - Expected to be used with 12Fs only """ if (child.nodeType == Node.ELEMENT_NODE): if (child.nodeName == "edc:AdjustPoin...
3f18126ea529b5bf299f69fad1bc92f8345718f7
3,616,133
def _mogrify_team(cursor, xs, fieldsList): """Shortcut for mogrifying a list as if it were a tuple.""" for valueIndex, [thisValue, thisColumn] in enumerate(zip(xs, fieldsList)): if (thisColumn == "team") | (thisColumn == "pos_team"): xs[valueIndex] = nfldb.standard_team(thisValue) ...
f90a87ebedb8af35e691231cab4c157533d4abc5
3,616,134
def table_columns(table, session): """ :param string table: Name of table or table schema :param Session session: SQLAlchemy Session :returns: List of column names in the table or empty list """ res = [] if isinstance(table, basestring): table = table_schema(table, session) for ...
6ac7d4923e55800d3ed2b636b9764b599d9e5c31
3,616,135
def _dpss_wavelet(sfreq, freqs, n_cycles=7, time_bandwidth=4.0, zero_mean=False): """Compute Wavelets for the given frequency range Parameters ---------- sfreq : float Sampling Frequency. freqs : ndarray, shape (n_freqs,) The frequencies in Hz. n_cycles : float...
c10cde512bcbbf222fb15c2ae5f7d432aaad4f63
3,616,136
def create_model(config: ml_collections.ConfigDict, deterministic: bool) -> nn.Module: """Creates a Flax model, as specified by the config.""" if config.model == "GraphNet": return models.GraphNet( latent_size=config.latent_size, num_mlp_layers=config.num_mlp_lay...
bcc2581de315876b115da2f5a06770a7d51d865e
3,616,137
def property_from_list(index): """Returns the item at position 'index' from a list. Args: index: The (0-based) item in the list to return. Returns: A function that returns the specified item from a list, or '' if the list contains too few items. """ @empty_if_none def property_from_list_lambd...
6a5aad5f40f6fbb94333492b520f341e530e14ba
3,616,138
def clothes_info(request, id): """Просмотр информации об одежде""" clothes = Clothes.objects.get(pk_clothes=id) return render(request, "clothes_info.html", {"clothes": clothes})
4ab555d24e6de7fe7a73f97a727052ca9032296d
3,616,139
def multiTag(type, tag=None, **kwargs): """ Displays the "multiple tag widget" """ kwargs["tag"] = tag kwargs["type"] = type kwargs["atf"] = AddTagForm({"type":type, "colour":["white"]}) return kwargs
53483fc339dc28c99eebb3d703868c57f4b67b90
3,616,140
import inspect import re def findsource(object, cache_key): """ findsource that does not cache """ file = inspect.getsourcefile(object) if not file: raise IOError('source code not available') lines = None with open(file) as f: lines = f.readlines() if not lines: ...
1f7deb36420df615d07b578e12c77abc5138a8f2
3,616,141
def parse_from_file( root_processor, # type: RootProcessor xml_file_path, # type: Text encoding='utf-8' # type: Text ): # type: (...) -> Any """ Parse the XML file using the processor starting from the root of the document. :param root_processor: Root processor of the XML doc...
03d002a33e236578c49ae7527b8192a982b575ad
3,616,142
def bb(a, b, c): """ナップザック問題を分枝限定法で解く :param np.array a: 制約条件の係数 :param int b: 制約条件の値 :param np.array c: 目的関数の係数 :return: """ answer_temp = greedy(a, b, c) # スタックに(aの残り, bの残り, cの残り, 答えの先頭部分)という形式で部分問題を登録する stack = [(a, b, c, np.array([]))] while stack: print('---------...
fabf39d16d9cc74f17be0e33260598f8d22b736c
3,616,143
import typing def is_lock_pending( end_state: NettingChannelEndState, secrethash: typing.SecretHash, ) -> bool: """True if the `secrethash` corresponds to a lock that is pending to be claimed and didn't expire. """ return ( secrethash in end_state.secrethashes_to_lockedlocks or...
2e4df0e532230f3d0176eb60ce5eff9440d18aac
3,616,144
def NCBITAXON( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2021-12-14", **kwargs ) -> Graph: ...
fd99a31972c9ed9acab845b4325084c7be2b8832
3,616,145
def gather_contact_details(): """ **gather_contact_details** obtains contact details from request. args :return: """ names = request.args.get('names') email = request.args.get('email') cell = request.args.get('cell') subject = request.args.get('subject') message = req...
9dc5d81102009173be680903bd50f8ab13c1b6f0
3,616,146
def dave4vm(mag, window_size, threshold=1.0): """ DAVE4VM - Differential Affine Velocity Estimator for Vector Magnetograms Parameters --------- MAG : structure of vector magnetic field measurements', MAG.DX : X spatial scale (used to compute B?X), ...
b48bd97644775462965bc6c2898fa181f4f94ec5
3,616,147
def get_unc_directory_from_string(string): """ Parses a string from `UncDirectory`'s `get_auth_path` method and returns a new `UncDirectory` object based on it. This may raise any errors that can be raised by `UncDirectory`'s constructor. """ creds = None path = string if '@\\\\' in str...
11b0a0e7e09c66b278a3610e2c6d300659e64b9b
3,616,148
def start(start): """When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date.""" start_date = dt.datetime.strptime(start, '%Y-%m-%d') session = Session(engine) year_query = session.query(func.min(measurement.tobs), \ ...
84a29ce18bd3c5fbc801657de135164f7487542a
3,616,149
def create_model(fingerprint_input, model_settings, model_architecture, is_training): """Builds a model of the requested architecture compatible with the settings. There are many possible ways of deriving predictions from a spectrogram input, so this function provides an abstract interface for c...
fceddf64e7a4d50d307b34c954c5e8bcadcc0655
3,616,150
def orbit2frame(name, ref_orbit, orientation=None, center=None, bypass=False): """Create a frame based on a Orbit or Ephem object. Args: name (str): Name to give the created frame ref_orbit (Orbit or Ephem): orientation (str): Orientation of the created frame bypass (bool): By-p...
4236fa92e60c56e18ee19e7860e844836b9cc428
3,616,151
def from_hex_lsb(text): """Decode a hex encoded fingerprint string where the bits and bytes are in LSB order >>> from_hex_lsb('102f') (None, '\\x08\\xf4') >>> Raises a ValueError if the hex string is not a multiple of 2 bytes long or if it contains a non-hex character. """ return (Non...
bc66e35176eca5ea9148714a7929c90a9a167c66
3,616,152
def get_first_char(value): """ Returns the first char of the given string :param value: :return: """ return value[:1]
98207e7269371f0177f45a2c85f874e1d9bbb756
3,616,153
import json def load_instructions(ufilename): """ Expand this, maybe in the readme/docs because it's pretty much the heart and soul of the program. Loads a json file that describes the titlecard. In general, it'll be pairings of json keys and values. There are two keys that are handled specially...
e6b0d5ed81f5bc5c3a1837455f3815b282533e80
3,616,154
def dfs_search_recursive(G, src): """Entry to recursive Depth First Search.""" marked = {} node_from = {} def dfs(v): """Recursive DFS.""" marked[v] = True for w in G[v]: if not w in marked: node_from[w] = v dfs(w) dfs(src) re...
b433aba6a0d397c355ce578a867cfdebcccd980d
3,616,155
def is_cat(filename: str) -> bool: """ Returns true if filename is an image of a cat. In the dataset we are using this is indicated by the first letter of the filename; cats are labeled with uppercase letters, dogs with lowercase ones. """ result = filename[0].isupper() # print(f"File: {fil...
ad56c7c3ae28951fc31bcf70fece29bf934e4cec
3,616,156
def rm_user_edges(lcen, rcen, rm_slits): """ Remove one or more slits, as applicable Code compares exisiting slits (which must be sycnhronized) against the input request and removes any that match. Args: lcen (np.ndarray): Left traces of slit/orders rcen (np.ndarray): Right traces ...
38e9eae662813e126721aa1e45d7ff738775c02d
3,616,157
def analyze_text(filename): """ Calculate the number of lines and characters in a file :param filename: the name of the file to analyze :raises: IOError: if ``filename`` does not exist or can't be read :return: a tuple where the first element is the number of lines in the file and the second...
1670d3bff0402482e9e33be401e8914eea117f6c
3,616,158
def auto_adapt_batch(train_size, val_size, batch_count_multiple=1, max_size=256): """ returns a suitable batch size according to train and val dataset size, say max_size = 128, and val_size is smaller than train_size, if val_size < 128, the batch_size1 to be returned is val_size if 128 < val...
d0a6fa9e6bde3d563bd7fad5e2bbcf7068f9ff65
3,616,159
def get_model(model, feat_dim, meta): """Build a model specific for the given task. Arguments: - model: The model architecture. - feat_dim: Feature (last hidden layer) dimension. - meta: Meta data about the task. Return: - The corresponding neural network ""...
04c033555cc91ea622b70cd1edde72e7ecf51fb1
3,616,160
from typing import Tuple def pascals_triangle(rows: int) -> Tuple[Tuple[int, ...], ...]: """Return tuple containing pascals triangle up to specified length.""" result = [] next_numbers = [1] for _ in range(0, rows): # move row current_numbers = next_numbers next_numbers = [] ...
80c46657d413ff67bf3fc94091fd8a81bdb5a148
3,616,161
def gauss2D(valRange, size, mu, sigma): """ calculate 2D Gaussian on array. Parameters ---------- valRange : int value range to which the Gaussian will be scaled. size : list of ints x and y size of array. mu : list of floats x and y center position of Gaussian. ...
345152a70ef25fe607e4de2503a9e7424dd2ab8e
3,616,162
def two_fer(name="you"): """Returns a string in the two-fer format.""" return "One for " + name + ", one for me."
a7f10a45b214ea1ea79a6956148b3c6677f27e21
3,616,165
import random def insere_randomico(lista, qtd_insercao): """ Insere n elementos de acordo com a quantidade passada por parametro qtd_insercao - quantidade a ser inserida na lista """ for i in range(qtd_insercao): lista.append(random.randint(1,10000)) random.shuffle(lista) return li...
8e208870893e3809db6e589ec41a305a8e089b80
3,616,166
def use_case_config(privilege=None, request_object=NoneType): """Class decorator that allows to attach a privilege and a request_object class to a certain use case class Usage: @use_case_config(Privileges.ListStudies, ListStudiesRO) class ListStudiesUC(UseCase): pass :param privilege...
2b9c96333ca55c53eda4e86ad46734ab5492898a
3,616,167
def project(ifs: IteratedFunctionSystem, point: Vec) -> Vec: """Project a point by repeatedly applying functions from the IFS. :param ifs: The Iterated Function System to use for projection. :param point: The point in the plane to repeatedly project. :returns: A point obtained by applying random functi...
5389b902d8d3e158abc5adab8305597d02db1577
3,616,168
import math def create_pagination(page, results_per_page, total_results): """Create pagination to filter results to manageable amounts.""" pagination = {} # For UI pagination['page'] = page pagination['total_results'] = total_results pagination['total_pages'] = math.ceil(total_results / resul...
d58bf2adee3e090e88aa82a5a91560e8fb1631e0
3,616,169
def get_source(url): """Return the source of the supplied url argument""" http = httplib2.Http() try: status, response = http.request(url, headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'}) if status.status == 200: return response else: return None ex...
f0c9f98d8de070ccf0d0f88582ab4fc5227a771c
3,616,170
def pygrep_iterator(iterator, keyword, ilen=100, ishift=0, begin=0): """ """ ibuffer = -1 out_str = "" maxlen = ishift + ilen # for line in iterator: if keyword in line: out_str = keyword + line.partition(keyword)[2] ibuffer = len(out_str) break #...
c5438357792155007ab479d37bccf1ae1bd2373b
3,616,171
def waveletCoeffs(name): """ Return the wavelet coefficients according to the wavelet name. Parameters ---------- name : str Name of wavelet. Supported values: * '**haar**' : Haar wavelet * '**db1**'-'**db20**' : Daubechie wavelets with different support size ...
b0c692f25326c127a3a91eb060cd964705ef955f
3,616,173
import socket import struct def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: # If not ...
9dd0117358d7b333d03cf1cf87a02c0d7f203943
3,616,174
def find_or_update_user(id, role=None): """ Find existing user and update role """ user = User.query.filter(User.id == id).first() if user and role: user.roles.append(role) db.session.commit() return user
ceef9023dc1222595141a66eb3fbd05e54efe205
3,616,175
def conv_len(a, l): """ Function that converts a number into a bit string of given length :param a: number to convert :param l: length of bit string :return: padded bit string """ b = bin(a)[2:] padding = l - len(b) b = '0' * padding + b return b
b3c28e82c759e3a433ca9b52d7e7726f786e76ff
3,616,176
def catalog_to_mask(catalog, shape, wcs, radius=np.radians(4/60)): """ Convert catalog with DEC, RA values to binary point source mask. Parameters ---------- catalog : (2, N) array DEC and RA values (in radians) for each point source. shape : tuple Shape of output map. wcs :...
35360e67473affa3c4bc8fbe1c8da10a728337cb
3,616,177
import math def _cost_of(rule): """Calculate the cost of a rule based on the number of constraints. Rules requiring more tokens to match are made less costly and tried first. """ return math.log2(1 + 1 / (1 + _num_tokens_of(rule)))
819ef7c2f1115c553d1be62f0dc9ec727b3e9f1f
3,616,180
def ensure_aware_datetime(dt, default_tz=UTC): """ Ensures that the returned datetime object is not naive. """ if dt.tzinfo is None: dt = dt.replace(tzinfo=default_tz) return dt
e211cea62f22f089df922dbb88a6548a754e8daa
3,616,182
import socket def ping_target(target, timeout, count, size): """Ping a target and handle socket errors. Returns: pythonping.ResponseList socket.error RuntimeError """ try: return pythonping.ping( target=target, timeout=timeout, coun...
d9c0e1223c1444bc8a7b890d1b0fa4678febfcc2
3,616,183
def validate_password(password): """Validates a password Notes ----- The valid characters for a password are: * lowercase letters * uppercase letters * numbers * special characters (e.g., !@#$%^&*()-_=+`~[]{}|;:'",<.>/?) with the exception of a backslash ...
09628fed13c161a477d28fa8016bc2cccf0b298e
3,616,184
def Sub(a, b): """ Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). :param a: operand a :param b: operand b :return: a - b if a - b > 0 or revert the transaction. """ Require(a>=b) return a-b
5f6fde80f3b4a6da31b0eb75ddfb680c0667ed33
3,616,185
def wrap_mc_method(func, f_args, f_kwargs, return_val, funcname=None): """Pulls the operation and (for get) whether a key was found, on each public method.""" kvs = {} if funcname in MC_COMMANDS: kvs['KVOp'] = funcname # could examine f_args for key(s) here if funcname == 'get': kvs[...
867265d4c3b7446cc5380c366d5a16f3ceae1932
3,616,186
def binary_accuracy(output: paddle.Tensor, target: paddle.Tensor) -> float: """Computes the accuracy for binary classification""" with paddle.no_grad(): batch_size = target.shape[0] # .size(0) pred = (output >= 0.5).t().flatten() # .view(-1) correct = pred.eq(target.flatten()).sum() ...
28a92cec755168c31e5deeec3a729b7bb6800c6e
3,616,187
def check_iban(iban): """Check the syntax and the checksum of an IBAN. Return the parts of the IBAN: Country Code, Checksum, Bank/Branch Code and Account number. Raise an IBANError exception if the input is not correct. """ err = None code = iban[:2] checksum = iban[2:4] bban ...
2cb6ded222499973dcb0d2516c43401b1648be9b
3,616,188
def best_step(x, y): """ Fits a step function to the data. Returns ------- low, high, threshold : floats The parameters of the step function """ ths = x[2:-2] scores = np.array([((y - degrau(x, y[x<th].mean(), y[x>=th].mean(), th))**2).sum() for th in ths]) th = ths[scores...
773223a2a9c4466025511920c3b396a7f801898a
3,616,189
def peek(buckets, max_builds=None, start_cursor=None): """Returns builds available for leasing in the specified |buckets|. Builds are sorted by creation time, oldest first. Args: buckets (list of string): fetch only builds in any of |buckets|. max_builds (int): maximum number of builds to return. Defaul...
80641dcdf3e97e8a4d020c139187f4bb90b43f0f
3,616,190
import math def a_raininess_oracle(timestep): """Mimics an external data source for raininess Arguments ========= timestep : int Requires a year between 2010 and 2050 Returns ======= raininess : int """ msg = "timestep {} is outside of the range [2010, 2050]".format(time...
e1b4f32f62fe19f95ac876a0acf03fe533858366
3,616,191
def load_model_keras(model_path): """ Loads Keras model. :param model_path: Path to H5 model. :return: Keras model. """ model_loaded = load_model(model_path) return model_loaded
7289af5e628ad50275d6da78956bc8635d88c20e
3,616,192
def user_identity_lookup(user: User) -> str: """Define identity user field.""" return user.email
ff1251eee8c126b94d37c3302e4fa4b1a1060cd8
3,616,193
def plot_data_tiled(data, normalize=False, title="", vmin=None, vmax=None, cmap="Greys_r", save_filename=None): """ Save figure for input data as a tiled image Inpus: data: [np.ndarray] of shape: (height, width, features) - single image (n, height, width, features) - n images normalize: [boo...
15c76eff2ff16ec4f1eb2a254a395a339afd5d66
3,616,194
import asyncio def extract_entity(funct): """Decorate for extract entity object from request.""" @asyncio.coroutine def async_api_entity_wrapper(hass, config, request): """Process a turn on request.""" entity_id = request[API_ENDPOINT]['endpointId'].replace('#', '.') # extract sta...
c623443933d801ad0526fbe293d37b87a13b76bd
3,616,195
def _value_name(value): """Return the name of the value.""" return '{} {}'.format(_node_name(value.node), value.label)
f2efacd23b86787d246fa9257aeb235d72dd9fc8
3,616,196
def shrinking_sphere(xyz, vxyz, m, delta=0.025): """ Compute the center of mass coordinates and velocities of a halo using the Shrinking Sphere Method Power et al 2003. It iterates in radii until reach a convergence given by delta of 1% of the total number of particles while there are more than 1000...
9a97509647fcff67a7ff22d83a60ce4ecfa99f3b
3,616,197
def movefiles(): """ function to move files. """ data=json.loads(request.data) parentid = data["parentid"] filelist = data["filelist"] if len(filelist) > 0: try: return update.movefiles(parentid,filelist,current_user) except Exception as e: print e ...
5e52d08d5ee3de1126da6bb3cc2ca860d53ab130
3,616,198
from math import ceil def get_positives(scores, label, other_labels, threshold, shift = 10): """ :param scores: :param label: :param other_labels: :param threshold: :return: """ avg_window_half_size = int(ceil(100 / shift)) positives = [] x = scores[:, label] peaks = fin...
a5e655cee5db2facd77f33efb5abaadf9b676697
3,616,199
from typing import Tuple from typing import List from typing import Dict def find_folders(root: str, file_client: FileClient) -> Tuple[List[str], Dict[str, int]]: """Find classes by folders under a root. Args: root (string): root directory of folders Returns: Tuple[List[...
d01c41a6fad24c1d869042b1af5980f099510e2d
3,616,200
import torch def matrix_to_homogeneous(batch: torch.Tensor) -> torch.Tensor: """ Transforms a given transformation matrix to a homogeneous transformation matrix. Args: batch: the batch of matrices to convert [N, dim, dim] Returns: torch.Tensor: the converted batch of matrices ...
ab3bf1acf1e8fab2d4a4fcdcfd062821bc891b9d
3,616,201
from typing import Callable def council_member(func: Callable[..., R]) -> CouncilMember[R]: """ a function decorator to create an appropriate member :param func: the function to wrap :return: a CouncilMember that will call func, ignoring council_state unless a parameter of that name exists in fu...
5aad18808b62dba6de1ea586f60e2d33ffe8da9a
3,616,202
def setup(hass, config): """Setup the Buspro component. """ host = config[DOMAIN][CONF_HOST] port = config[DOMAIN][CONF_PORT] name = config[DOMAIN][CONF_NAME] hass.data[DOMAIN] = "<buspro>" #load_platform(hass, 'light', DOMAIN, {'optional': 'arguments'}) #load_platform(hass, 'light', ...
5c7fcdce7e0b8ee87b598c1fb0ba53e0ef4720ef
3,616,203
def check_output(output): """Check if output contains any error. Several commands return output which we need to return back to the caller. But, before we return anything back we want to perform a sanity check on on the output in order to catch wrong input as it is impossible to perform any sanitiz...
f1d4e64bd6a98cae23ae6c536dcb85c2d4c38024
3,616,205
import json def englishToFrench(EnglishText): """Translate english to french.""" translation = language_translator.translate( text=EnglishText, model_id='en-fr').get_result() jsonStr = json.dumps(translation, indent=2, ensure_ascii=False) data = json.loads(jsonStr) for i in data['translat...
626f8e813b6316143afc147395cc4827406b48dd
3,616,206
def nulls_first(column: _ColumnExpressionArgument[_T]) -> UnaryExpression[_T]: """Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression. :func:`.nulls_first` is intended to modify the expression produced by :func:`.asc` or :func:`.desc`, and indicates how NULL values should be handled whe...
cd3f9cdcb8120cab3cdf38b4b370d64ba97bf97d
3,616,207
import struct def readHeader(fd): """read protocol header""" data = fd.recv(6) value = struct.unpack(">bib", data) return value
6f1ac379f9eb1f5862754dd10fced9a817bb664a
3,616,208
def load_default_item(monkeypatch) -> Item: """Save a default item object, and return the object""" default_category = MockCategory.default_category() save_mock_category(monkeypatch, default_category) default_item = MockItem.default_item(parent_category=default_category) save_mock_item(monkeypatch, ...
0f6085e592b9318418477a6eded7ec65778bbbc7
3,616,209
import tqdm def encode_vocab(data, word2ind): """Converts string tokens to indices based on given dictionary.""" dialogs = data['data']['dialogs'] print("[%s] Encoding caption tokens..." % data['split']) for i, dialog in enumerate(tqdm(dialogs)): dialogs[i]['caption_tokens'] = [word2ind.get(wo...
cc67720badc41d8f46af361e5efad4ea2aed7e2a
3,616,210
def get_RSI(df, column='Close', time_window=14): """Function to make the RSI values for a given stock dataframe""" # Differential between the Column diff = df[column].diff(1) # Integrity of the difference values up_chg = 0 * diff down_chg = 0 * diff # We consider the upchange as positive...
dca6f44062b8dbc04444f033d2e3b54075ad2ca6
3,616,211
def text_classification_mappings(): """Text classification index mappings""" return { "_source": mappings.source( excludes=[ # "words", # Cannot be exclude since comment text_length metric is computed using this source fields "predicted", "pre...
da83494f73308bec0c7e56ff196d44cfa1902e03
3,616,212
def use_mapping(*args): """ use_mapping(ea) -> ea_t Translate address according to current mappings. @param ea: address to translate (C++: ea_t) @return: translated address """ return _ida_bytes.use_mapping(*args)
1fdab28dbbba25d33a01e1f53a81f46f5ce99cbc
3,616,213
def get_oldest_timestamp(data, additional_groups_to_ignore, additional_tags_to_ignore, print_all_tags=False): """data as dictionary from json. Should contain only time stamps except SourceFile""" # save only the oldest date date_available = False oldest_date = None oldest_keys = [] # save src...
fa2212adebacc2713b76ad436b354fec6e733de3
3,616,214
def get_pascal_voc_colors(): """Load the mapping that associates pascal classes with label colors Returns: np.ndarray with dimensions (21, 3) """ num_cls = 21 colors = [0] * (num_cls * 3) colors[0:3] = (0, 0, 0) # 0: 'road' colors[3:6] = (128, 0, 0) # 1 'sidewalk' colors[6:9] ...
5638e802587763d77350ad0642cadae54167a6b7
3,616,215
def orth_complement(A, B): """Returns the orthogonal complement of A in B """ rank_a = A.shape[1] C = jnp.hstack([A, B]) Q, R = jnp.linalg.qr(C) return Q[:, rank_a:]
53f0317c38d81113f616927d56661de139c8c278
3,616,216
def get_grouped_data(input_data, feature, target_col, bins, cuts=0): """ Bins continuous features into equal sample size buckets and returns the target mean in each bucket. Separates out nulls into another bucket. :param input_data: dataframe containg features and target column. :param fe...
f63bf9680107f1fc6f50d5e79faa64d29ce9db00
3,616,218
from typing import List def get_trajectory_from_environment( environment: tf_py_environment.TFPyEnvironment, observation: List[List[float]], predicted_action: int) -> trajectories.Trajectory: """Gets trajectory data from `environment` based on observation and action. Aligns `environment` observation ...
6dcd4d9b4f2628d560f7cca0234453d5af69d259
3,616,219
def resize_nd_skimage(img, size, order=1, **kwargs): """ Resize the input numpy array image to the given size. Args: img (numpy array): Image to be resized. size (tuple): Desired output size. order (int, optional): Desired interpolation. Default is 1 kwargs: other parameters for...
df34f5717b6699687279b8aef3b111994f6956c2
3,616,220
def MAXA(*args) -> Function: """ Returns the maximum numeric value in a dataset. Learn more: https//support.google.com/docs/answer/3094016 """ return Function("MAXA", args)
5f19796115365c0b7e19fd0c6529d22d28d5998c
3,616,221
def row_data(data): """handle tuple (row) data arrival""" if is_ok(data): return OK(data) if is_eof(data): if len(data) < 9: return EOF(data) return OK(data) return Packet(data)
d34873a082071a51c2dcbf269c1c74a76e2e3be8
3,616,222
def timelined_cb(data, command, rc, stdout, stderr): """Very generic callback in case timelined acts weird.""" global buffers buf = buffers[data] name = wc.buffer_get_string(buf, "name") stream = data + "STREAM" del(hooks[stream]) wc.buffer_close(buf) print_error("timelined for %s exited...
8510f6715773af5290d947963412cd63aa138023
3,616,223
import re import logging def get_gpu(): """Returns video device as listed by WMI. Not cached as the GPU driver may change underneat. """ wbem = _get_wmi_wbem() if not wbem: return None, None client = _get_win32com() dimensions = set() state = set() # https://msdn.microsoft.com/library/aa394512...
653c99f5539fafda3a7d8a641adc08c14b7b732b
3,616,225
def tfnormalize(X): """ Skip connection layer normalization. """ sh = np.shape(X) X_norm = tf.contrib.layers.layer_norm(X, trainable=False) return X
5eabf19bc7cd376af6638c092b452a239b5650d3
3,616,226
def do_filter(parser, token): """ Filters the contents of the block through variable filters. Filters can also be piped through each other, and they can have arguments -- just like in variable syntax. Sample usage:: {% filter force_escape|lower %} This text will be HTML-escape...
edd2b6ee87615a24f7f9124da5eb95b3752d7028
3,616,227
def find_ch_interest_dict(show_channel_dict : dict, usr_pref_dict : dict): """Pass in show_channel_dict {show:channels} and usr_pref_dict {show: rating}. Returns dictionary {channel : total rating}""" ch_interest_dict = {} for show in usr_pref_dict: if show in show_channel_dict: if show_...
9928b03c0ceea3ea38c3808a5fd4053553f4e5c4
3,616,228
async def discover_source_aliases(serial_port=None): """ Discover the alias configured for each input Cycle through the device sources and get the alias from the feedback message Restore the original source (which we can only do once we know its alias) Note that: - the device will be powered o...
e3a8ae0eb07d9ccc53b3150e4ad547398c4b2697
3,616,229
def compute_average_embedding(input_embeddings, input_lengths): """Computes bag-of-words embedding. Args: input_embeddings: <tf.float32>[bs, max_seq_len, emb_dim] input_lengths: <tf.int64>[bs, 1] Returns: bow_embedding: <tf.float32>[bs, emb_dim] """ max_seq_len = tf.shape(input_embeddings)[1] ...
471a56d680ec3194a48300f0d573bc54ab2708b7
3,616,230
def is_valid_int(s: str) -> bool: """ Return true if s can be converted into a valid integer, and false otherwise. :param s: value to check if can be converted into a valid integer :return: true if s can be converted into a valid integer, false otherwise >>> is_valid_int("hello") False >>> ...
9d2c849839f6fdcf729a7c1503a3eac3daa5f000
3,616,231
def validate_report_input(X, y_true=None, y_pred=None, y_prob=None, prtc_attr=None, priv_grp:int=1): """ Raises error if data are of incorrect type or size for processing by the fairness or performance reporters Args: X (array-like): Sample features prtc_attr...
d159ad9cec76e0030b881545f82f5aea81cb9849
3,616,232
def gap_statistic(X, Wk, n_components, n_trials=100, reference='uniform', n_jobs=1, random_state=None): """Calculate gap statistic for k-means clustering.""" rng = check_random_state(random_state) random_seeds = [] for _ in range(n_trials): has_seed_already = True wh...
c31bf0ac3ed664a43e49d73b514c62ca76b9f976
3,616,233