content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _read_method(schema): """Add a write method for named schema to a class. """ def func( self, filename=None, data=None, add_node_labels=True, combine_on='index', use_uids=True, **kwargs): # Use generic write class to write data. df0 ...
65aaa9f3137506699cc50570932993d9f34796e1
53,207
from typing import List def mark_nb_animals_neighbors(neighbors: List[List[int]], w: int, h: int, nb_animals: int, animal_type: str) \ -> ClausesBase: """ Permet d'ajouter des contraintes concernant le nombre d'animaux autour d'une cellule :param neighbors: Liste des cordonnées des cellules voisin...
43c2a784dd3223861e5b08018322c567d32abd55
53,208
def predict_next_daterange(dateranges, min_probability=0.8): """ Takes a list of dateranges (start, end) and tries to predict the next daterange in the list. See :func:`predict_next_value` for more information. """ return predict_next_value( values=dateranges, min_probability=min_...
424bbb677f512cfdbfdd127bf5eae990590a2dd9
53,209
import torch def resize_activations(v, so): """ Resize activation tensor 'v' of shape 'si' to match shape 'so'. :param v: :param so: :return: """ si = list(v.size()) so = list(so) assert len(si) == len(so) and si[0] == so[0] # Decrease feature maps. if si[1] > so[1]: ...
9e2cc25cbc5b31b986e3486d6c66dd24ac5c36c8
53,211
import torch def show_model(model:nn.Module): """ Render graphviz representation of neural network model """ hl_graph = hl.build_graph(model, torch.zeros([1, 3, 224, 224])) hl_graph.theme = hl.graph.THEMES["blue"].copy() return hl_graph
98b6deee208ee9cba23c42b19937f9e0aca26764
53,212
def seg_pixel_accuracy_nd(label_imask, pred_imask, vague_idx=-1, use_vague=False, macro_average=True, empty_result=0.0): """ The segmentation pixel accuracy (for MXNet nd-arrays). ...
7da093ef624dee07fd335021ae2317d53583e612
53,213
import wave def record_audio(record_len, filename): """ records an audio clip from the default input device @params: length: the length of recorded audio [seconds] filename: the ouput filename """ try: CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNEL...
9b9b4ea57f56fe97a40e7e4f620765779de903be
53,214
import importlib import inspect def getCoursesFromModels(): """This method imports and inspects Models.py file and adds name of its classes to the list. User class is skipped so it is not added into list of courses. Returns: list: List of string names of classes in Models.py file. """ co...
fd3685ca68e98afd9384ad0711e43ac68e02c94d
53,215
def format_message(article_dict): """ From a dictionary of randomly selected articles, create and format a message string. """ msg = "" for subject in article_dict: url = article_dict[subject][1] abstract, authors = get_abstract(url) msg = msg + "<h2>" + subject + "</h2>...
dfb5008eefb67017a359d0aa452b40414acf21c7
53,216
from datetime import datetime def lock_nqueuedjobs(cur, nrows): """ Function to lock first N rows for futher processing :param nrows: :return: lock_time """ lock_time = datetime.now().strftime(defaultDatetimeFormat) lquery = """UPDATE atlas_pandabigmon.art_results_queue SE...
b81721e27b8dd28020110e7d689bc4d0302093ee
53,217
def extract_seed(path, key): """ Scrape the 5-character seed from the path and return it as an integer. :param path: path to the tsv file containing results :param key: substring preceding the seed, "batch-train" for splits, seed-" for shuffles """ try: i = path.find(key) + len(key) ...
c5073ad43e8a966aba5382894490aa6cbc871271
53,218
from datetime import datetime def UTC2JD1JD2(epoch: datetime.datetime): """ :param epoch: :return: """ return astropyTime(epoch, format='datetime', scale='ut1').jd1, astropyTime(epoch, format='datetime', scale='ut1').jd2
5183af2730130ee7e28434f67071ba6b0e232692
53,219
import sympy as sym def test_solver(): """Check 1st order convergence rate.""" m = 4; b = 0.1 s = lambda u: 2*u f = lambda v: b*v def ode(u): """Return source F(t) in ODE for given manufactured u.""" print 'ode:', m*sym.diff(u, t, 2), f(sym.diff(u,t)), s(u) return m*sym.di...
b7b8eaba059b832d3cfc175cffcd310b49f649e1
53,220
def spawn(n): """ Spawn a list of SeedSequence from the global seed sequence. Parameters ---------- n : int Number of seed sequences to spawn Returns ------- seed_seq : list List of spawned seed sequences """ return _GLOBAL_SEED_SEQ.spawn(n)
109b374607e0fdcb52f117c5176ea918f633ad14
53,221
def get_certificates(country=None): """ This function retrieves all the data stored in `certificates.csv` file, which previously was retrieved from Investing.com. Since the resulting object is a matrix of data, the certificate's data is properly structured in rows and columns, where columns are the ce...
4bf7984ab8b9856039ae4f012868558000ee206c
53,223
def f_t(x_tm1, potential_function, parameters, dt, **kwargs): """ NOTE : parameters should reflect potential function at time t (not t-1) compute f_t(x_tm1) = x_tm1 + 0.5 * dt * forcet(x_tm1) = mu arguments x_tm1 : np.array(N) positions at time t-1 potential_function : funct...
8903b5ce003832c1dadaca24cd539c03ec828984
53,224
def get_neighbor_dict_from_table(db, table_name): """ returns a dict with bgp neighbor ip as key and neighbor name as value :param table_name: config db table name :param db: config_db """ neighbor_dict = {} neighbor_data = db.get_table(table_name) try: for entry in neighbor_data...
17d8230956c36db8c79bd98f0eec63320b6e77d0
53,225
def french_to_english(french_text): """This function translates text in french to english""" if french_text == "": return "" english_text = language_translator.translate(text=french_text, model_id='fr-en').get_result() english_text = english_text.get("translations")[0].get("translation") re...
6d50828cb5dd9dd964f41b3427597107130e87aa
53,226
import re def highlight_cycles(dot_stream, cycle_list): """Highlight the include cycles in red.""" for cycle in cycle_list: cycle_edges = determine_cycle_edges(cycle) for edge in cycle_edges: regex = fr'([<"]{edge[0]}[">] -> [<"]{edge[1]}[">])' match = re.search(regex,...
e6aba9c3c920ec5680d1fdd29625401a36f9462e
53,227
def find_role_similarity(roles, i, j, parameters=None): """ Calculate a number of similarity between different roles Parameters ------------- roles List of roles i Index of the first role j Index of the second role parameters Parameters of the algorithm ...
6fc669c0537907b0442d7db959db5ad6fd2feb5a
53,228
def histogram_matching(mov_scan, ref_scan, histogram_levels=2048, match_points=100, set_th_mean=True): """ Histogram matching following the method developed on Nyul et al 2001 (ITK implementation) inputs: - mov_scan: np.array cont...
9f4149ffd56470044f3603750b34f445a915dcdc
53,229
def configure_vrrp(module, csv_data): """ Method to configure VRRP L3. :param module: The Ansible module to fetch input parameters. :param csv_data: String containing vrrp data passed from csv file. :return: Output string of configuration. """ output = '' vnet_name = get_global_vnet_name...
be6787a282f747b107d50fc869093c612a38f971
53,230
def update_priorities(repo, username=None, namespace=None): """Update the priorities of a project.""" repo = flask.g.repo form = pagure.forms.ConfirmationForm() error = False if form.validate_on_submit(): weights = [ w.strip() for w in flask.request.form.getlist("p...
6f93aea172c5457068ee01e18c98b03e7ae7406b
53,231
from typing import Union def find_post(url: str) -> Union[Album, None]: """Find post with twitter id in the url Args: url (str): twitter url Returns: Union[Album, None]: Album """ return Album.first(F['source.url'].regex(r'https://twitter.com/.*/status/' + url.split('/')[-1]))
76f5fc8b130c09bcfceacca6c0905e03d0c548d3
53,232
import html def serialize_categories_ical(category_ids, user, event_filter=True, event_filter_fn=None, update_query=None): """Export the events in a category to iCal. :param category_ids: Category IDs to export :param user: The user who needs to be able to access the events :param event_filter: A SQL...
86c1f209b16a6a246edebcff71a327bc2db7dfe3
53,233
import re def create_attribute(name, snake_case=True): """ Gets an attribute name from the enum and convert it to snake_case, by default, or to CamelCase """ # Removes any hyphens or dots from the name, substituting by an underscore name_normalized = re.sub('[-.]', '_', name) if snake_case...
a337e386af1a1ea735612d310618ce8ebf40f679
53,235
def preprocessing_fn(inputs): """Preprocesses Covertype Dataset.""" outputs = {} # Scale numerical features for key in features.NUMERIC_FEATURE_KEYS: outputs[features.transformed_name(key)] = tft.scale_to_z_score( _fill_in_missing(inputs[key])) # Generate vocabularies and maps categorical featu...
81fb7b301f447e7b31a31fa6c174d0821992fe18
53,236
import tokenize def build_model(gridsearch=False): """ Create a classification model :param gridsearch: bool. Activate GridSearch, default = False :return: pipeline """ # Create pipeline with Classifier moc = MultiOutputClassifier(RandomForestClassifier()) pipeline = Pipeline([ ...
ce4c7a6a1afc58957884e1e4073247c42ca7b8ac
53,237
import pickle def get_cells_to_calculate_variance(file_path, percentage_of_extreme_cells=15): """ Get a list of cells to use to calculate the methylation and variance In this case we have a list of all cells that might be possible and the avg methylation and variance of them and we want to take the pe...
c151b03cb873f179eb946dd12f6a286aeea8e7a3
53,238
def device_smart_capabilities(device): """Returns SMART capabilities of the given device. Args: device: (Device) Device in question. Returns: (tuple): tuple containing: (bool): True whenever SMART is available, False otherwise. (bool): True whenever SMART is enable...
b3f3ea1908fd75808d9b73ee77a69dfb503cda04
53,239
def slice_arrays(arrays, start=None, stop=None): """ Function extracted from Keras - check keras.utils.generic_utils for the original version. Slices an array or list of arrays. This takes an array-like, or a list of array-likes, and outputs: - arrays[start:stop] if `arrays` is an array-lik...
841a645ff866e0e811291d416037263f38035d12
53,240
def test_with_exit(exit_code): """ We parametrize over the first few exit codes to ensure they are all handled the same. `utils.with_exit` should always raise, even in the case where `foo` ran successfully (`exit_code==0`). """ @utils.with_exit def foo(): return exit_code with pytes...
fe7ed64616f54058241098cfda2f038af16c4fc8
53,241
import gzip def load_data_sample(fn): """ :param fn: :return: samples: 1D: n_docs, 2D: n_utterances, 3D: elem=(time, speaker_id, addressee_id, response, ... , label) """ samples = [] sample = [] with gzip.open(fn, 'rb') as gf: for line in gf: line = line.rstrip().split(...
6f6828a60767a1ac1674ad5abbe519b1d1b18df0
53,242
def calc_buckets( start: float, upper_bound: float, /, *, increment_ratio: float = 1.20 ) -> tuple[float, ...]: """Calculate histogram buckets on a logarithmic scale.""" # See https://amplitude.com/blog/2014/08/06/optimal-streaming-histograms # for more details. result: list[float] =...
541fdb81b150a81d24b515acaf53365afb4b62b4
53,243
def ximp(N, i, real=False, polar=False, show_x=False, v=1, unwrap=False, get=False): """Impulse(s); form e.g. square wave""" if not isinstance(i, (list, tuple, np.ndarray)): i = [i] i = [(idx if idx >= 0 else N + idx) for idx in i] x = np.array([(v if n in i else 0) for n in range(N)]) ...
fe5af063eb73674d755621e356cd3c25e92c7fc8
53,244
import torch def quantizer(forward_number=None, backward_number=None, forward_rounding="stochastic", backward_rounding="stochastic", clamping_grad_zero=False, backward_hooks=[]): """ Creates a quantization function to support quantizing forward and backward process differently. ...
5985d64c31d4ef42ae1c4cc0ed5ccf322f20c75e
53,245
def dumpinfo(id0): """ print various infos on the idb file """ def ftstring(ft): if 0 < ft < len(filetypelist): return "%02x:%s" % (ft, filetypelist[ft]) return "%02x:unknown" % ft def decodebitmask(fl, bitnames): l = [] knownbits = 0 for bit, name in enu...
7afe394022107261a3ce660d76247e876b5c9f0f
53,246
def is_size_lower_or_equal(size_a: str, size_b: Size): """Returns true if size_a is lower or equal than size_b""" return int(size_a) <= int(size_b.get_value(Unit.MebiByte))
89966dfee96489daf64942b4c36ab9a395c787a6
53,247
def from_hexpoints(s): """Parses a string from its codepoints as hex. Given a string containing one or more code points (as hex values), parse it to a a string. For example, the input "006E 006F" produces output "no". """ return "".join([chr(int(cp, 16)) for cp in s.split()])
55b5088d000cf90059ca93d7e3895aee043d554e
53,248
def hamming_distance(s1, s2): """ Defines the minimum number of substitutions required to change one string into another. """ if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal lenght.") return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
5228ec015a87797860075e18a955a47236e03460
53,249
import inspect import torch def get_pure_function(fcn) -> PureFunction: """ Get the pure function form of the function or method ``fcn``. Arguments --------- fcn: function or method Function or method to be converted into a ``PureFunction`` by exposing the hidden parameters affect...
54994a04e5cf925c0dcd7cab876c1ceb631b071a
53,250
def img_brighten(img, factor): """ Increase the brightness of the input img :param img: input img :param factor: the degree of increasing the brightness :return: output img """ img2 = img * factor img2 = np.clip(img2, 0, 255) return img2
80b6d6529213ce13aacce9da979208600c247778
53,251
def choose_random_action(all_actions: int) -> int: """ Chooses one of the possible actions in the environment randomly Parameters ---------- all_actions: int number of all possible actions available Returns ------- int random action number """ return np.random.r...
777f30f48152857011eac4818b3c3e6b2485dc33
53,252
from typing import List def generate_equi_width_buckets(quantiles: List[float], finite_min: float, finite_max: float, total_count: float, num_buckets: int) -> List[Bucket]: """Generate buc...
f7704bd2449553607187c1dadf6a2c5c204a764a
53,253
def turnover_knee(f, log10_A, gamma, lfb, lfk, kappa, delta): """ Generic turnover spectrum with a high-frequency knee. :param f: sampling frequencies of GWB :param A: characteristic strain amplitude at f=1/yr :param gamma: negative slope of PSD around f=1/yr (usually 13/3) :param lfb: log10 tra...
c01b634b5a4a6603b6e77244b0b57f30afba119e
53,254
def basicFitness(individual, env): """ The trivial case, where fitness is just the result of passing through the environment. """ return individual.result
7d108bac92ce390699b66e1ead5b08080856c5be
53,255
def map_reward(const=1.0) -> MapReward: """ Factory for map_reward argument in GPMultiFidelitySearcher. """ def const_minus_x(x): return const - x return MapReward(forward=const_minus_x, reverse=const_minus_x)
37cfbe67b791f0bd566744054f74c657efda2e5b
53,256
import time import socket import errno def check_for_daemon(limit=10, delay=0.1, timeout=0.1, port=TCP_GIT_PORT): """Check for a running TCP daemon. Defaults to checking 10 times with a delay of 0.1 sec between tries. Args: limit: Number of attempts before deciding no daemon is running. dela...
9f1d4f378e1b08c6af2de92dcfd78ce77d5cc23f
53,257
def evaluate_recall(gt_rels, gt_boxes, gt_classes, pred_rels, pred_boxes, pred_classes, rel_scores=None, cls_scores=None, iou_thresh=0.5, phrdet=False): """ Evaluates the recall :param gt_rels: [#gt_rel, 3] array of GT relations :param gt_boxes: [#gt_box, 4] array...
3cc53b481643b4fd4dfbbc4b41b15b0fa5e2adf1
53,260
def not_found(arg): """Page not found.""" return render_template('404.html', title='404 error.', message='Page Not Found')
12147889561a182abbb03f517cc6f642a9cc9cd2
53,262
def mte_unobserved( X, Y, b0, b1_b0, prop_score, bandwidth, gridsize, startgrid, endgrid ): """ This function computes the unobserved component of the MTE in MTE = mte_x + *mte_u*, where *mte_u* depends on the unobserved esistance to treatment u_D. Parameters ---------- X: pandas.DataFr...
e77a44e8aff584c4c649c2da167d09afff27eccc
53,263
def wavepacket(m, x0, p0): """Generates normalized Gaussian wavepacket in position and momentum space. Parameters ---------- m : int Number of planck cells in one direction. x0 : float Initial x-coordinate of localized wavepacket in position space. p0 : float Initial...
d4bd5894609039ca44b99412d0e732bea11d5c2c
53,264
def make_key_with_salt(seed, salt): """generates a key from a given seed, returns the key and a salt Args: seed Returns: signing key, a salt Raises: assertion failure if the signature is not verified """ ecdsa_seed = hash_256(seed + salt) secexp = randrange_from_se...
2b262f96768f6ec1566590836f55ac531336b44e
53,265
def find_missing_integer(arr): """ Find the first missing integer in unsorted array of integers """ # segregate integers, with negative (including zero) on right and positives # on left left = 0 right = len(arr) - 1 while left < right: if arr[left] > 0: left += 1 ...
d31b5a42ed9bd43d7d036098e8491b4b839c5873
53,266
def break_weights(weights): """ Breaks the weights for the different nodes :param weights: :return: """ bias_node_hidden = weights[4:6] bias_node_hidden = np.reshape(bias_node_hidden, (2, 1)) bias_node_output = np.reshape(weights[8], (1, 1)) weights_input = weights[0:4] weights...
2f77feab5cd083553c4b6b4f8600f1f3646381b9
53,267
def get_movies(genre: str): """Get first N movies in the specified genre.""" with MongoClient(uri) as client: movie_collection = client[DB][MSG_COLLECTION] msg_list = movie_collection.find({"genres": genre}).limit(100) movie_title_list = [] for msg in msg_list: movie_...
795fc4b4595e92686efa190b4ba2933aeaed4451
53,268
def apply_all_transformations(df): """Apply all feature transformations.""" df["age_quantile"] = compute_age_quantile(df, 5) df["competition_open"] = compute_competition_open(df) df["count"] = df.groupby("store")[["date"]].transform("cumcount") df["open_lag_1"] = compute_open_lag(df) df["open_la...
e14c3aa9f79c851085daf75e269dcea9bec7a87b
53,269
def _lcmv_source_power(info, forward, noise_cov, data_cov, reg=0.01, label=None, picks=None, pick_ori=None, rank=None, verbose=None): """Linearly Constrained Minimum Variance (LCMV) beamformer. Calculate source power in a time window based on the provided data ...
265a1a7a2e8e70ff4142288c0dbd484b2e36321c
53,270
def summary(d): """ Generate a summary message of the dictionary. :param d: A dictionary to summary. :return: A string as summary message. """ msg_list = [] for key, value in d.items(): msg = '- {}: '.format(key) if isinstance(value, np.ndarray): msg += 'shape {...
26139ed6fa1617fb28fab0b515e00deb054fb8d6
53,271
def execute(context: cli.CommandContext) -> Response: """ """ response = context.response project = cauldron.project.internal_project if not project: return response.fail( code='NO_OPEN_PROJECT', message='No project is open. Unable to refresh' ).console( ...
44fc1a8df66e586769fee21727978cf30034ab8c
53,274
def get_username(strategy, user=None, *args, **kwargs): """Sets the `username` argument. If the user exists already, use the existing username. Otherwise generate username from the `new_uuid` using the `helusers.utils.uuid_to_username` function. """ storage = strategy.storage if not user: ...
2c3f15ae156641ed26b5fa55d8208002716ebf43
53,275
import http def uptest_latest(request): """ Look up most recent test run and redirect to its record in the API. """ runs = models.TestRun.objects.filter(end__isnull=False).order_by('-start') if not runs: return http.HttpResponseNotFound() url = reverse('api_dispatch_detail', ...
8b5b047c7db820a0aa288d1478af1b2554da6dc2
53,276
def one_to_three(one_letter): """ Convert a one letter code amino acid to a three letter code. """ assert one_letter.upper() in "FLSYCWPHERIMTNKVADQG*U", "Error, %s is not a valid amino acid" % one_letter AA = { "I": "Ile", "V": "Val", "L": "Leu", "F": "Phe", ...
6554ff9063824f348a512e28df3dc936073d1355
53,277
def get_video_frame(video_path, frame_number): """ Obtain numpy array corresponding to a particular video frame in video_path :param video_path: local path to mp4 file :param frame_number: video frame to be returned :return: numpy array corresponding to frame of interest. Dimensions are (1024, 1280...
05fc204829b648ab51315d1901f52805948e9fc0
53,278
import time def float_product(size=DEF_MATRIX, rep=DEF_REP): """ Returns the execution time of performing a product of random real matrices. Parameters ---------- size : int The dimension of the square matrices that will be used in the operation. ...
0826058fd3ba971001a512c02e506bc759f9bf52
53,279
def _empty_frozen_http_headers() -> HttpHeaders: """Used for the 'default_factory' of the 'NodeConfig.headers'""" return HttpHeaders().freeze()
7e0f323fd463901f6b2f46f53719a6db2232461a
53,280
def reorder_evals(ev,times): """ Parameters ---------- evals : 2D numpy array containing a series of eigenvalues. times : 1D numpy array containing the corresponding times Returns ------- newev : 2D numpy array with continuous (along dim=0) eigenvalues """ evals = ev....
27e33caa4d235ca27b5d2f2764cbae314c310e82
53,281
import types def get_public_members(): """Get public members in :mod:`bezier` package. Also validates the contents of ``bezier.__all__``. Returns: list: List of all public members **defined** in the main package (i.e. in ``__init__.py``). Raises: ValueError: If ``__all__`` h...
4e5a7d5173c0c4a9c1024428e95ef21e1386e37e
53,282
import hashlib def sha256_hash(stream, block_size=65536): """ Calculates a sha256 hash for the contents of the provided stream. :param stream: The stream of the content where to calculate the hash for. :type stream: IOStream :param block_size: The amount of bytes that are read each time. :typ...
f18c170c961c651301ee9b4bfd8d526a05e199ef
53,283
def central_time(sqrIR: np.ndarray, tstamp: np.ndarray) -> np.ndarray: """ Room parameter. Parameters ---------- sqrIR : np.ndarray Squared room impulsive response. tstamp : np.ndarray Time stamps of each IR sample. Returns ------- central_time : np.ndarray ...
f307c77e0069c6feec7a3e8cc272b59bd022c1b9
53,284
def get_html_fields(fields): """ Converts a fields table with mandatory keywords type, text, id and partially optional keywords value, allowed_values, checked and help into html input lines. The tal in the templates has become too complicated therefore the python code handles most of the condition...
9269d26a86892791d5ef4847546600d629c8f7c6
53,285
def GetAccessTokenIfEnabled(account=None, scopes=None, allow_account_impersonation=True): """Returns the access token of the given account or the active account. If credentials have been disabled via properties, this will return None. Otherwise it return th...
3540e5f05712430c6cca0a50d43f09495e876861
53,286
from datetime import datetime def plot_drifters(ax, DATA, DRIFT_OBJS=None, color='red', cutoff=24, zorder=15): """Plot a drifter track from ODL Drifter observations. :arg time_ind: Time index (current drifter position, track will be visible up until this point, ex. 'YYYY-mmm-dd HH:MM:SS', format is f...
c3398ce48bc2b61a3fe4933e72a8d72da97c3530
53,287
from typing import List import math def quaternion_from_angle_axis( angle: float, axis: np.ndarray, axis_normalized: bool = False ) -> List[float]: """Gets a quaternion from an angle and an axis. For more information, check `this Wikipedia page <https://en.wikipedia.org/wiki/Conversion_between_quatern...
71379e483ae35ebf18d6a692bd961dc29487ca4b
53,288
def _overlaps(existing, new): """Check whether existing diff op shares a key with the new diffop, and if they also have the same op type. """ if not existing: return False existing = existing[-1] # Only need to check last op! if existing.op == new.op: if existing.key == new.key:...
0edc849ea2cbdf1f840a4239a0088d42692ec79a
53,289
def A000121(n: int) -> int: """Give Number of representations of n as a sum of Fibonacci numbers. (1 is allowed twice as a part). a(0) = 1; for n >= 1, a(n) = A000119(n) + A000119(n-1). - Peter Munn, Jan 19 2018 """ if n == 0: return 1 return A000119[n] + A000119[n - 1]
3bc565ab2c971bfbe4af46f69d700489da1e8654
53,290
import logging def fetch_cordis_organisations(): """Fetch cordis organisations""" logging.info("Fetching cordis organisations") orgs = pd.read_csv( "https://cordis.europa.eu/data/cordis-h2020organizations.csv", delimiter=";" ) orgs.columns = [camel_to_snake(c) for c in orgs.columns] o...
2bb1efa5fd61ed9c165935d3981e8b7193595729
53,291
def run_program(memory, inputs): """Execute the successive instructions of the program""" instr_ptr = 0 output = [] while True: (opcode, modes) = parse_opcode(memory[instr_ptr]) if opcode == 99: # Program end break elif opcode in [1, 2]: # 1 = Addition, 2 = Multi...
004b4f5df2b6b97697e6a3cbb80f1e2787efdddc
53,293
def load_image(filename, color=True): """ Load an image converting from grayscale or alpha as needed. Parameters ---------- filename : string color : boolean flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Ret...
41b9e18cdc481c38abd685796b3ee942bf19ae7f
53,294
def build_pixel_sample_scale_display(node: hou.RopNode) -> str: """Build a label to display the adjusted pixel samples. :param node: The node to build the display for. :return: The display scale. """ samples = node.evalParmTuple("vm_samples") sample_scale = node.evalParm("ip_sample_scale") ...
677d13c374f174a790989bd46eb7ea3f66d0e9dc
53,296
import copy def test_oauth_logout(app, mockservice_url): """Verify that logout via the Hub triggers logout for oauth services 1. clears session id cookie 2. revokes oauth tokens 3. cleared session id ensures cached auth miss 4. cache hit """ service = mockservice_url service_cookie_na...
de3383a0c85c4c5f502c15f59b1f2694641e279e
53,298
def get_metadata_from_attributes(Object, skip_attributes = None, custom_classes = None): """ Get metadata dict from attributes of an object. Parameters ---------- Object : object from which the attributes are. skip_attributes : list, optional If given, these attributes are...
0c6eacae223ea94e128ff5b507fcaa5a71034c38
53,299
def add_list(): """ Add new list """ # User reached route via PODT (as by submitting a form via POST) if request.method == "POST": # Ensure title was submitted if not request.form.get("title"): return apology("must provide title", 400) # Add new list into the database ...
f6c7d4268352be811f60abe3b8cb147519a79461
53,302
def power_flow_2_bus(v1, theta1, v2, theta2, g, b): """ Calculate the power flow from bus 1 to bus 2 across the line with admittance g+jb from the given voltages and angles. """ p = 0 q = 0 # Build admittance matrix values g12, b12 = -g, -b g11, b11 = g, b p += v1 * v2 * (g12 *...
b8f871b485d251b0ba3f1695f57d06c5c4b1fd5e
53,304
import zipfile import json def _GetExtensionInfoFromCRX(crx_path): """Parse an extension archive and return information. Note: The extension name returned by this function may not be valid (e.g. in the case of a localized extension name). It's use is just meant to be informational. Args: crx_path...
8a5f2ef2547c67d65195334df89d589fbff54dcf
53,305
def update_state(td_state, job_results): """ Updates the torsiondrive state with the compute jobs. The state is updated inplace Parameters ---------- td_state : dict The current torsiondrive state job_results : dict A dictionary of completed jobs and job ID's Returns --...
476d19fb9946045dc555f815d680d0475f253003
53,306
import inspect def extract_script_classes(module, target_kls): """ Returns list of classes (`Script`) detected from the module. """ return iter(kls for name, kls in inspect.getmembers(module) if is_class_and_subclass(kls, target_kls))
debb2187d2b0c6632b4d268063763ce7892e7510
53,307
def to_obj(cls, obj_data=None, *fields, **field_map): """ prioritize obj_dict when there are conficts """ obj_dict = obj_data.__dict__ if hasattr(obj_data, '__dict__') else obj_data if not fields: fields = obj_dict.keys() obj = cls() update_obj(obj_dict, obj, *fields, **field_map) return...
e4781d6d3229e69ba4eb5ba8efd574435b66c4fa
53,308
def V_NN(mol): """ Compute Nuclear-Nuclear repulsion energy """ nn = 0 for i in range(mol.num_atoms): for j in range(i+1, mol.num_atoms): # Select atoms from molecule Ri = mol.coordinates[i] Rj = mol.coordinates[j] Zi = mol.charges[i] ...
22ccc5d05e3c954da2418312a7bb0d149c1afbd5
53,309
import json def report(request): """ 通过csrf_exempt装饰器,跳过Django的csrf安全机制,让post的数据能被接收,但这又会带来新的安全问题。 可以在客户端,使用自定义的认证token,进行身份验证。这部分工作,请根据实际情况,自己进行。 :param request: :return: """ if request.method == "POST": asset_data = request.POST.get('asset_data') data = json.loads(asset_d...
7761404cab007bf7328c657d0f8882be79a83c3f
53,310
def find_adjacent(kmeans_img, start_row, start_col, width, height): """Start start_row, start_col, search LR then up for matching values, repeat. Return end col, return list of matching row,col ie x,y. Simple version of the "fill" command in Photoshop. These matching row,col will be used later to curv...
84d14821ea3658e98b9f38fe3155773d6fd1c51a
53,311
from typing import Dict def parse_profile(obj: Element, profile: Element) -> Dict[str,str]: """Parses model profile and related object element. Function is called once per object element and profile information is repeated per object. Arguments: obj {Element} -- Profile object profile {E...
b849058678865f2e1365bc6e1af2855f41c0ace2
53,312
def _format_rangeyaxis( axis: plt.axis, pdata: dict, rg_converter: bool = False, **kwargs ) -> plt.axis: """Zoom to a specific range interval and format yaxis. Args: axis: plot axis pdata: plot structure data rg_converter: if True convert range from meter...
2efe6c85a152079f313e1ae3e1dcafab44cba753
53,313
from datetime import datetime def now_str(pattern=TIME_FMT): """Return a formatted timestring for the current time.""" # return time.strftime(pattern, time.gmtime()) return datetime.utcnow().strftime(pattern)
828fe7a15a160402a337a8498acfbcf53211c8e2
53,314
def categorical_crossentropy(Y, Yhat, eps=1e-8): """ Computes the categorical cross-entropy for one hot encoded labels Y - (m,dim_y) array of labels m=examples Yhat - (m,dim_y) array of logits """ m = np.shape(Y)[0] Yhat = np.clip(Yhat, eps, 1 - eps) # for numerical stability if this is us...
d69070fddb92b366d02344ba325652ae8f8bc22a
53,315
from typing import Tuple def yaml_remove_split(docstr: str) -> Tuple[str, str]: """Extract parameter summary within :yaml: tags in docstring, and clean up the :yaml: tag for the full docstring. Return cleaned up docstring, and summary version.""" key = ":yaml:" summary = "" i_start = docstr.fi...
e0e3e34871c56c5cc176fcd371e5402846771078
53,316
from typing import Iterator from typing import Any def isdictreversediterator(object: Iterator[Any]) -> bool: """Returns True or False based on whether the given object is a reversed dict iterator. Parameters ---------- object: Any The object to see if it's a reversed dict iterator. Retu...
b3e0733a876c3f1faf16269ed4343503ac64d3ce
53,317
def create_regex(s: str, initials: bool = True) -> str: """ Given a string representation of either a channel or marker, generate a standard regex string to be used in a panel template Parameters ---------- s: str String value of channel or marker to generate regex term for initials...
4289acfa614a45eabf06742aafc3d62b311d603f
53,318
from operator import or_ def verify_password(email_or_token, password): """ verifies the credentials provided by HTTP Auth, is invoked before endpoint is accessed Args: email_or_token: email address of user or authentication token password: user password (only required in case of login via...
f260408547ba22fea3bbe4f20bd905a5243ac252
53,319
import http def dataverse_config_get(node_addon, auth, **kwargs): """API that returns the serialized node settings.""" return { 'result': serialize_settings(node_addon, auth.user), }, http.OK
6f05d6addc62bbc60383ab5525a16fc3a114267a
53,320