content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def even(x): """ Returns 1 if x is even, 0 otherwise. """ return x % 2 == 0
a7add035b3a39e2bd7e31a4ede9db1457a085a10
644,120
def dictUpdate(original,newer): """Combine two dictionaries. If duplicate keys exist, use the newer values to overwrite the older ones.""" for k in newer.keys(): original[k]=newer[k] return original
742ad9e4f8c4e05ddc83227e6310aaff649d5a97
644,121
import torch def collate_fn(dataBatch): """ Collate function definition used in Dataloaders. """ vis_seq_list = torch.cat([data[0] for data in dataBatch]) wordtargetBatch = torch.cat([data[1] for data in dataBatch]) return vis_seq_list, wordtargetBatch
be207f823632355ee96ea70e611c97f775d2a061
644,122
import sys import traceback def format_exception(ex): """ Format exception using traceback :param ex: """ exc_type, exc_value, exc_traceback = sys.exc_info() return repr(traceback.format_exception(exc_type, exc_value, ...
c0c4314570216c3ec23851341f2a618dd3644897
644,123
def wps_to_words(wps): """ input wp sequence and output word sequence For example: this is a g@@ oo@@ d day -> this is a good day """ s = '' for wp in wps: if wp.endswith('@@'): s += wp[0:-2] else: s += wp + ' ' return s.split()
1a5de705e1d9486fe88a1f8b7f6a7fdb47172775
644,124
def normalize_minmax(ar): """ Return the array ar scaled so that the min value is 0 and the max value is 1. """ x = ar - min(ar) mmax = max(x) if mmax == 0: return x return x/mmax
6590827e0b33a92e3c772bfd9a9a57f788f6ea10
644,125
def _is_chrome_only_build(revision_to_bot_name): """Figures out if a revision-to-bot-name mapping represents a Chrome build. We assume here that Chrome revisions are always > 100000, whereas WebRTC revisions will not reach that number in the foreseeable future. """ revision = int(revision_to_bot_name.split('...
c40ead84670aaa9435b948e16d7a12591362b5f6
644,126
async def get_json(client, url): """Llama a la url y envia su contenido a la corrutina llamante""" async with client.get(url) as response: assert response.status == 200 return await response.read()
b3553b9a8cc685623995648f434165d542000a92
644,127
def me( context, api_client, api_key, output_file, output_format, verbose, ): """Get information about the currently authenticated Sublime user.""" result = api_client.me() return result
8113e3a7f3e45bf41697936415c9ec9cf658a3a4
644,128
from typing import Union from typing import Any from typing import List from typing import Type def normalize_model_list_parameter( candidate_list: Union[Any, List[Any]], elements_number: int, object_type: Type, default_value: Any = None, can_be_empty: bool = False ) -> List[Any]: """Return gi...
2f69fb60135461e960e62cb2d6b4ddca0f615d4b
644,129
def wasp_contigs(func): """Take a wasp link, run functions on contigs """ def func_on_contigs(*wasplinks): contigs = [] for w in wasplinks: contigs += w['default_output'].files return func(contigs) return func_on_contigs
2bd62954f6673e71f25b9dc499a7f2fdaa318355
644,130
import re def parse_line(line,pattern,strict=True): """Matches given input line to regex. Line is stripped of leading/trailing whitespace. Args: line (string) : input line to parse pattern (string) : string containing regex strict (bool) : raise exception if mismatch (default: Tr...
1c73bb48277572ce408848975683c34f8c565f25
644,132
import click def main(): """Console script for jos.""" click.echo("You are running the 'jos' command-line.") return 0
7b30e795f1c0b5a1a4cd5df8d7ea0ba9dde055b6
644,133
def trim(data, meta): """ Removes the edges of the data arrays Args: dat: Data object md: Metadata object Returns: subdata arrays with trimmed edges depending on xwindow and ywindow which have been set in the S3 ecf """ data.subdata = data.data[:, meta.ywindow[0]:meta.y...
2b51ebff8af74529feb4ca8ba94e4f7252844050
644,134
def subdivideShape(shape, subdivision_level=1): """ input : shape array [37, 13, 42] output : split it subdivided shapes """ newShape = [] for i, value in enumerate(shape): newValue = value / subdivision_level for i in range(subdivision_level): newShape.append(int(newVal...
f934672bcdb93ee24893f01b4c38bc17dd1b15f4
644,135
def remote(fixture_localhost, tmpdir, generate_remote_data): """Fixture: Remote folder created by a CalcJob with inputs.""" remote = generate_remote_data( fixture_localhost, str(tmpdir), 'quantumespresso.pw', ) return remote
871ebc6fcf74ef1841710d9c71c8ea0aecca97e9
644,136
def always_defect(p, p_other_lag, p_own_lag, rounder_number): """ Return 1 if price corresponds to defection at the stage game Nash equilibrium and 0 else. """ return 1 if p == 1 else 0
a5e135f6d52f7bc61f6bda2c2763128c48d7d59e
644,137
from typing import Any from typing import List def default_value(value: Any, fallback: Any, disallowed: List[Any] = [None]) -> Any: """ Checks whether the provided value is (by default) None or matches any other disallowed value, as provided. If the value is disallowed, the fallback will be returned. ...
70aefaa302e12b611927423a39ecff4dcf9e7990
644,138
def hrule(): """ HTML horizontal rule tag: <hr> """ return '<hr>'
03ad78a44dd265e85a188e3acc7785fc735a922e
644,140
import torch def log_loss(weights, features): """ Compute logistic loss function. """ return torch.log(1 + torch.exp(weights.dot(features)))
b5487112fd4ff9811cfe032a99b851ef04cb4b31
644,142
def _get_chromosome_sequence_upper(fasta_path, fai_df, query_chrom): """ read a whole chromosome sequence into memory """ chrom_pointer = fai_df.loc[query_chrom, 'OFFSET'] tail = fai_df.loc[query_chrom, 'LINEBASES'] - fai_df.loc[query_chrom, 'LINEWIDTH'] seq = "" with open(fasta_path, 'r') a...
05bdf023b70aacf09e52c4f58b34d6889e835104
644,143
import torch def slice_patches(rays, idx, patch_size): """Extract patches from rays.""" patches = [] n_patches = idx.size(0) for v in range(n_patches): v_idx = idx[v] view = v_idx[0] top = v_idx[1] left = v_idx[2] patches.append(rays[view, top:top + patch_size, left:left + patch_size]) r...
68e90cdf21c60685cd03385fa298e109cdec8959
644,144
import tempfile import base64 def dummy_image(filetype='gif'): """Generate empty image in temporary file for testing""" # 1x1px Transparent GIF GIF = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' tmp_file = tempfile.NamedTemporaryFile(suffix='.%s' % filetype) tmp_file.write(base64.b64...
917306b8aca8bcc84ac2e5369c2271fd13b9a312
644,145
def get_play_actions(events, filter_len=5): """ Given a list of events occuring during a game, it splits the events into play actions using the following principle: - an action begins when a team gains ball possession - an action ends if one of three cases occurs: -- there is interruption of th...
ec11e17dd6320632394bfce357eba52b3d4bd189
644,146
def contains_any(string, candidates=[]): """Return True if a string contains any of the given candidate strings.""" for candidate in candidates: if candidate.lower() in string.lower(): return True return False
1c422cbc8f00c07854118784ca54454cdc9085d3
644,147
def get_table_i_3(): """表I.3 式(1)における係数 Args: Returns: list: 表I.3 式(1)における係数 """ # 表I.3 式(1)における係数 table_i_3 = [ (-0.51375, -0.57722, -0.18114, -0.30429), (-0.01782, 0.03865, 0.10483, 0.08497), (0.27640, 0.18173, 0.0, 0.0), (9.40671, 15.30711, 5.85285, 10...
534247961c87002bea72b1bb0f55162ee4a6ed27
644,148
from typing import List def get_token_bio_from_strs(tokens: List[str]) -> List[str]: """ for tokenization tasks """ bios = [] for tok in tokens: assert len(tok) != 0, "Contain invalid empty token: {} ".format(tokens) bios.append("B") _nchar_in_tok = len(tok) # token...
fa76c82a2597905013df3c628e0ee81a8444dfc2
644,149
def vec_div (v,s): """scalar vector division""" return [ v[0]/s, v[1]/s, v[2]/s ]
6e56bb65431616d3ab2e59cddb096bfc579e3894
644,150
def lista_de_compras(): """Sou, na verdade, uma tupla de coisas a serem compradas.""" return 'biscoito', 'chocolate', 'farinha'
21f3c06b592a3efad152ff6ed2a3e57c6b3c48a2
644,151
def drop_prevalent(df, threshold=0.01): """ if 99% is one single answer drop """ col_to_drop_prevalent = list() for col in df.columns: prevalent = df[col].value_counts(normalize=True).max() if 1-prevalent < threshold: col_to_drop_prevalent.append(col) return ...
2165b1c331ecb1278f65597731e0da5b08ad7bd6
644,152
import os def save2File(contents, filename, path): """Save string contents to a file, creating the file if it doesn't exist. NOTE Not generalized much, so use at your own risk. Parameters ---------- contents: str File contents filename: str Name of the file. path: str ...
1acfb0afb109891cbe8f379cdb7f7a0e5966e173
644,154
import sys def _nested_list_size(nested_list): """ Obtains the memory size for the nested list. """ total = sys.getsizeof(nested_list) for i in nested_list: if isinstance(i, list): total += _nested_list_size(i) else: total += sys.getsizeof(i) return tot...
ed8d688d9a29d0edf8248a597c8487cbc78273ea
644,155
def create_atom_pair_cst_string( resnums, lattice_space, repeat_size, cst_tolerance, sheet_mode=False, sheet_sd=0.2, ): """ Creates atom pair csts between repeats. Sheet mode adds N-O H-O also """ lines = "" cst_template = "AtomPair CA %s CA %s HARMONIC %s %s" # cst_temp...
4292dcaee317eea0dbc2c2e02ae9e1996ee3f89c
644,156
def cleanup_amendment(json_data): """Delete empty amendment add/remove arrays.""" if 'addVehicleCollateral' in json_data and not json_data['addVehicleCollateral']: del json_data['addVehicleCollateral'] if 'deleteVehicleCollateral' in json_data and not json_data['deleteVehicleCollateral']: de...
466497144be4611f71b6e1fef9e3368b04c45ced
644,157
def feed_id_from_feed_url(feed_url): """feed IDに変換します.""" return 'feed/{url}'.format(url=feed_url)
fdad558e35e9fff180374b12089cc55c168a2b87
644,159
import os def out_file_path(path, method): """ Function to build an export filepath based on the original filepath and the method being investigated. Parameters ---------- path : string absolute path of the original file method : string method of investigation (to be used...
c990f3eca2adff5fbeca10e530c73f15ee6549ed
644,160
import os import re def get_extension(filename: str) -> str: """ Returns the extension of a file/full path as a string. Emtpy if the file has no extension. .tar.xx archives are handled accordingly. """ filename = os.path.basename(filename) if re.search('\.tar\.\w{1,4}', filename): ...
bf2f947c60b4720e2ad5be4f66048cc3ae67dce4
644,162
def parse_codepoint_range(codepoints): """Parses a string that specifies a range of code points or a single code point. Returns a range of (numeric) code points.""" begin, sep, end = codepoints.partition("..") if not sep: return [int(begin, 16)] return range(int(begin, 16), int(end, 16) + 1...
1cb3ad9bc4b24158331bfb9e2548543ae0f31ddd
644,163
def add_genotype(cell_genotypes, cell_barcode, umi, genotype): """ Append genotype information for cell and UMI to dictionary return modified cell_genotypes dictionary """ try: cell_genotypes[cell_barcode] except KeyError: # haven't seen the cell, must be new UMI cell_gen...
8d0a5050c108c9e28a1190f88f5ebda4667ca13f
644,165
import yaml def get_new_addresses(config_path="./hegic_deployer/contract_config.yaml"): """Get the contract addresses from the deployer.""" with open(config_path, "r") as f: addresses = yaml.safe_load(f) print(addresses) return addresses
afdb59ed186c0c7e847bf0151893dad6af308343
644,166
def _alpha(n, threshold=30, scale=2000): """ Calculate a rough guess for the best alpha value for a default scatterplot. This is calculated with the equation .. math:: \\alpha = \\frac{0.99}{1 + \\frac{n}{\\text{scale}}} This is done so that is ranges from nearly 1 for small values of n ...
80fc718b1e624bbe91fd2f64e2c58eaa98723b8a
644,168
import numbers import torch def is_identically_zero(x): """ Check if argument is exactly the number zero. True for the number zero; false for other numbers; false for :class:`~torch.Tensor`s. """ if isinstance(x, numbers.Number): return x == 0 if not torch._C._get_tracing_state(): ...
641e57d7b09ffe6623f9f15e769ed33c0354dbea
644,169
def str13(s): """ String -> [String] """ r = [] for i in range(len(s)-12): r += [s[i:i+13]] return r
74913582821cf45e4f1471ead40018b834f36fc5
644,170
def module_common_argument_spec(): """ Returns a dict containing common options used by ansible modules :return: dict """ options = dict( state=dict(type='str', choices=['present', 'absent'], default='present'), force=dict(type='bool', default=False), ) return options
e9b4279e8585d57d512533d76ed274587482c64b
644,171
def countDetailedPathsByNode2(cursor, node2Id): """ =========================================================================== Count records of DetaildedPaths with node2Id =========================================================================== **Args**: * cursor: cursor db co...
352372ce2db865da765d6bd5a6ac216187887e02
644,172
import datetime import pandas def get_daterange(start, end=None, freq='D'): """ """ if end is None: yesterday = datetime.date.today() - datetime.timedelta(days=1) end = yesterday.isoformat() # Dates to be downloaded. return [f"{i.year}-{i.month:02d}-{i.day:02d}" for i in pandas.Series...
682ac15a1420bfc92120330ce3dc44cd156dcb0d
644,173
import time from datetime import datetime def get_current_chart(charts): """Get the current relevant chart""" current_unix_time = time.mktime(datetime.now().timetuple()) current_chart = charts[-1] for chart in charts: if float(chart.datetimestamp) <= current_unix_time: current_ch...
a136c111c827c22e397ff827158840dec9b4c91d
644,175
from typing import List def __remove_common_postfix_from_string_list( string_list: List[str]) -> List[str]: """If a list of strings share the same postfix they will be removed.""" if any([len(string) < 2 or not string for string in string_list]): return string_list uniq_last_char = len(set...
52aaa2fec053bbcd6327c58e0ea2da0a48a6a084
644,176
def format_column(column): """Convert Column to fixture format. """ return { "fields": { "name": column.name, "table_id": column.table_id, "workspace_id": str(column.workspace_id), "created_at": str(column.created_at), "updated_at": str(col...
5fc4019e40ee1b79e8f0ed719e8a42756840c830
644,177
import fnmatch def shell_match( namelist, matchlist ): """ Looks for a name in 'namelist' that matches a word in 'matchlist' which can contain shell wildcard characters. """ for n in namelist: for m in matchlist: if fnmatch.fnmatch( n, m ): return 1 return 0
634788e15d63be687945ed7042708b2ec234cf26
644,178
from typing import List def _trim_empty_lines(docstring_lines: List[str]) -> List[str]: """A helper function to remove redundant line feeds.""" i_start = 0 lines_iter = iter(docstring_lines) while not next(lines_iter): i_start += 1 i_end = len(docstring_lines) lines_iter = iter(docstr...
60d076de389feeedc31130bd4356d415da2b2ed7
644,179
import random def checkMissPlayer(defender): """ Returns a boolean token: if player missed or not. If defenders AC (Armor Class) is above players hit the token will evaluate to False, and the player will respectively miss. """ global currPlayerHitToken missChance = random.randrange(0, 25) if missChance <...
8066865a303d694044b550f96a8c5af25d988d46
644,180
def calculate_precision_recall(TP, TN, FP, FN): """ Calculates the Precision and Recall meassure of the supplied reference and test data, as per https://en.wikipedia.org/wiki/Precision_and_recall#Definition_(classification_context) Incase of the denominator being zero for precision/recall, the values are se...
5244e6021c1861e510bfcb927be918e39410c1e4
644,181
def heptagonal_n(n): """Returns the nth heptagonal number""" return int(n * (5 * n - 3) / 2)
80e996d449d19611bf1e220a0f2103d5de9adc00
644,182
def get_minimum_rect_from_contours(contours, padding=2): """ Find the minimum that include all of contour of contours array :param contours: array of contour :param padding: Add padding value for return rect :return: return rect object represent in format of (x_min, x_max, y_...
a58c30b2dc22885aff62198262f6932e982d55f5
644,183
import torch def mixup_data(x, y, l): """Returns mixed inputs, pairs of targets, and lambda""" indices = torch.randperm(x.shape[0]).to(x.device) mixed_x = l * x + (1 - l) * x[indices] y_a, y_b = y, y[indices] return mixed_x, y_a, y_b
063175fe09267684633b329cd4fa315cc1b9c89d
644,184
def untitle_str(str_): """ Untitle a string. :param str_: str; :return: str; """ str_ = str(str_) return str_.lower().replace(' ', '_').replace('-', '_')
bbde26a56627526f00326d83dce16fec707ecbf1
644,185
def _data(ident, env): """Private data function to allow repeated processing (in a loop).""" # Check if the value is defined anywhere in the environment if not ident in env: return 0 # If so, get it and query it for it's data var = env.get(ident, get_var=True) return var.data(ident)
4bb0f1d090393f29dd1627470721317fe6759fcd
644,186
import csv def read_csv_to_dict(filepath): """ read csv file. :param file_path: the path of the csv file :return: list of list """ reader = csv.reader(open(filepath, 'r')) video2gtrank = {} for x in reader: video2gtrank[x[0]] = x[1:] return video2gtrank
2171d9a847e4d11f923daf4f33d01dcc2ee4a605
644,187
from pathlib import Path def fixture_db_path(db_dir: Path, db_name: str) -> Path: """Return the path to a database""" return db_dir / db_name
bdc70c3096035296ca2dbda9728b5f143c3e77d2
644,188
def _merge_small_dims(shape_to_merge, max_dim): """Merge small dimensions. If there are some small dimensions, we collapse them: e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if max_dim = 1024 [1, 2, 768, 1, 2048] --> [2, 768, 2048] Args: shape_to_merge: Shape to merge small dimensions. ...
807cdd4682b1387405f1b0f35cb7b1858a763357
644,189
def trimhttp2(url): """ Strip 'http://' or 'https://' prefix to url """ if url[:7] == b'http://': return url[7:] elif url[:8] == b'https://': return url[8:] return url
541d698bf6fffab5f0bdf6b71a44eec48e08e9f9
644,190
def identify_nominal_indices(flat_list): """Identifies nominal values and returns their index in a list. :param flat_list: a flat list that contains elements of type `int`, `str`, `bool`, or `float`. The first 3 types are considered as nominal values. :returns: a...
35d1d0ebb1c20067573bf5064c713e5077517c3c
644,192
def styb(x): """ modified styblinski-tang """ d = len(x) sum = 0 for ii in range(0, d): xi = x[ii] new = xi ** 4 - 16 * xi ** 2 + 5 * xi sum = sum + new y = 50 - sum / 2 return y
0bdd44846123de33e23ffa5b2e74c1b780555387
644,194
def is_affiliate_empty(affiliate_obj): """ Check for an empty Affiliate object to detect for empty Excel rows. :param affiliate_obj: Affiliate :return: Boolean """ if affiliate_obj.affiliate_name is None \ and affiliate_obj.is_accs is False \ and affiliate_obj.is_pcp is F...
3e87f8dd9d9123780753eeed3ea480e90f97d013
644,195
def score_defaults(gold_labels): """ Compute the "all false" baseline (all labels as unrelated) and the max possible score :param gold_labels: list containing the true labels :return: (null_score, best_score) """ unrelated = [g for g in gold_labels if g['Stance'] == 'unrelated'] null_sco...
7c3f794f364975a5090892e1d60d7142695573db
644,197
def get_parsed_context(context_arg): """Return context arg stub.""" return {'parsed_context': context_arg}
9787f92b8a65e2f61176559af29ac50fd1186eeb
644,198
def get_labels(path, name, negative_label="no_relation"): """See base class.""" with open(path + "/" + name, "r") as f: features = [] for line in f.readlines(): line = line.rstrip() if len(line) > 0: features.append(eval(line)) return features
259d0fe1354fb1d663f9767ad1c3f55f08b8fa0a
644,199
from typing import List import requests import string def get_public_suffixes() -> List[str]: """ Retrieves an extensive list of public suffixes used and filters out non ASCII suffixes. In case of any issues connecting to the website this function returns a much less comprehensive builtin list. ""...
24993476cba0ddec3f60cd72e745a77874e37b20
644,200
def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ return list(set(range(1, len(nums)+1)) - set(nums))
510d8e9dc38ff6483c8c86a43eed861d4aa582fc
644,202
def task_locks_resource(task, resources): """ Checks if a task locks the resources. This is used for checking if a resource is occupied storing a link between protocol actions :param task: type DAGSubTask The task that may/may not lock the resources :param resources: type list List o...
2bfbe4592f28af392b906c2769210ed648edcd7b
644,203
def str2bool(v): """Bodge around strange handling of boolean values in ArgumentParser.""" return v.lower() in ('yes', 'true', 't', '1')
ed3922f193477f0c691c8b2eda253ff9b128327f
644,204
def strip_right_above_below(chars): """Drop leading and trailing blank lines, and drop trailing spaces in each line""" lines_plus = chars.splitlines() lines = list(_.rstrip() for _ in lines_plus) while lines and not lines[0]: lines = lines[1:] while lines and not lines[-1]: lines ...
bef9218dc7a2aed5ca9beae40246cbd6542bf11a
644,205
def append_query_attrs_odc(ds, bbox, collections, bands, resolution, dtype, fill_value, slc_off, resampling): """ Takes a newly constructed xr dataset and appends some of the original query parameters (e.g., collections, bands, bbox, slc-off) to assist in updates later on. Parameters ------...
1fab084ee1567b2883c8783773887d47b121b417
644,208
import csv def get_max_node_id(nodes_file): """ Examines the 'nodes_file' passed in and finds the value of highest node id. It is assumed the 'nodes_file' a tab delimited file of format: <CLUSTER NAME> <# NODES> <SPACE DELIMITED NODE IDS> <SCORE> :param nodes_file: :type nodes_file:...
76a580eba12767a113f288cf367de834d5b4b104
644,209
def create_map(mapping_table): """Create table to hold mappings of statbank variables """ mapping_table.create(checkfirst=True) return mapping_table
dd7cc081d6c4f4ceef3347b45b7102d4c70b8d0f
644,210
def hexadecimal(): """Hexadecimal representation.""" return "{0:x} or {0:X}".format(2**8-1)
07140b16c69c11e7e534dc3ae75a122d5e4e48b6
644,211
def get_verbose_field_name(instance, field_name): """ Get the verbose_name for a field in a model instance Parameters ---------- instance : Django models.Model An instance of any sub-class of a Django models.Model field_name : str Name of the field to return the verbose field na...
3d1dd01270857ef3215b88b5a7c31e7655906f95
644,212
def _split_channels(num_chan, num_groups): """Split range(num_chan) in num_groups intervals. The first one is larger if num_chan is not a multiple of num_groups""" split = [num_chan // num_groups for _ in range(num_groups)] # add the remaining channels to the first group split[0] += num_chan - sum(split...
9546d317f297584167a411b2702d442553f5bffa
644,213
def calc_crc(data): """Calculate frame CRC.""" crc = 0x2d for b in data: crc += b return crc & 0xff
3ee7530ab8fa252907acabeca4e000b2a9facadc
644,214
def time_info(cli): """Return time/timezone info by running 'date' command""" return cli.exec_command('date\n')
ad92006993729d3f9323309adc9e11ca5a3d76c5
644,216
def MPO_change(df, date_, visa_, reduction): """Adjust a visatype, year by a fixed amount - distributing across visa types on basis of share change_array = ( ("2020-09" ,( "family"), 2_500), ("2020-12" , "family", 2_500), ("2020-09" , "skill_permanent", 5_000), ("2020-12" , "ski...
8e1c65d9d324616b7e0afa7fd8eaa97617af0e2f
644,218
import uuid from datetime import datetime def _send_event(relay, project_id=42, event_type="error"): """ Send an event to the given project. If the project doesn't exist, relay should generate INVALID outcome with reason "project_id". """ event_id = uuid.uuid1().hex message_text = "some messa...
eb91440a1880b0c6c61acbba9f7a7ee8d170ca6a
644,219
def get_instances_joined(game, player): """ Return the instance ids of instance that player has joined. Args: game: The parent Game database model to query for instances. player: The email address of the player to look for in instances. Returns: An empty list if game is None. Else, returns a list of...
3c968b614d15d2986c076588fa24a4ee3d1b1ca2
644,220
def partial(element, function): """ partial : sympy.core.symbol.Symbol * sympy.core.add.Add -> sympy.core.add.Add partial(element, function) Performs partial derivative of a function of several variables is its derivative with respect to one of those variables, with the others held constant. Return partial_...
030fbfddda0bef1eac48a518f0a63cb143e436e6
644,223
import torch def clone(tensor, device=None): """Clone a list of tensors.""" if not isinstance(tensor, torch.Tensor): return [clone(t) for t in tensor] cloned = tensor.detach().clone() cloned.requires_grad = tensor.requires_grad if device is not None: cloned = cloned.to(device) ...
a579e50f746570f6f2c927cfa21aded8b7754744
644,224
def rearrange(arr: list) -> list: """ Simplest approach would be to create and fill a temp array. But it would require extra space. In case there is only one cycle (test case 1), it is easy to do it in one loop. In case of multiple cycles(test case 2), the solution becomes more convulated We...
99160102d527de9f0e75736766a1292164a8d786
644,225
def node_abs_paths(node): """Return absolute node path name.""" node_names = node.name.split('/') return ['/'.join(node_names[0:i + 1]) for i in range(len(node_names))]
fe665242affd380801299444ccc6690f2342f18b
644,226
def _get_timestamps(ix_list, ix, orig_ixs): """Returns the first and the last position in a list of an index. Args: ix_list (List): A sorted list of indicies, indicies appear multiple times ix (Int): Index Returns: Tuples: Returns two tuples. """ first_ix = ix_list.index(ix...
c58541071034674c2758d2227949cf2bfe506ae7
644,228
def is_subset(a, b): """Test whether every element in a is also in b.""" return set(a).issubset(set(b))
da8c42d9299b4e37d6f71a23c84e51506e69fb0e
644,229
def read_ppm_header(fp, filename): """Read dimensions and headersize from a PPM file.""" headersize = 0 magic_number = fp.readline() if magic_number != "P6\n": raise TypeError("Hey! Not a ppm image file: %s" % filename) headersize += len(magic_number) comment = fp.readline() if comment[0] == "#": ...
0b7540ad5dc505e313393e9d6a5f870fb95185fa
644,230
def readFile(nam): """ Read a file and return its content as a string. """ f = open(nam,"r") s = f.read() f.close() return s
35a7b1f044807872ab514ef08b46e91646415b7e
644,231
import numpy def pad(mat, padrow, padcol): """ Add additional rows/columns to a numpy.matrix `mat`. The new rows/columns will be initialized with zeros. """ if padrow < 0: padrow = 0 if padcol < 0: padcol = 0 rows, cols = mat.shape return numpy.bmat([[mat, numpy.matrix(...
bb3f25d1266573f74d77a2ad673d618806a59b93
644,232
def top_players_stat(fifa_df, stat, no_of_players): """ Returns the top x no players in a stat Parameters ---------- fifa_df The fifa versions players (df) no_of_players The number of players to return (int) stat The stat to sort by (str) Returns ------- ...
989dcc66e62236a797915fd25dd85c00a0fb6ca8
644,233
def _remove_invalid_uris(uris_and_names): """ Remove as URIs inválidas, isto é, que não inicializam com o termo http. Parameters ---------- uris_and_names : list Uma lista contendo dicionários do tipo {"uri": str, "name": str}. Returns ------- list Uma lista contendo di...
e95017a1d53f01fdfa78df80465477fd99b94810
644,234
import os def which(executable): """See if executable exists.""" location = None if os.path.basename(executable) != executable: if os.path.isfile(executable): location = executable else: paths = [x for x in os.environ["PATH"].split(os.pathsep) if not x.isspace()] f...
da75fae258c10f4b974309e6e36516082a0cba66
644,235
def df_to_features(vectorizer, df, split): """Convert pandas DataFrame containing spam data to bag-of-words PyTorch features.""" words = [row.text for i, row in df.iterrows()] if split == "train": feats = vectorizer.fit_transform(words) else: feats = vectorizer.transform(words) X = ...
96fab8ae7fb31d264ffd9f5fbc69959322ea3731
644,236
def get_the_node_dict(G, name): """ Helper function that returns the node data of the node with the name supplied """ for node in G.nodes(data=True): if node[0] == name: return node[1]
d73db645177f00377ae1f202181b69d2f51d540b
644,237
import json def load_data(path='../../../../data/multiwoz/test.json'): """Note that the path parameter indicates the path of testing file.""" data = json.load(open(path)) result = [] for id, session in data.items(): log = session['log'] turn_data = ['null'] goal = session['goal...
88765d2e29fec9914d343a9605332531289e8b62
644,238
def make_kw(bbox, time_range): """Make kw for search. Parameters ---------- bbox: list Geographic bounding box: [min_lon, min_lat, max_lon, max_lat] time_range: list [start_time, end_time] where each are strings that can be interpreted with pandas `Timestamp`. Returns ...
887a41a65454284c82e00c76b3864313e7bb4549
644,240