content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List import sys def read_zones() -> List[str]: """Read the list of zone_names from the sys.stdin.""" zones: List[str] = [] for line in sys.stdin: line = line.strip() if not line: continue if line.startswith('#'): continue zones.app...
b13c39e87167d54ca731f7b1c19b01cdca6f2943
29,500
def get_username(strategy, details, backend, user=None, *args, **kwargs): """Resolve valid username for use in new account""" if user: return None settings = strategy.request.settings username = perpare_username(details.get("username", "")) full_name = perpare_username(details.get("full_na...
728a0aadf9aa58369fcf791d8cccb0d9214a4583
29,501
def not_at_max_message_length(): """ Indicates if we have room left in message """ global message return message.count(SPACE) < WORD_LIMIT
0bd7d758c80ed272de0571b4f651fe6a24c39b58
29,502
def _create_jwt( user, scopes=None, expires_in=None, is_restricted=False, filters=None, aud=None, additional_claims=None, use_asymmetric_key=None, secret=None, ): """ Returns an encoded JWT (string). Arguments: user (User): User for which to generate the JWT. ...
5a7e48630f54471be041e42c5666e511b3e445b3
29,503
from typing import Union import os import logging def make_log_dir( _run, log_dir: str, log_level: Union[int, str], ) -> str: """Creates log directory and sets up symlink to Sacred logs. Args: log_dir: The directory to log to. log_level: The threshold of the logger. Either an inte...
c275feaeef3627adc3984740da2d05cfeb4deaf6
29,504
from typing import Iterable from pathlib import Path import os def check_files_exist(file_list: Iterable[str]) -> list[str]: """Check if all files exist. Return False if not.""" file_errors: list[str] = [] cwd = Path(os.getcwd()) for file_ in file_list: if cwd.joinpath(file_).is_file() is Fals...
20fc5caba0fe8ad173020ce18eea109c59425243
29,505
import math def _fill_arc_trigonometry_array(): """ Utility function to fill the trigonometry array used by some arc* functions (arcsin, arccos, ...) Returns ------- The array filled with useful angle measures """ arc_trig_array = [ -1, math.pi / 4, # -45° math.pi ...
6b5c39dbacf028d84a397e2911f9c9b7241fe0f4
29,506
from typing import Optional def get_default_tag_to_block_ctor( tag_name: str ) -> Optional[CurvatureBlockCtor]: """Returns the default curvature block constructor for the give tag name.""" global _DEFAULT_TAG_TO_BLOCK_CTOR return _DEFAULT_TAG_TO_BLOCK_CTOR.get(tag_name)
33d002ef206aa13c963b951325a92f49c86eb202
29,507
def panel_list_tarefas(context, tarefas, comp=True, aluno=True): """Renderiza uma lista de tarefas apartir de um Lista de tarefas""" tarefas_c = [] for tarefa in tarefas: tarefas_c.append((tarefa, None)) context.update({'tarefas': tarefas_c, 'comp': comp}) return context
3de659af41a6d7550104321640526f1970fd415c
29,508
from datetime import datetime def get_bdy_times(init_time, fcst_hours, bdy_interval): """ Returns a list of datetime objects representing the times of boundary conditions. Read the init_time, fcst_hours and bdy_interval from config and returns a list of datetime objects representing the boundary...
b84ffca80240bb2291bc4c27d58631e41c06d9c0
29,509
def remove_stopwords(label): """ Remove stopwords from a single label. """ tokenized = label.split() # Keep removing stopwords until a word doesn't match. for i,word in enumerate(tokenized): if word not in STOPWORDS:# and len(word) > 1: return ' '.join(tokenized[i:]) # Fo...
f15e50e5e11ecc6a0abca6b68219789e72070a69
29,510
def single_device_training_net(data_tensors, train_net_func): """ generate training nets for multiple devices :param data_tensors: [ [batch_size, ...], [batch_size, ...], ... ] :param train_net_func: loss, display_outputs, first_device_output = train_net_func(data_tensors, default_reuse) ...
d94e7b552f3612d2f0fd16973612adea77de0bd0
29,511
import requests import os import json import time def get_grafana_session(config): """ Connect to grafana and get a session. We try for 60 seconds. """ session = requests.Session() tries = 30 url = get_grafana_url(config) user = config['grafana']['user'] password = config['grafana']['p...
f0353f8e7be3db26e01bf4260d1f50dd23185f40
29,512
def ALMACopyTable(inObj, outObj, inTab, err, inVer=1, outVer=0, logfile='', check=False, debug = False): """ Copy AIPS Table Returns task error code, 0=OK, else failed * inObj = Input Object (UV or Image) * outObj = Output object * inTab = Table type, e.g. "AIPS A...
b2fd0e0a0de0a2ff792719624441079cf0663c8a
29,513
import requests def get_commit_date(component_path, repo_name, bug_id, version): """ Get date of triggerring commit """ bug_info_path = join(component_path, DependencyAnalyzerConstants.PROJECTS_DIR, repo_name, DependencyAnalyzerConstants.BUGS_DIR, str(bug_id), DependencyAnalyzerConsta...
2bd26012204ea8cd14cd71c8646a0cf941f8f134
29,514
def clopper_pearson(k,n,alpha): """Confidence intervals for a binomial distribution of k expected successes on n trials: http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval Parameters ---------- k : array_like number of successes n : array_like number of trials ...
c10db17a4fb75cc0d7304aceacde9cf716a5cb77
29,515
def add_link(news_list:list) -> list: """ Description: Function to remove the readmore and the add the url as a marked up link for the 'content' key in the 'articles' dictionary. Arguments: news_list {list} : list containing the news articles dictionaries Returns: news_list ...
f1339ddb8854800ae241b7cbb0badc6654c30696
29,516
import array def taitnumber(c): """ Return Tait number from signed edge list of Tait graph. """ c = array(c) # If type(c) != ndarray tau = sum(sign(c[:, 0])) return tau
b30e3d294ae4af80e5d09b7c5de0a6a0682d6d27
29,517
def _difference_map(image, color_axis): """Difference map of the image. Approximate derivatives of the function image[c, :, :] (e.g. PyTorch) or image[:, :, c] (e.g. Keras). dfdx, dfdy = difference_map(image) In: image: numpy.ndarray of shape C x h x w or h x w x C, with C = 1 or C = 3 ...
deff16dbe73005d52444babf05857c2cfea25e0b
29,518
import math def force_grid(force_parameters, position_points, velocity_min, velocity_max): """Calculates the force on a grid of points in phase space.""" velocity_min_index = velocity_index(velocity_min) velocity_max_index = velocity_index(velocity_max) spacing = 2*math.pi / position_points force = np.zeros((vel...
d8d74604c8e313904f97e97364778b0db8db801c
29,519
def calc_coordination(mysupport, debugging=0): """Calculate the coordination number of the support using a 3x3x3 kernel.""" nbz, nby, nbx = mysupport.shape mykernel = np.ones((3, 3, 3)) mycoord = np.rint(convolve(mysupport, mykernel, mode="same")) mycoord = mycoord.astype(int) if debugging == ...
827d36ee297ead88e885dff086323261a25f97f3
29,520
def valueFromMapping(procurement, subcontract, grant, subgrant, mapping): """We configure mappings between FSRS field names and our needs above. This function uses that config to derive a value from the provided grant/subgrant""" subaward = subcontract or subgrant if mapping is None: return ...
1bf2dda830183d1c8289e957b83b1c0d01619160
29,521
def get_cards_in_hand_values_list(player): """Gets all the cards in a players's hand and return as a values list""" return list(Card.objects.filter(cardgameplayer__player=player, cardgameplayer__status=CardGamePlayer.HAND).values('pk', 'name', 'text'))
474ac071950857783dfd76b50ae08483a03fc8bc
29,522
def get_dGdE(fp, tau_E, a_E, theta_E, wEE, wEI, I_ext_E, **other_pars): """ Compute dGdE Args: fp : fixed point (E, I), array Other arguments are parameters of the Wilson-Cowan model Returns: J : the 2x2 Jacobian matrix """ rE, rI = fp # Calculate the J[0,0] dGdrE = (-1 + wEE * dF(wE...
9a53cc9b0cadea8f8884b64d687a2397c0a973a7
29,523
def convert_data_to_ints(data, vocab2int, word_count, unk_count, eos=True): """ Converts the words in the data into their corresponding integer values. Input: data: a list of texts in the corpus vocab2list: conversion dictionaries word_count: an integer to count the words in the dat...
c415aea164f99bc2a44d5098b6dbcc3d723697a6
29,524
def apply_objective_fn(state, obj_fn, precision, scalar_factor=None): """Applies a local ObjectiveFn to a state. This function should only be called inside a pmap, on a pmapped state. `obj_fn` will usually be a the return value of `operators.gather_local_terms`. See the docstrings of `SevenDiscretedOperator` ...
c4fa72f84ce241aa765416fe21ff5426758d5303
29,525
import requests def oauth_generate_token( consumer_key, consumer_secret, grant_type="client_credentials", env="sandbox"): """ Authenticate your app and return an OAuth access token. This token gives you time bound access token to call allowed APIs. NOTE: The OAuth access token expires ...
7ab44b7ba1eb569d0b498946e2936928612e3fa7
29,526
from typing import List import shlex def parse_quoted_string(string: str, preserve_quotes: bool) -> List[str]: """ Parse a quoted string into a list of arguments :param string: the string being parsed :param preserve_quotes: if True, then quotes will not be stripped """ if isinstance(string, l...
6715778f5190445e74b8705542cbfdb1fe022ecc
29,527
def scalar(name, scalar_value): """ 转换标量数据到potobuf格式 """ scalar = make_np(scalar_value) assert (scalar.squeeze().ndim == 0), 'scalar should be 0D' scalar = float(scalar) metadata = SummaryMetadata(plugin_data=SummaryMetadata.PluginData(plugin_name='scalars')) return Summary(value=[Summary.Value(...
e31046a00dc0e2ae6c33bd041b34652c08d2a439
29,528
def filter_citations_by_type(list_of_citations, violation_description): """Gets a list of the citations for a particular violation_description. """ citations = [] for citation in list_of_citations: filtered_citation = check_citation_type(citation, violation_description) if filtered_ci...
398d7cbe43761070c8b5b9117478f6fe5c985a2c
29,529
def user_import_circular_database(injector, session, user_mock_circular_database) -> UserMockDataSource: """Return the circular data source and import its schema to the user's project.""" facade = injector.get(DataSourceFacade) facade.import_schema(user_mock_circular_database.data_source) session.co...
492b87c7cf8d5ef8306fb827620cba860677f5be
29,530
import torch def loss_fn(model, data, marginal_prob_std, eps=1e-5): """The loss function for training score-based generative models. Args: model: A PyTorch model instance that represents a time-dependent score-based model. x: A mini-batch of training data. marginal_prob_std: A funct...
f42dd43d1de865ec31c7702e747852a6df04e479
29,531
from functools import reduce from operator import mul def nCk(n, k): """ Combinations number """ if n < 0: raise ValueError("Invalid value for n: %s" % n) if k < 0 or k > n: return 0 if k in (0, n): return 1 if k in (1, n-1): return n low_min = 1 low_max = min(n, k) high_min = ...
9d84ba8fad27860f64980fb4165f72f0a7ec944c
29,532
def knowledge_extract_from_json(): """ 半结构化数据知识抽取的第二步 json <-> 数据表映射 Returns: """ data = request.json result = extract_data_from_json(data) return jsonify({"data": result})
361d38891a8d90d30a75e3041e082e9c60395666
29,533
import random def vote_random_ideas(request, owner, repository, full_repository_name): """ Get 2 random ideas """ database_repository = get_object_or_404(models.Repository, owner=owner, name=repository) jb = jucybot.from_config() context = {} context = jb.get_issues(full_repository_name, c...
dba4d24711e49f68e85ef6b9f5d3fb4428cb6351
29,534
def delta_EF_asym(ave,t_e,t_mu,comp,t_f,n,alpha = None,max_ave_H = 1): """computes the EF with asymptotic f, f(N) = f_i*H_i*N_i/(N_i+H_i) For more information see S10 H_i is uniformly distributed in [0,2*ave_H] Input ave, t_e, t_mu, t_f, comp,n: As in output of rand_par ...
82abe7a6473b9a0b432654837fb8bffff86513e8
29,535
from scipy.signal.spectral import _median_bias from scipy.signal.windows import get_window def time_average_psd(data, nfft, window, average="median", sampling_frequency=1): """ Estimate a power spectral density (PSD) by averaging over non-overlapping shorter segments. This is different from many othe...
98fb788fdec7f2a868cc576f209c37e196880edf
29,536
import torch def Variable(tensor, *args, **kwargs): """ The augmented Variable() function which automatically applies cuda() when gpu is available. """ if use_cuda: return torch.autograd.Variable(tensor, *args, **kwargs).cuda() else: return torch.autograd.Variable(tensor, *args, **...
b8b0534efd0fd40966eaa70e78e6a8db41156cd4
29,537
import time import os def get_log(device): """ Gets log file from device. :param device: device identifier (e.g. "TA9890AMTG"). """ file_name = str(int(time.time() * 1000)) + ".txt" target_dir = os.getcwd() log_path = os.path.join(target_dir, file_name) clear_log_command = "adb -s " + ...
23a7ca9834c92510fdedb8da32bd45ae6db4f85f
29,538
def edit_distance(graph1, graph2, node_attr='h', edge_attr='e', upper_bound=100, indel_mul=3, sub_mul=3): """ Calculates exact graph edit distance between 2 graphs. Args: graph1 : networkx graph, graph with node and edge attributes graph2 : networkx graph, graph with node and edge attributes ...
550f44e91e60a7c3308d5187af3d32054cf6dffa
29,539
def get_node_elements(coord,scale,alpha,dof,bcPrescr=None,bc=None,bc_color='red',fPrescr=None,f=None,f_color='blue6',dofs_per_node=None): """ Routine to get node node actors. :param array coord: Nodal coordinates [number of nodes x 3] :param int scale: Node actor radius :param float alpha: Node act...
f6e9c2eec12c1816331651d821fa907e5ce34d42
29,540
import logging import time import pickle def temporal_testing( horizon, model, observ_interval, first_stage, bm_threshold, ratio, bootstrap, epsilon, solve ): """ first stage random forest, cross validation, not selecting a best model, without separate testing """ model_name = "horizon...
c6320d2638ee98931af8523085d37981095e9f14
29,541
def _endian_char(big) -> str: """ Returns the character that represents either big endian or small endian in struct unpack. Args: big: True if big endian. Returns: Character representing either big or small endian. """ return '>' if big else '<'
2e1a63ec593ca6359947385019bcef45cb3749c0
29,542
def planar_angle2D(v1, v2): """returns the angle of one vector relative to the other in the plane defined by the normal (default is in the XY plane) NB This algorithm avoids carrying out a coordinate transformation of both vectors. However, it only works if both vectors are in that plane to start...
c244ce7a2bcd27e110062dba0c88f2537e0cb7dd
29,543
def test_agg_same_method_name(es): """ Pandas relies on the function name when calculating aggregations. This means if a two primitives with the same function name are applied to the same column, pandas can't differentiate them. We have a work around to this based on the name property ...
638447c081d2a5dcf4b2377943146876b7438e2c
29,544
def dispatch(request): """If user is admin, then show them admin dashboard; otherwise redirect them to trainee dashboard.""" if request.user.is_admin: return redirect(reverse("admin-dashboard")) else: return redirect(reverse("trainee-dashboard"))
046107c46cbac5e7495fee19c4354a822c476a5b
29,545
def log_pdf_factor_analysis(X, W, mu, sigma): """ log pdf of factor analysis Args: X: B X D W: D X K mu: D X 1 sigma: D X 1 Returns: log likelihood """ Pi = tf.constant(float(np.pi)) diff_vec = X - mu sigma_2 = tf.square(sigma) # phi = tf.eye(K) * sigma_2 # M = tf....
70eb515c3a7b7cc8ea49f6a0e79c11327629c7b5
29,546
import logging def _assert_initial_conditions(scheduler_commands, num_compute_nodes): """Assert cluster is in expected state before test starts; return list of compute nodes.""" compute_nodes = scheduler_commands.get_compute_nodes() logging.info( "Assert initial condition, expect cluster to have {...
6a19830caf029dd2a28cdb2363988940610bbc14
29,547
from typing import Dict from typing import Any def _clean_parameters(parameters: Dict[str, Any]) -> Dict[str, str]: """ Removes entries which have no value.""" return {k: str(v) for k, v in parameters.items() if v}
b8e911674baee7a656f2dc7ba68514c63f84290c
29,548
def delete(run_id): """Submits a request to CARROT's runs delete mapping""" return request_handler.delete("runs", run_id)
8f106d83ba39995f93067a3f8eb67b430b8fd301
29,549
import math def get_tile_lat_lng(zoom, x, y): """convert Google-style Mercator tile coordinate to (lat, lng) of top-left corner of tile""" # "map-centric" latitude, in radians: lat_rad = math.pi - 2*math.pi*y/(2**zoom) # true latitude: lat_rad = gudermannian(lat_rad) lat = lat_rad * 180.0...
6bf0e31b30930f3916112d6540e4387a72238586
29,550
def process_zdr_precip(procstatus, dscfg, radar_list=None): """ Keeps only suitable data to evaluate the differential reflectivity in moderate rain or precipitation (for vertical scans) Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, ...
44b58f755a103756a2cd6726d19b3a7d958d09c3
29,551
import random def get_initators(filepath, n_lines): """ Open text file with iniator words and sample random iniator for each line in the poem. """ with open(filepath, "r", encoding = "utf-8") as file: # save indices of all keywords loaded_text = file.read() # load text file li...
94792679a6ea4e0bb14afd5eb38b656a2cc8af67
29,552
def GSAOI_DARK(): """ No. Name Ver Type Cards Dimensions Format 0 PRIMARY 1 PrimaryHDU 289 () 1 1 ImageHDU 144 (2048, 2048) float32 2 2 ImageHDU 144 (2048, 2048) float32 3 3 ImageHDU 1...
c1cea8420ef518027d14bcf4d430c772268c6024
29,553
import traceback import time def wrapLoop(loopfunc): """Wraps a thread in a wrapper function to restart it if it exits.""" def wrapped(): while True: try: loopfunc() except BaseException: print(f"Exception in thread {loopfunc}," ...
86c48bc850bb1cf17121130ee9349dd529acf5e3
29,554
def get_version(tp): """ Get Version based on input parameters `tp` - Object of class: Transport """ response = None try: response = tp.send_data('proto-ver', '---') except RuntimeError as e: on_except(e) response = '' return response
276dae2599ec99906ea954aae8ad9f79eb2de7d7
29,555
def _decode_feed_ids(option_feeds): """ >>> _decode_feed_ids('123,456') [123, 456] """ return [int(x) for x in option_feeds.strip().split(',')]
9218a170c445b3b8d83f08c39d1547c3ff6e2d20
29,556
def append_to_phase(phase, data, amt=0.05): """ Add additional data outside of phase 0-1. """ indexes_before = [i for i, p in enumerate(phase) if p > 1 - amt] indexes_after = [i for i, p in enumerate(phase) if p < amt] phase_before = [phase[i] - 1 for i in indexes_before] data_before = [dat...
1b416e5352efdff9e578e77f8a068a8f6a446a38
29,557
def timedelta2s(t_diff): """return number of seconds from :class:`numpy.timedelta64` object Args: t_diff: time difference as :class:`numpy.timedelta64` object Returns: scalar corresponding to number of seconds """ return t_diff / np.timedelta64(1, 's')
47d3b41717c877aa9c57a0f2745b95888738523b
29,558
def window(MT_seq, WT_seq, window_size=5): """ Chop two sequences with a sliding window """ if len(MT_seq) != len(WT_seq): raise Exception("len(MT_seq) != len(WT_seq)") pos = [] mt = [] wt = [] for i in xrange(len(MT_seq) - window_size + 1): pos.append(i) mt.appen...
67fecea9ed7155a2c85e9cd7acae9ff5a17402e7
29,559
def splits_for_blast(target, NAME): """Create slices for BLAST This function creates multiple slices of 400 nucleotides given an fasta sequence. The step size is 50. This the gaps are excluded from the sequence. Thats why sequences with less than 400 nucleotides are excluded. Args: target (np...
6ad193fe494a6387fbb06d2c2a3b6a059b903a5f
29,560
from io import StringIO def test_load_items_errors() -> None: """ Test error cases when creating a list of classification Items from a dataframe """ def load(csv_string: StringIO) -> str: df = pd.read_csv(csv_string, sep=",", dtype=str) numerical_columns = ["scalar2", "scalar1"] ...
649358c42db33e178a4269ed48b186999903bbdb
29,561
import imghdr def validate_image(stream): """ Ensure the images are valid and in correct format Args: stream (Byte-stream): The image Returns: str: return image format """ header = stream.read(512) stream.seek(0) format = imghdr.what(None, header) if not format: ...
1a1976f5b009c2400071ebf572d886c1f7d12ab0
29,562
def my_mean(my_list): """Calculates the mean of a given list. Keyword arguments: my_list (list) -- Given list. return (float) -- Mean of given list. """ return my_sum(my_list)/len(my_list)
2423d51bf457a85ee8a6a8f1505a729b6d1d3f6f
29,563
def pr(labels, predictions): """Compute precision-recall curve and its AUC. Arguments: labels {array} -- numpy array of labels {0, 1} predictions {array} -- numpy array of predictions, [0, 1] Returns: tuple -- precision array, recall array, area float """ precision, recall,...
5cf18052875396483f7a76e4c6c0b55f1541803d
29,564
def grouped_evaluate(population: list, problem, max_individuals_per_chunk: int = None) -> list: """Evaluate the population by sending groups of multiple individuals to a fitness function so they can be evaluated simultaneously. This is useful, for example, as a way to evaluate individuals in parallel o...
ea43be334def0698272ba7930cc46dc84ce78de9
29,565
def ZeusPaypalAccounts(request): """ Zeus Paypal Account Credentials """ if request.method == "GET": return render(request, "lost-empire/site_templates/zeus/paypal_accounts.html")
34a0fc616beac2869d501d1652ccd7c9d8ff2489
29,566
def upper_tri_to_full(n): """Returns a coefficient matrix to create a symmetric matrix. Parameters ---------- n : int The width/height of the matrix. Returns ------- SciPy CSC matrix The coefficient matrix. """ entries = n*(n+1)//2 val_arr = [] row_arr = []...
5fdca1868f0824d9539bd785aa99b20c6195b7c0
29,567
def prod(a, axis=None, dtype=None, out=None, keepdims=False): """Returns the product of an array along given axes. Args: a (cupy.ndarray): Array to take product. axis (int or sequence of ints): Axes along which the product is taken. dtype: Data type specifier. out (cupy.ndarray)...
567ca4b23d2828b9a978e44729ff10f823d13113
29,568
import os import sys def get_dataset_path(filename): """Searches for filename in SEARCH_PATH""" for p in SEARCH_PATH: candidate = os.path.join(p, filename) if os.path.exists(candidate): print("Found %s in %s" % (filename, candidate)) sys.stdout.flush() retur...
b1e0c7359aa0868acf78bae1e2ef561500b48804
29,569
def sort_dnfs(x, y): """Sort dnf riders by code and riderno.""" if x[2] == y[2]: # same code if x[2]: return cmp(strops.bibstr_key(x[1]), strops.bibstr_key(y[1])) else: return 0 # don't alter order on unplaced riders else: return strops....
ccf20fb43df26219ce934e18b2d036e3cf6d13b7
29,570
import torch def gen_diag(dim): """generate sparse diagonal matrix""" diag = torch.randn(dim) a_sp = sparse.diags(diag.numpy(), format=args.format) a_pt = _torch_from_scipy(a_sp) return a_pt, a_sp
9ca2842553a1b6331347210bd1da049f53e67361
29,571
def one_of(patterns, eql=equal): """Return a predicate which checks an object matches one of the patterns. """ def oop(ob): for p in patterns: if validate_object(ob, p, eql=eql): return True return False return oop
058f1f64780760d9e996858dcfad4c0a47c07448
29,572
import os def load_dataset_BlogCatalog3(location): """ This method loads the BlogCatalog3 network dataset (http://socialcomputing.asu.edu/datasets/BlogCatalog3) into a networkx undirected heterogeneous graph. The graph has two types of nodes, 'user' and 'group', and two types of edges, 'friend' and '...
709fa29d0493b90ebc5cf986c9ad2a2c2a836e7d
29,573
def convert_to_MultiDiGraph(G): """ takes any graph object, loads it into a MultiDiGraph type Networkx object :param G: a graph object """ a = nx.MultiDiGraph() node_bunch = [] for u, data in G.nodes(data = True): node_bunch.append((u,data)) a.add_nodes_from(node_bunch) ed...
bde49710bed50386bd7bb09816e6f18089ed8030
29,574
def x_to_world_transformation(transform): """ Get the transformation matrix from x(it can be vehicle or sensor) coordinates to world coordinate. Parameters ---------- transform : carla.Transform The transform that contains location and rotation Returns ------- matrix : np.nd...
718227deea6a6be4a0b24ebf4eda40d78be20fcf
29,575
def protobuf_get_constant_type(proto_type) : """About protobuf write types see : https://developers.google.com/protocol-buffers/docs/encoding#structure +--------------------------------------+ + Type + Meaning + Used For + +--------------------------------------+ + + + i...
46ce7e44f8499e6c2bdcf70a2bc5e84cb8786956
29,576
def edit_delivery_products(request, delivery): """Edit a delivery (name, state, products). Network staff only.""" delivery = get_delivery(delivery) if request.user not in delivery.network.staff.all(): return HttpResponseForbidden('Réservé aux administrateurs du réseau '+delivery.network.name) ...
fc734e5ded0a17d20a79d36e8ae599ee763ea73a
29,577
def _tc_imul_ ( self , other ) : """Multiplication for TCut objects >>> cut = ... >>> other = ... >>> cut *= other """ ## self.strip() ## if isinstance ( other , num_types ) : if self : self.SetTitle ( "(%s)*%s" % ( self , other ) ) else : sel...
003ca68e1995e7741cf23576e7515b626d49ff20
29,578
import pprint def format_locals(sys_exc_info): """Format locals for the frame where exception was raised.""" current_tb = sys_exc_info[-1] while current_tb: next_tb = current_tb.tb_next if not next_tb: frame_locals = current_tb.tb_frame.f_locals return pprint.pform...
b5a21f42c8543d9de060ff7be2b3ad6b23065de9
29,579
def binarize_garcia(label: str) -> str: """ Streamline Garcia labels with the other datasets. :returns (str): streamlined labels. """ if label == 'hate': return 'abuse' else: return 'not-abuse'
5cc26303e0c496d46b285e266604a38a0c88e8d7
29,580
def diagstack(K1,K2): """ combine two kernel matrices along the diagonal [[K1 0][0 K2]]. Use to have two kernels in temporal sequence Inputs ------- K1, K2 : numpy arrays kernel matrics Returns -------- matrix of kernel values """ r1,c1 = K1.shape r2,c2 = K2.sh...
6e163bf62ca2639e5bacebad6c03700b1056de2e
29,581
import string def submit_new_inteface(): """POST interface configuration from form data""" global unassigned_ints, interface_nums ip = None mask = None status = None descr = None vrf = None negotiation = None int_num = [i for i in request.form.get("interface") if i not in string...
f746071d1f1ce2c1bdd9c0b4d4401edbb1119c36
29,582
from typing import Optional def component_clause(): # type: ignore """ component_clause = type_prefix type_specifier array_subscripts? component_list """ return ( syntax.type_prefix, syntax.type_specifier, Optional(syntax.array_subscripts), syntax.component_lis...
cd788687645d028c39f7ad439aab1ee21e5ad495
29,583
import numpy as np def clean_time_series(time, val, nPoi): """ Clean doubled time values and checks with wanted number of nPoi :param time: Time. :param val: Variable values. :param nPoi: Number of result points. """ # Create shift array Shift = np.array([0.0], dtype='f') # Shift ...
35a4cea11a0dbf33916f3df6f8aae5c508a0c838
29,584
from typing import Callable def deep_se_print(func: Callable) -> Callable: """Transforms the function to print nested side effects. Searches recursively for changes on deep inner attributes of the arguments. Goes down a tree until it finds some element which has no __dict__. For each element of the ...
e5c2ee57f9f5ecd992ac36a30ac6e32c7afdbd8a
29,585
from pathlib import Path def prepare_checkpoints(path_to_checkpoints:str, link_keys=["link1","link2","link3","link4"], real_data=True,*args, **kwargs)-> str: """ The main function preparing checkpoints for pre-trained SinGANs of Polyp images. Parameters ----------- path_to_checkpoints: str A ...
4e49a495b3dd587c4b9b350d5e329f7dab36ef30
29,586
def data_count(): """ :return: 数据集大小 """ return 300
1582c3782cd77ee79727a7874afbb74539f3ff9e
29,587
import logging import re def grid_name_lookup(engine): """Constructs a lookup table of Institute names to ids by combining names with aliases and cleaned names containing country names in brackets. Multinationals are detected. Args: engine (:obj:`sqlalchemy.engine.base.Engine`): connection to...
0a0fef49c722d6c8c40e2d00f1d87d8f41efbbef
29,588
def sample_vMF(theta, kappa,size=1): """ Sampling from vMF This is based on the implementation I found online here: http://stats.stackexchange.com/questions/156729/sampling-from-von-mises-fisher-distribution-in-python (**** NOTE THE FIX BY KEVIN *****) which is based on : ...
1e8d327b5613d9f2e5f77c26eab86d09d9d8338b
29,589
def fbx_mat_properties_from_texture(tex): """ Returns a set of FBX metarial properties that are affected by the given texture. Quite obviously, this is a fuzzy and far-from-perfect mapping! Amounts of influence are completely lost, e.g. Note tex is actually expected to be a texture slot. """ # M...
363c9f60084a55aa8d9c01c2f06d4d30d5e45993
29,590
def get_from_STEAD(key=None, h5file_path='/mnt/GPT_disk/DL_datasets/STEAD/waveforms.hdf5'): """ Input: key, h5file_path Output: data, p_t, s_t """ HDF5 = h5py.File(h5file_path, 'r') if key.split('_')[-1] == 'EV': dataset = HDF5.get('earthquake/...
9bab2db49eab81abe72cb27e86d3cdf787c4e902
29,591
import traceback def _safeFormat(formatter, o): """ Helper function for L{safe_repr} and L{safe_str}. """ try: return formatter(o) except: io = NativeStringIO() traceback.print_exc(file=io) className = _determineClassName(o) tbValue = io.getvalue() r...
610e8063fa91d211e749be829c2d562fa1b86ea6
29,592
import os def get_int(name, default): """ Get an environment variable as an int. Args: name (str): An environment variable name default (int): The default value to use if the environment variable doesn't exist. Returns: int: The environment variable value parsed a...
6adb80b14034c4561a5bae8fe9983e2165678a55
29,593
from datetime import datetime import pytz def now_func(): """Return current datetime """ func = get_now_func() dt = func() if isinstance(dt, datetime.datetime): if dt.tzinfo is None: return dt.replace(tzinfo=pytz.utc) return dt
c715be9fde2d245c79536d792b775678bc743aaa
29,594
import itertools def flatten_search_result(search_result): """ Converts all nested objects from the provided search result into non-nested `field->field-value` dicts. Raw values (such as memory size, timestamps and durations) are transformed into easy-to-read values. :param search_result: result to ...
380b244bcee0d968532db512b6bf79cc062ef962
29,595
import os def get_stretch_directory(sub_directory=''): """Returns path to stretch_user dir if HELLO_FLEET_PATH env var exists Parameters ---------- sub_directory : str valid sub_directory within stretch_user/ Returns ------- str dirpath to stretch_user/ or dir within it i...
0af8b46c160008750c62b4aada700ed46b87aff9
29,596
def xroot(x, mu): """The equation of which we must find the root.""" return -x + (mu * (-1 + mu + x))/abs(-1 + mu + x)**3 - ((-1 + mu)*(mu + x))/abs(mu + x)**3
5db07cc197f1bc4818c4591597099cd697576df2
29,597
import random def spliter(data_dict, ratio=[6, 1, 1], shuffle=True): """split dict dataset into train, valid and tests set Args: data_dict (dict): dataset in dict ratio (list): list of ratio for train, valid and tests split shuffle (bool): shuffle or not """ if len(ratio)...
793af274e3962d686f2ef56b34ae5bc0a53aac5b
29,598
import scipy def smooth(x, window_len=None, window='flat', method='zeros'): """Smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. :param x: the input signal (numpy array) :param window_len: the dimension of the smoothing wi...
148c1f4b420ce825d3b658e90329dac7b9360c2c
29,599