content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def need_verified_email(request, *args, **kwargs): # pylint: disable=unused-argument """ Returns error page for unverified email on edX """ return standard_error_page(request, 401, "verify_email.html")
258f0cd7cc9d48724a4192397742ad476baf0aaf
335
def random_masking(token_ids_all): """对输入进行随机mask,增加泛化能力 """ result = [] for token_ids in token_ids_all: rands = np.random.random(len(token_ids)) result.append([ t if r > 0.15 else np.random.choice(token_ids) for r, t in zip(rands, token_ids) ]) return...
5798fd271b6f8a1749ef04139c44a53ef2801473
336
def used_caches_and_sources(layers, caches, sources): """ Find used cache and source names in layers and caches configuration. """ used_layer_sources = find_layer_sources(layers) used_cache_sources = find_cache_sources(caches) all_used_sources = used_layer_sources.union(used_cache_sources) ...
21df59bea5cf4d336f9f103de841bfbbedadf3d5
338
from typing import Union def encode_labels( labels: Union[list, np.ndarray, pd.Series], multi_label: bool = False, sep: str = '|' ): """Encode labels Return coded labels, encoder, and decoder. Examples: >>> # multi-class problem >>> labels = ['OK', 'OK', 'NG1', 'NG2', 'OK'] ...
2cd3ec563edfe0d0f42df3018bfd2cf007738c9d
339
def sigmoid_xent(*, logits, labels, reduction=True): """Computes a sigmoid cross-entropy (Bernoulli NLL) loss over examples.""" log_p = jax.nn.log_sigmoid(logits) log_not_p = jax.nn.log_sigmoid(-logits) nll = -jnp.sum(labels * log_p + (1. - labels) * log_not_p, axis=-1) return jnp.mean(nll) if reduction else ...
a427532ddf0feba69879bc5b5d5a9a34d71d9ca6
340
def is_palindrome(s: str) -> bool: """Return whether a string is a palindrome This is as efficient as you can get when computing whether a string is a palindrome. It runs in O(n) time and O(1) space. """ if len(s) <= 1: return True i = 0 j = len(s) - 1 while i < j: if ...
6d3001486fe3603a17e72861e3bdea495cd675c1
341
def accuracy(pred_cls, true_cls, nclass=3): """ compute per-node classification accuracy """ accu = [] for i in range(nclass): intersect = ((pred_cls == i) + (true_cls == i)).eq(2).sum().item() thiscls = (true_cls == i).sum().item() accu.append(intersect / thiscls) return...
208c2e31b5df37179b2d67a2b8423c3236c64264
342
def my_hostogram(gray, bins): """ pixel values has to be within bins range, otherwise index out of range, for example if pixel 400th has value 70, but bins are -> [0...40], then histogram[70] yields IOR """ histogram = [0 for i in bins] for i in range(gray.shape[0]): for j in range(gray....
a2e774fb7b2249325191b20e6fa08847e38211c2
343
def reverse(password, position_x, position_y): """Reverse from position_x to position_y in password.""" password_slice = password[position_x:position_y + 1] password[position_x:position_y + 1] = password_slice[::-1] return password
46fec2c6b9c02d8efa71d53451974e46cbe68102
344
from typing import Union from typing import List import random def gen_sentence( start_seq: str = None, N: int = 4, prob: float = 0.001, output_str: bool = True ) -> Union[List[str], str]: """ Text generator using Thai2fit :param str start_seq: word for begin word. :param int N: number of wor...
800b498498396a4cda84885481b09df689f541aa
345
def GetBoolValueFromString(s): """Returns True for true/1 strings, and False for false/0, None otherwise.""" if s and s.lower() == 'true' or s == '1': return True elif s and s.lower() == 'false' or s == '0': return False else: return None
d6ef53e837fc825a32e073e3a86185093dd1d037
346
def genomic_del6_abs_37(genomic_del6_37_loc): """Create test fixture absolute copy number variation""" return { "type": "AbsoluteCopyNumber", "_id": "ga4gh:VAC.60XjT6dzYKX8rn6ocG4AVAxCoUFfdjI6", "subject": genomic_del6_37_loc, "copies": {"type": "Number", "value": 1} }
64d8bb95768587adef71c8a98111e0454dfdbb93
347
def get_typical_qualifications(cfg): """ create qualification list to filter just workers with: - + 98% approval rate - + 500 or more accepted HIT - Location USA :param cfg: :return: """ if not cfg['hit_type'].getboolean('apply_qualification'): return [] qualification_re...
4cfad92d7c2587e2fce1caeac032a69f87c70c01
348
def _shell_wrap_inner(command, shell=True, sudo_prefix=None): """ Conditionally wrap given command in env.shell (while honoring sudo.) (Modified from fabric.operations._shell_wrap to avoid double escaping, as the wrapping host command would also get shell escaped.) """ # Honor env.shell, while ...
6a1a185262e312aac193b70babf9c4b8c1fc2c73
350
from typing import List import time def events_until(events: List[ScheduleEvent], until: time, *, after: time = None) \ -> List[ScheduleEvent]: """ Return events up to and including the given time. Keyword arguments: after -- if specified, only events after this time...
8d7390c684fb5590ad1fbdaa0680b3aff7474c56
351
import socket def get_ip(): """ Get local ip from socket connection :return: IP Addr string """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('bing.com', 80)) return s.getsockname()[0]
9afb9cfc5721ea7a89764579bd878a9b51361af2
352
import unicodedata def shave_marks(txt): """去掉全部变音符号""" norm_txt = unicodedata.normalize('NFD', txt) # 把所有的字符分解为基字符和组合记号 shaved = ''.join(c for c in norm_txt if not unicodedata.combining(c)) # 过滤掉所有的组合记号 return unicodedata.normalize('NFC', shaved)
0b8e15c72854a5bca7b12f6452292d7472bbf1bc
353
def _kld_gamma(p_data, q_data): """ Computes the Kullback-Leibler divergence between two gamma PDFs Parameters ---------- p_data: np.array Data of the first process q_data: np.array Data of the first process Returns ------- r_kld_gamma: numeric Kullba...
c20fd6764299300dc555bca356d9942e98d38214
354
def interpolate_rat(nodes, values, use_mp=False): """Compute a rational function which interpolates the given nodes/values. Args: nodes (array): the interpolation nodes; must have odd length and be passed in strictly increasing or decreasing order values (array): the values at the i...
cdc98a0a04a6d35fb409fb4235dab759c1f96c1c
355
import re def binder_update_page_range(payload): """Parser for `binder_update_page_range`""" try: match = re.match(binder_update_page_range_pattern, payload) if match: match_group_dict = match.groupdict() return BinderUpdatePageRange(int(match.group(1)), int(match.group...
82f3bc931bebc5816b38feb75f918779fa271840
356
import re def generate_breadcrumb(url: str, separator: str) -> str: """ Fungsi yang menerima input berupa string url dan separator dan mengembalikan string yang berisi navigasi breadcrumb. Halaman Wikipedia tentang navigasi breadcrumb: https://en.wikipedia.org/wiki/Breadcrumb_navigation Cont...
8fc4e84ba68a5ff0d359ded9c70aef9ebec89b32
357
from pathlib import Path def extract_all_sentences(dataset_path, features_outfile=None): """ Extract features from sentences using pretrained universal sentence embeddings and save them in a pickle file :param dataset_path: the path of the dataset to use :param features_outfile: file used to store the ex...
259ef284310c8bc2a52aa201ec17522e4b00b6d1
359
def search_sorted(array, value): """ Searches the given sorted array for the given value using a BinarySearch which should execute in O(log N). array a 1D sorted numerical array value the numerical value to search for returns index of array closest to value returns None if valu...
6eec5fb24cd2da1989b4b80260ce185191d782f1
362
from typing import Dict import attr def to_doc(d: DatasetDoc) -> Dict: """ Serialise a DatasetDoc to a dict If you plan to write this out as a yaml file on disk, you're better off with `to_formatted_doc()`. """ doc = attr.asdict( d, recurse=True, dict_factory=dict, ...
83a3ca0838074e000238765c34067e8086e4a2ab
363
def annealing_exp(start, end, pct): """Exponentially anneal from start to end as pct goes from 0.0 to 1.0.""" return start * (end / start) ** pct
4517b07ad7d065a1ba8d4f963c688677846640e3
364
def _compile_theano_function(param, vars, givens=None): """Compile theano function for a given parameter and input variables. This function is memoized to avoid repeating costly theano compilations when repeatedly drawing values, which is done when generating posterior predictive samples. Paramete...
bed6879a63beebe3af8eaabf654e5617e550e971
365
def redirect(url): """Create a response object representing redirection. :param url: a URL :return: a Response """ headers = { "Location": url, } return Response(headers=headers, code=HTTPStatus.FOUND)
13a61d5854fd5ef50ce51e38a0dc38af282a5693
366
import json def remove_ordereddict(data, dangerous=True): """turns a nested OrderedDict dict into a regular dictionary. dangerous=True will replace unserializable values with the string '[unserializable]' """ # so nasty. return json.loads(json_dumps(data, dangerous))
f5ca4db424c721a5e9015e77cd727f71b3912699
367
from typing import List def evaluate_v1(tokens: List[str]) -> Number: """Evaluates a tokenized expression and returns the result""" stack: List = [] for token in tokens: stack = consume_token(token, stack) return get_result_from_stack(stack)
1507baf55f427096b12690d76854d0189ec1571e
368
def load_gromacs_reaction_coord_files(us_path, n_wins, step=10, verbose=False): """ Parameters ---------- us_path: string Path to the xvg files with sampled reaction coordinate values n_wins: integer Number of umbrella runs step: integer Time interval for analysis ver...
47a304592306b142b96638f40410685ce31e0482
369
from typing import Dict def h_customer_role_playing( process_configuration: Dict[str, str], h_customer: Hub, staging_table: StagingTable ) -> RolePlayingHub: """Define h_customer_role_playing test hub. Args: process_configuration: Process configuration fixture value. h_customer: Hub custo...
f8f6fadc9dad8c637fbf173a2d10378f087954f6
370
def _js_requires(offline: bool = False) -> str: """Format JS requires for Plotly dependency. Args: offline: if True, inject entire Plotly library for offline use. Returns: str: <script> block with Plotly dependency. """ helper_fxns = _load_js_resource(_AxPlotJSResources.HELPER_FXN...
cc5bf8b5c6a840b9905008c0986f5b7ef65d6942
374
def resnet_retinanet(num_classes, backbone='resnet50', inputs=None, modifier=None, **kwargs): """ Constructs a retinanet model using a resnet backbone. Args num_classes: Number of classes to predict. backbone: Which backbone to use (one of ('resnet50', 'resnet101', 'resnet152')). inputs...
9e44d811cc0da8e7810731379259f8921483e907
375
def trans_full_matrix_projection(input, size=0, param_attr=None): """ Different from full_matrix_projection, this projection performs matrix multiplication, using transpose of weight. .. math:: out.row[i] += in.row[i] * w^\mathrm{T} :math:`w^\mathrm{T}` means transpose of weight. The ...
c8c69a01bf311d449ec6b9af68d61fe917073c75
376
def http_head_deck_etag(gist_url): """Perform a HEAD against gist_url and return the etag.""" class HeadRequest(Request): def get_method(self): return 'HEAD' head_request = HeadRequest(gist_url + '/raw') response = urlopen(head_request) headers = response.headers etag = h...
b5f4d4ebb80ec95059562c500edc8fc3a4040064
377
def _get_fluxes(sol, reactions): """Get the primal values for a set of variables.""" fluxes = { r.id: sol.fluxes.loc[r.community_id, r.global_id] for r in reactions } return pd.Series(fluxes)
da5ff0af1a3072baca70ac338ee29a7ea91606ac
378
def compatible_elfs(elf1, elf2): """See if two ELFs are compatible This compares the aspects of the ELF to see if they're compatible: bit size, endianness, machine type, and operating system. Parameters ---------- elf1 : ELFFile elf2 : ELFFile Returns ------- True if compatibl...
808c52de45e96d177429ebe1339f4a97c2c219d0
379
def _tear_down_response(data): """Helper function to extract header, payload and end from received response data.""" response_header = data[2:17] # Below is actually not used response_payload_size = data[18] response_payload = data[19:-2] response_end = data[-2:] return response_header, ...
0c9684c2c054beaff018f85a6775d46202d0095a
381
import pymysql def read_data_from_bd(query, host, user, port, database, password): """ get data from abc database arg: query: sql username: database username password: datab...
a7ff96f9bda9b71bced1baaceeeb7c7797839bb4
382
def stack_atomic_call_middleware(q_dict, q_queryset, logger, middleware): """ Calls the middleware function atomically. * Returns cached queue on error or None """ cached_q_dict = q_dict[:] cached_q_query = q_queryset.all() try: middleware(q_dict, q_queryset, logger) except: ...
9d01c51e19702ba4bc0ae155f0b9b386a4d947b6
383
def collate_with_neg_fn(generator): """Collate a list of datapoints into a batch, with negative samples in last half of batch.""" users, items, item_attr, num_attr = collate_fn(generator) users[len(users) // 2:] = users[:len(users) // 2] return users, items, item_attr, num_attr
189104ba993e522a1a5f7b40dfcaa06b25e69966
384
def build_scenario_3(FW, verbosity=None): """ Tests if override is cleared when all switch behaviours go out of scope. And tests switch command with opaque value. Returns a list of 2-lists: [time, 0ary function] that describes exactly what needs to be executed when. The 0ary functions return a fals...
a676d7997affcb92ea19dc007a8c38eebc919af3
385
def read(input): """Read an entire zonefile, returning an AST for it which contains formatting information.""" return _parse(input, actions=Actions())
46cbef9f1b5f85705166ec0527f60e8346157955
386
def generate_conditionally(text='welcome', random_seed=1, **kwargs): """ Input: text - str random_seed - integer Output: stroke - numpy 2D-array (T x 3) """ model = ConditionalStrokeModel.load( str(MODEL_DIR / 'conditional-stroke-model'), batch_size=1, rnn_steps=1,...
e58a06fc620a71e6ff0704bfe5cae3693ef5f758
387
import torch def cross_entropy(pred, soft_targets): """ pred: unscaled logits soft_targets: target-distributions (i.e., sum to 1) """ logsoftmax = nn.LogSoftmax(dim=1) return torch.mean(torch.sum(-soft_targets * logsoftmax(pred), 1))
1a81e36a9839600bd621ec0e3bb0da1d5fca0c0a
388
def get_credentials(_globals: dict): """ Gets Credentials from Globals Structure may be found in modules/ducktests/tests/checks/utils/check_get_credentials.py This function return default username and password, defaults may be overriden throw globals """ if USERNAME_KEY in _globals[AUTHENTICATIO...
2ca95af842f1e68eb31b452374adec4d0b830383
391
def hideablerevs(repo): """Revision candidates to be hidden This is a standalone function to allow extensions to wrap it. Because we use the set of immutable changesets as a fallback subset in branchmap (see mercurial.branchmap.subsettable), you cannot set "public" changesets as "hideable". Doing ...
caf59496abeb0f6d42063509f3357c7520a90d82
392
import torch def squeeze_features(protein): """Remove singleton and repeated dimensions in protein features.""" protein["aatype"] = torch.argmax(protein["aatype"], dim=-1) for k in [ "domain_name", "msa", "num_alignments", "seq_length", "sequence", "superfam...
05c1a174935f7ebe845a0a3b308ca933baccfde6
393
import pathlib def get_cache_dir(app_name: str, suffix: str = None, create: bool = True): """Get a local cache directory for a given application name. Args: app_name: The name of the application. suffix: A subdirectory appended to the cache dir. create: Whether to create the directory...
40db55ce5d891a5cd496d23760ac66fe23206ed7
394
import random import pickle def _dump_test_data(filename, num_per_type=10): """Get corpus of statements for testing that has a range of stmt types.""" sp = signor.process_from_web() # Group statements by type stmts_by_type = defaultdict(list) for stmt in sp.statements: stmts_by_type[stmt._...
4eb2fbcfc6524d3f10c92e13f01475834f26f7f2
395
def gin_dict_parser(coll): """ Use for parsing collections that may contain a 'gin' key. The 'gin' key is assumed to map to either a dict or str value that contains gin bindings. e.g. {'gin': {'Classifier.n_layers': 2, 'Classifier.width': 3}} or {'gin': 'Classifier.n_layers = 2\nClassifier.w...
d47fa1785948d70e5bf4575ed879fe37827db6ba
396
def ones(shape, dtype): """ Declare a new worker-local tensor with all elements initialized to one. :param shape: the tensor shape :param dtype: the tensor data type :return: the tensor expression """ np_dtype = DType(dtype).as_numpy() init = _ConstTensor(np.ones(shape, dtype=np_dtype))...
7345dad51739c1ada5dfd89ae9c0d0b21df54ce8
397
def _valid_url(url): """Checks that the given URL is Discord embed friendly. Or at least, it tries.""" def _valid_string(segment, main=True): if not len(segment): return False for c in [ord(it.lower()) for it in segment]: if not (97 <= c <= 122 or (main and (48 <= c <= 5...
74d359bc2c8430fc5990cead6695626ea825db64
398
def isText(node): """ Returns True if the supplied node is free text. """ return node.nodeType == node.TEXT_NODE
150efc016028d0fab4630ad5e754ebaeed0c82c0
399
def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext') -> 'Descriptor': """ :meta private: Parse a descriptor given the context level we are in. Used recursively to parse subdescriptors :param desc: The descriptor string to parse :param ctx: The :class:`_ParseDescriptorContext` indic...
7c755482ba31ce656ae597eeb166de9cfaa2f649
400
def get_editable_fields(cc_content, context): """ Return the set of fields that the requester can edit on the given content """ # For closed thread: # no edits, except 'abuse_flagged' and 'read' are allowed for thread # no edits, except 'abuse_flagged' is allowed for comment ret = {"abuse_f...
19cea27fdda79b365c25329851bb7baf8d18bcac
401
def rate_of_matrix_function(A, Adot, f, fprime): """Find the rate of the tensor A Parameters ---------- A : ndarray (3,3) A diagonalizable tensor Adot : ndarray (3,3) Rate of A f : callable fprime : callable Derivative of f Returns ------- Ydot : ndarray...
404d189b2bc6cc91c30ef857a8ebef7cc0db49d9
402
def enumerate_changes(levels): """Assign a unique integer to each run of identical values. Repeated but non-consecutive values will be assigned different integers. """ return levels.diff().fillna(0).abs().cumsum().astype(int)
4787c0e84d6bca8f6038389e5bebf74317059ed8
403
def TDataStd_ByteArray_Set(*args): """ * Finds or creates an attribute with the array. If <isDelta> == False, DefaultDeltaOnModification is used. If attribute is already set, all input parameters are refused and the found attribute is returned. :param label: :type label: TDF_Label & :param lower: ...
a0f3402e1106021affb3dfe12fe93c5ae8ed2dad
404
def _get_total_elements(viewer) -> int: """ We need to fetch a workflows listing to figure out how many entries we have in the database, since the API does not contain a method to count the DB entries. :param viewer: CWL Viewer instance URL :return: number of total elements in the CWL Viewer in...
a7289ed13546b68e381793e0fdd8410f986f87d4
405
def entrepreneursIncubated(dateFrom=None, dateTo=None): """ Returns all entrepreneurs ages count between a set of ranges """ queryset = Stage.objects output = { 'queryset': None, 'fields': [], 'values': [], 'fieldLabels': [], } queryset = queryset.filter(stage...
5b06dc8a9ca15357ecab20e615d329fcaaffc8d8
406
def get_steps(x, shape): """ Convert a (vocab_size, steps * batch_size) array into a [(vocab_size, batch_size)] * steps list of views """ steps = shape[1] if x is None: return [None for step in range(steps)] xs = x.reshape(shape + (-1,)) return [xs[:, step, :] for step in range(s...
44133ddd1ad78b3ea05042c6c16558bb982c9206
407
def LHS( a: int, operation1: str, b: int, operation2: str, c: float ): """ E.g. LHS(a, 'plus', b, 'times', c) does (a + b) * c params: a: int. First number in equation operation1: str. Must be 'plus', 'minus', 'times', 'divide' b : int. Second num...
af023f3cd70d123492c8a6abb92d7ae2994b56ae
408
import math def _validate(api_indicator_matype, option, parameters:dict, **kwargs): # -> dict """Validates kwargs and attaches them to parameters.""" # APO, PPO, BBANDS matype = int(math.fabs(kwargs["matype"])) if "matype" in kwargs else None if option == "matype" and matype is not None and matype in...
d73903514aa87f854d08e3447cca85f64eaa4b31
409
def scale_y_values(y_data, y_reference, y_max): """ Scale the plot in y direction, to prevent extreme values. :param y_data: the y data of the plot :param y_reference: the maximum value of the plot series (e.g. Normal force), which will be scaled to y_max :param y_max: the maximum y value...
b3b22b0f868ce46926a4eecfc1c5d0ac2a7c1f7e
410
def set_heating_contribution(agent, pv_power): """ If the water tank is currently in use, compute and return the part of the pv_power used for heating the water""" pv_power_to_heating = 0 if agent.water_tank.is_active(): pv_power_to_heating = pv_power * agent.pv_panel.heating_contribution return...
ece29b7f0fbbe10907ada8fd1450919f01ab74c3
411
import tqdm def predict_direction(clf, tickers, **kwargs): """ Use clf (an untrained classifier) to predict direction of change for validation data for each stock in 'tickers'. Pass additional keyword arguments to be used in building the stock datasets. Args: --clf: An untrained sklearn class...
798e25d3b652227407b50e8eec9f0289770d9d9a
412
def parse_primary(index): """Parse primary expression.""" if token_is(index, token_kinds.open_paren): node, index = parse_expression(index + 1) index = match_token(index, token_kinds.close_paren, ParserError.GOT) return expr_nodes.ParenExpr(node), index elif token_is(index, token_kin...
2413a0793062e2cfa52fb8d922c21a3af7d06a66
414
def chopper_pulses_of_mode(i): """How many single pulses the chopper transmits per opening, or in hybrid mode, how many single bunches the tranmitted intensity corresponds to, based on the current settings of the chopper. i: 0-based integer""" if isnan(i) or i<0 or i>=len(chopper.pulses): return nan...
c10ade662b515cfdde721b9c7c8cb2aac7fa8c03
415
def _get_content_from_tag(tag): """Gets the content from tag till before a new section.""" contents = [] next_tag = tag while next_tag and not _is_section(next_tag): content = parse_content(next_tag.text()) if content: contents.append(content) next_tag = next_tag.next...
832f01b7db2a5c2cdcc3454b1253a8399464952e
416
async def get_connections(request: data_models.ConnectionsRequest): """Get connections *from* and *to* each entity in the request. Connections *to* are all the subject-predicate pairs where the entity is the object, and connections *from* are all the predicate-object pairs where the entity is the subject.""" ...
e25a363cbd4cbbaa7a2f36132f73fcfa2ebd1d3c
417
def sunlight_duration(hour_angle_sunrise): """Returns the duration of Sunlight, in minutes, with Hour Angle in degrees, hour_angle.""" sunlight_durration = 8 * hour_angle_sunrise # this seems like the wrong output return sunlight_durration
b2887dd86caf25e7cac613bfa10b4de26c932c09
418
import warnings def add_particle_bunch_gaussian(sim, q, m, sig_r, sig_z, n_emit, gamma0, sig_gamma, n_physical_particles, n_macroparticles, tf=0., zf=0., boost=None, save_beam=None, z_injection_plane=None, ...
3aedae4d9ff7ec6026b3153946939858db48d332
419
def sell_shares_nb(cash_now, shares_now, size, direction, price, fees, fixed_fees, slippage, min_size, allow_partial, raise_reject, log_record, log): """Sell shares.""" # Get optimal order size if direction == Direction.LongOnly: final_size = min(shares_now, size) else: ...
cf16446421ae19aa7f1d142ee195d5d9dfa20bdf
420
import traceback def handler_no_answer(f): """Decorator that creates message handlers that don't reply.""" def handle_wrapper(*args, **kwds): answer = None try: f(*args, **kwds) except Exception: return MSG_STATUS_ERROR, [ 'Calling the cmd handl...
79f1e0d30eab4d7beb500a3a75f7b7e4415e311c
422
import re def wrapper_handle_attrs(func): """转化html的标签属性为字典""" # 这是一个装饰Parsing.handle_attrs_tmp、Parsing.handle_attrs_tag的装饰器 def handle_attrs(self, attrs_str): attrs = dict() if attrs_str == '/': return attrs attrs_list = re.findall(self.attr_reg, attrs_str) fo...
d7396433c9721c26c8d419d4e78f2b8445f5dd70
423
def transfer_weights(model, weights=None): """ Always trains from scratch; never transfers weights :param model: :param weights: :return: """ print('ENet has found no compatible pretrained weights! Skipping weight transfer...') return model
2b8b5e7d3ad72deea42ffccea6a561eac3b72320
424
def collapse_json(text, indent=4): """Compacts a string of json data by collapsing whitespace after the specified indent level NOTE: will not produce correct results when indent level is not a multiple of the json indent level """ initial = " " * indent out = [] # final json output sub...
625868ca90aab0be50cf6d2fdb2926d395d83301
425
import ast def get_skills_v1(): """ READING THE FIRST SKILLSET """ f = open('skills_v1.json', 'rb') for a in f: skills_v1 = ast.literal_eval(a) f.close() return skills_v1
c71b7ed4fc6579ea21a0aecceaf38be81a32964b
426
from typing import Tuple from typing import List from typing import Counter def create_mask(board: np.ndarray, dimensions: Tuple[int, int]) -> List[List[int]]: """ Function to create Mask of possible valid values based on the initial sudoku Board. """ mask = list(board.tolist()) counts = Counter(board.fl...
a8e4c68a55c96ad7502464934226f8909dbf18cd
427
def telegram(text: str, token: str, chat_id: int) -> str: """Send a telegram message""" webhookAddress = f"https://api.telegram.org/bot{token}/sendMessage?" + urlencode({"text":text, "chat_id":chat_id}) handler = urlopen(webhookAddress) return handler.read().decode('utf-8')
c80727f5e482b3e9bb48c28c3cc9e688228733fc
428
def match_term(term, dictionary, case_sensitive, lemmatize=True): """ Parameters ---------- term dictionary case_sensitive lemmatize Including lemmas improves performance slightly Returns ------- """ if (not case_sensitive and term.lower() in dictionary) or term in dicti...
aba706a211cf68e7c8c1668200da3f9c8613b3d2
429
import requests import json import csv def fill_user(user_ids, filename='user', write=True): """ Input: user_ids dictionary (user ids: task values) Output: csv file with user id, name, email """ emails = {} for user in user_ids: r = requests.get('https://pe.goodlylabs.org' ...
0ee2eb7104ee177a13d78e6e05b6fb787736bb06
430
def project_along_flow(dX_raw,dY_raw,dX_prio,dY_prio,e_perp): """ Parameters ---------- dX_raw : np.array, size=(m,n), dtype=float raw horizontal displacement with mixed signal dY_raw : np.array, size=(m,n), dtype=float raw vertical displacement with mixed signal dX_prio : np.ar...
fe0565667b77954b1df07d7ea31cbb620b20f800
431
from typing import Mapping import select def get_existing_pks(engine: Engine, table: Table) -> Mapping[int, dict]: """ Creates an index of hashes of the values of the primary keys in the table provided. :param engine: :param table: :return: """ with engine.connect() as conn: pk_col...
fead502b36f67c6732ba4b0e4e678af4fd96ed53
432
def create_transform_parameters( fill_mode = 'nearest', interpolation = 'linear', cval = 0, data_format = None, relative_translation = True, ): """ Creates a dictionary to store parameters containing information on method to apply transformation to ...
2172c283b53d76881877b618043885aa596507d4
433
def error_rate(model, dataset): """Returns error rate for Keras model on dataset.""" d = dataset['dimension'] scores = np.squeeze(model.predict(dataset['features'][:, :, 0:d]), axis=-1) diff = scores[:, 0] - scores[:, 1] return np.mean(diff.reshape((-1)) <= 0)
b16b234ead64737eb2d40b3aab612270ed86dc0a
434
def account(): """Update the user's account""" return _templates.account(UserContext.user())
4624bcce3987e71edcd8d720eea22b52658c1352
436
from typing import Awaitable import asyncio def run_synchronously(computation: Awaitable[TSource]) -> TSource: """Runs the asynchronous computation and await its result.""" return asyncio.run(computation)
2aa14167a2de06a85862b0b0c9294c76fa8ed012
437
from datetime import datetime from typing import Optional from pydantic import BaseModel # noqa: E0611 import cmd from typing import cast def create_running_command( command_id: str = "command-id", command_key: str = "command-key", command_type: str = "command-type", created_at: datetime = datetime(y...
a9e38fd534aaf29ebe265279eb86ed90233113fb
438
def x11_linux_stop_record(): """ stop test_record action """ return xwindows_listener.stop_record()
3a5e4728f8d6d27083ee43c26c84ba22133e0621
439
def yxy_intrinsic(mat: np.ndarray) -> np.ndarray: """Return yxy intrinsic Euler angle decomposition of mat (.., 4, 4))""" # extract components not_nan, r00, r01, r02, r10, r11, r12, _, r21, _ = extract_mat_components(mat) # pre-initialize results theta_y0 = np.full(not_nan.shape, np.nan) theta_...
d7fd0ab01c3c7cf27839caff53a905294e47b7ba
440
def mnemonic_and_path_to_key(*, mnemonic: str, path: str, password: str) -> int: """ Return the SK at position `path`, derived from `mnemonic`. The password is to be compliant with BIP39 mnemonics that use passwords, but is not used by this CLI outside of tests. """ seed = get_seed(mnemonic=mnemonic...
6127278c78a1e52e362c2d66c4eb065f63de0ba9
441
import inspect def test_function_with_annotations(): """Parse a function docstring with signature annotations.""" def f(x: int, y: int, *, z: int) -> int: """ This function has annotations. Parameters: x: X value. y: Y value. Keyword Arguments: ...
5fe7d046659a9e1511f8f321d186cd6e8f1d8d43
442
def acceleration(bodies, i, j): """ Calculer l'acceleration relative à un objet bodies[i] bodies: tous les objets i: index of concerned body which undergoes the gravitation of other objects. j: index of the step """ N = len(bodies) ax = 0; ay = 0; az = 0 #L'acceleration for ip in range(N): #Chaque objet bo...
e19ab098a72d43d0f28931d853866ba0999bd39d
443
import re def formatted(s): """If s contains substrings of form '#'<txt>'#', '(('<txt>'))', "''"<txt>"''", returns list of tuples (FORMAT_x, txt). Otherwise, returns s. """ matches = re.findall(_format_re, normalize(s)) if len(matches) == 1 and matches[0][0] != '': return matches[0][0]...
e164d743c5284de744948ab9db72f8887e380dc2
444
def deep_len(lnk): """ Returns the deep length of a possibly deep linked list. >>> deep_len(Link(1, Link(2, Link(3)))) 3 >>> deep_len(Link(Link(1, Link(2)), Link(3, Link(4)))) 4 >>> levels = Link(Link(Link(1, Link(2)), \ Link(3)), Link(Link(4), Link(5))) >>> print(levels) <<...
d8a33600085e51b181752b2dd81d5bcdae7aaff9
445
def union(A, B): """ Add two subspaces (A, B) together. Args: - A: a matrix whose columns span subspace A [ndarray]. - B: a matrix whose columns span subspace B [ndarray]. Returns: - union: a matrix whose columns form the orthogonal basis for subspace addition A+B [...
d88f09cd4be80d06d7ae0d6e8397e46910f81a90
446
def ldns_create_nsec(*args): """LDNS buffer.""" return _ldns.ldns_create_nsec(*args)
f9e8fd181f4476c745a9ac12c513e24e7939e2e3
447
def str_to_seconds(time): """ Returns the number of seconds since midnight in the string time (as an int). The value time is a string in extended ISO 8601 format. That is, it has the form 'hh:mm:ss' where h, m, and s are digits. There must be exactly two digits each for hours, minutes, and ...
3902e5743567f6d07e2c78fa76e5bc2fc0d6306f
448