content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import subprocess def sh(command, bg=False, **kwargs): """Execute a local command.""" kwargs['shell'] = True if bg: return subprocess.Popen(command, **kwargs) else: subprocess.check_call(command, **kwargs)
f4d4b562e77738a4a371587926b32a8c3df8422d
67,900
import torch def dataframe2onehot(df, node_attributes): """ Convert the data in dataframe format to a torch one-hot encodded format that the link prediction model can accept as input. The reason why this function receives as input both the dataframe of interest (df) and the NDSSL dataframe i...
85a96c579830581b066be121188501c85a83627f
67,901
def loaddb(cf, orderby='last DESC'): """Load all data in firewall database Parameters ---------- cf : Config orderby : str Sorting order for data Returns ------- List[Dict[blacklist database schema]] """ db = FwDb(cf) result = db.lookup('blacklist', orderby=orderby) ...
bd15c655f9dcb7582d558cc19e24a958ae5504e2
67,902
def __check_hdu(a) : """ Checks if input variable is an HDU """ if type(a) is fits.hdu.image.PrimaryHDU : return True else: print('Input must be HDU type, with header and data!') return False
02f35d00651f8887fc2ec5d3eb8f75b7009b3989
67,903
def items(): """This resource returns a list of items that were discovered by players in the game. Details about a single item can be obtained using the :func:`item_details` resource. """ return get_cached("items.json").get("items")
9b54ae20af547626e669da4881dadbe6c2e3677b
67,904
def gmm_pdf(x: np.ndarray) -> float: """ PDF. :param x: :return: """ centers = [(0, 0), (0, 10), (10, 0), (10, 10)] pdf = 0 for i in range(len(centers)): pdf += 0.25*multivariate_normal(np.array(centers[i]), np.eye(2)).pdf(x) return pdf
16f4c9c1df256668c556581815d062df2846249f
67,905
def FileEdit(** kwargs): """ Library function to edit/make new files :param deviceObj : Device object :type deviceObj : object :param stringEdit : File string content :type stringEdit : string :param filename : Filepath of the file to be edited :type filename : string :return: r...
224fbc27a345cdaa4ee68641237febdc305932d2
67,906
def read_signal_timing_file(signal_timing_filename): """Read signal timing (% time green, amber, red) by link and 30 secs csv file and store in pandas dataframe (signals_df)""" signals_df = pd.read_csv(supporting_files_path + signal_timing_filename) # reformat trantime_30sec to string, convert timedelta to ...
6236965fd14e346d9f7f13975e549f4cf3bc0e97
67,907
def is_event_stream(grid: MemoryGrid, **kwargs: Matcher) -> Matcher[tuple[str, dict]]: """ Match a Tahoe-LAFS directory entry representing a file which can be retrieved from the given grid and which contains an ``EventStream`` with a structure matched by the given keyword arguments. """ def is_...
f4611f4b5aa8624efda5d558dbcdf7786b9853e0
67,908
def scaled_dot_product_attention(q, k, v, mask): """Calculate the attention weights. q, k, v must have matching leading dimensions. k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v. The mask has different shapes depending on its type(padding or look ahead) but i...
8c387e3d053466c1301fa1a0a38b0d0fb28a52ed
67,909
from typing import OrderedDict import os def load_rois_predictions(dir: str, dataset: Dataset, num_labels: int) -> Predictions: """ TODO """ result = OrderedDict() for filename in dataset.keys(): probabilities = np.zeros((num_labels,)) rois_filename = os.path.basename(filename)[:-4...
9be7a99ec7803017ebf98613a4034158fdf0094e
67,910
from app.core.bot import bot async def send(sentence: Sentence): """ 情绪打分 \n return: 返回分数, point """ bot.send_text(sentence.to_user, sentence.sentence_text) return response_code.resp_200(sentence.to_user)
b214e5d66a41bddc89c36cc0181855b2da7cca68
67,911
import ast import os def blast(request, blast_form, template_init, template_result, blast_commandline, sample_fasta_path, extra_context=None): """ Process blastn/tblastn (blast+) query or set up initial blast form. """ if request.method == 'POST': form = blast_form(request.POST) ...
63db3b078c40fd3a0d79ab2e9dbb13e31a441f6f
67,912
def load_credentials_injector() -> CredentialsInjector: """Load the credentials injector fetching configuration from the environment.""" injector = CredentialsInjector() injector = add_credentials_from_env(injector) injector = add_credentials_from_env_file(injector) return injector
8cba31b5cfb8535feeb4f57f545a609eb67a54b7
67,913
def server_url() -> str: """ Get the url of the Enterprise Server. :return: The current url """ return core.BNGetEnterpriseServerUrl()
f8267d1baef00126082ebf02c086a6bf8b3a8e68
67,914
import pytz def load_from_yahoo(indexes=None, stocks=None, start=None, end=None, adjusted=True): """ Loads price data from Yahoo into a dataframe for each of the indicated assets. By default, 'price' is taken from Yahoo's 'Ad...
3f9ef862f795af88cf2aae7576b1e669a21111bc
67,915
import math def getDistance(p1, p2): """Return the distance between p1 and p2.""" return math.sqrt(sum([(p1[i] - p2[i])**2 for i in range(max(len(p1), len(p2)))]))
28d8156ad1eb5557a3fb3fa8bc7a94a66d06db3e
67,916
def subset(lst, k, empty=None, complement=False): """ An operative structure (like integer ot constant) that represent a subset of at most k elements. :param lst: The data for the subsets. :param k: The maximal bits for subsets. :param empty: The empty element, 0, by default. :param complement: ...
3296dad70a7cad13262140855f88e07fe0f43dd4
67,917
from typing import Optional def price_to_earnings_positive(asset: Asset, period: str, period_direction: FundamentalMetricPeriodDirection, *, source: str = None, real_time: bool = False, request_...
83d32dc97e8c5f8c77965c2e0fab2d03c684d2b9
67,918
import torch def get_axis_matrix(a, b, c, norm=True): """ Gets an orthonomal basis as a matrix of [e1, e2, e3]. Useful for constructing rotation matrices between planes according to the first answer here: https://math.stackexchange.com/questions/1876615/rotation-matrix-from-plane-a-to-b ...
3490b7968e9e9c6eab0004846f41857e3dc73242
67,919
from typing import Dict def load_pipeline(config: Dict, mode="train", **kwargs): """Load pipeline with required config. Args: config (Dict): Pipeline configuration. Returns: object: Pipeline object. """ validate_config(config) pipeline_class = globals()[config["training"]["...
a5d9df76b83491c4aa467125a5bf6f5929c223fa
67,920
from datetime import datetime def read_iso0_grib_data(fname): """ Reads a 2D field of iso-0 degree data from a MF NWP in GRIB format Parameters ---------- fname : str name of the file to read Returns ------- iso0_data : dictionary dictionary with the data and metadata...
7dc826b718594924aa882cbee085af243e8e68cc
67,921
def format_condition_value(conditions): """ @summary: ['111', '222'] -> ['111', '222'] ['111', '222\n333'] -> ['111', '222', '333'] ['', '222\n', ' 333 '] -> ['222', '333'] @param conditions: @return: """ formatted = [] for val in conditions: formatted += [it...
b79269ab375c1bec9724f29528c5a42d3bda3a72
67,922
from typing import Callable from re import T from typing import List def parse_list(s: str, convert: Callable[[str], T] = identity, fallback: List[T] = None) -> List[T]: """ :returns list of values converted from comma separated substrings :raises ValueError if value cannot be parsed and no fallback is pr...
6684b0df4330e3a6f039f88a93870918d805b86a
67,923
from sage.rings import sum_of_squares from warnings import warn def three_squares(n): """ Write the integer `n` as a sum of three integer squares if possible; otherwise raise a ``ValueError``. INPUT: - ``n`` -- an integer OUTPUT: a tuple `(a,b,c)` of non-negative integers such that `n =...
036d40660f237127956d252725ddc5d1357c37e7
67,924
def get_root_ids(phylogeny): """Get ids of root nodes in phylogeny Args: phylogeny (networkx.DiGraph): graph object that describes a phylogeny Returns: For all nodes in phylogeny, return ids of nodes with no predecessors. """ return [node for node in phylogeny.nodes if ...
624ab70805a9833c1fa46b9d3d8007afe43e2c10
67,925
def find_threshold_pr(y_test, y_preds, *, min_precision, min_recall): """ Find the threshold to use with `predict_proba()` for classification based on the minimum acceptable precision and the minimum acceptable recall. Parameters: - y_test: The actual labels. - y_preds: The predicted la...
2ce8f1c8c76e1258dec2c8dddb30ea94265a1ab1
67,926
from pathlib import Path from typing import List import os def get_unrename_dir(rename_dir: Path, json_files: List[Path], root_name: str) -> str: """جلب المسار القديم الخاص بالمسار الجديد Args: rename_dir (Path): المسار الجديد المراد جلب مساره القديم json_files (List[Path]): ملفات الجيسون الت...
accdf9e973e87628a7afe95619f47090b3aba92b
67,927
def ymdhms_format_from_day_sec(day, sec, sep="T", digits=None, suffix="", buffer=None): """Date and time in ISO format 'yyyy-mm-ddThh:mm:ss....'. Works for both scalars and arrays. Input: day integer or arbitrary array of integers defining day numbers ...
da99f88b688eb1a37bf30835d3f9ab6fc82a0357
67,928
def links_and_nodes(): """ J4 S1 / \ / / \ / S3 / J3 S2 \ / | / \ / | / J6 BR | // \ | // \ ~BI J2 INF ...
b8a154738407fee77fbd2d111443a42753ff749c
67,929
import numbers def is_numeric(N): """Determine if `N` is numeric. `N` may be a single value or a collection. """ def is_num(n): return isinstance(n, numbers.Number) and (not isinstance(n, bool)) if '__iter__' in dir(N): return False not in [is_num(n) for n in N] else: ...
4381d9ad7a3ee5f2f689b78f54b663e8349c58ff
67,930
def find_unique_namespace(namespace, increment_fn=None): """ Returns a unique namespace based on the given namespace which does not exists in current scene :param namespace: str, namespace to find unique name of :param increment_fn: fn(basename, index), returns a unique name generated from the namespace...
889e8ef59aaaa6e760ca90183dd2fb95b427c0e8
67,931
def GET(request): """Get this Rack's Machines.""" # Make sure required parameters are there try: request.check_required_parameters( path={ 'tileId': 'int' } ) except exceptions.ParameterError as e: return Response(400, e.message) # ...
14289462b52335d88c0ccc195530f878174809f2
67,932
def get_most_stimulated_cell(mem_cells, pattern): """ Tim te bao kich thich thag pattern nhat. :param mem_cells: :param pattern: :return: """ mem_cells = stimulate(mem_cells, pattern) sorted_cells = sorted(mem_cells, key=lambda elem: elem['stimulation']) # Sap xep tang dan` do kich ...
38692b3f8538b7f1d6b88a1c41afa55adbec113d
67,933
def is_timer_stopped(): """ Check whether the current timer level is stopped. Returns: bool: True if stopped. """ return f.t.stopped
62d3222241c81ae26678e597c2de4a09b7d7e2d3
67,934
def GET_feedback_search(): """ Returns all feedback documents """ try: feedbacks = feedback.find() return dumpJSON(feedbacks) except Exception as e: return respond500(e)
f3591d17a2898b936955424c3635d4be3fd62150
67,935
import requests def address_lookup(query: str) -> FeatureCollection: """ Looks up address using DataBC's geocoder """ q = { "addressString": query, "autoComplete": "true", "maxResults": 5, "brief": "true" } search_url = "https://geocoder.api.gov.bc.ca/addresses.json?"...
acc72f47565da19c4d7d5b78473ad0b55bf74055
67,936
def _TrackFitter(kwargs): """Returns TrackFitter module name. Arguments: - `kwargs`: Used to supply options at construction time of the object. """ isCosmics = kwargs.get("isCosmics", False) if isCosmics: return ("RecoTracker.TrackProducer.CTFFinalFitWithMaterialP5_cff", ...
2b61b02b5c9767362ad40eb2c968cd032d2f3f7e
67,937
import os def search(pathe, folder): """ Busqueda De carpetas al interior de los directorios que contienen las imagenes :pathe: Directorio en el cual se desea buscar :folder: Nombre de la carpeta que se desea encontrar Devuelve array con la totalidad de coincidencias encontradas """ direc...
12b7fe6125959b4abda605dd9bb633c783c8057c
67,938
def decode(bytes_sequence, encodings): """Return the first successfully decoded string""" for encoding in encodings: try: decoded = bytes_sequence.decode(encoding) return decoded except UnicodeDecodeError: # Try the next in the list. pass raise...
dc9a5077da63350dbd0f87fb2c743845fc184f59
67,939
import argparse def build_parser(): """Build argument parser""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "input_json", type=str, help="json of generated sequences", ) parser.add_argument("reference_file", ty...
21b83044e749c041b0d2a32630489823db8a8895
67,940
import os def modify_config_for_dataset(config, task_name, dataset_type, hdf5_type, base_dataset_dir, filter_key=None): """ Modifies a Config object with experiment, training, and observation settings to correspond to experiment settings for the dataset collected on @task_name with dataset source @dat...
af8bf3e7ea4d045888bd1f258997fd790e0e3b81
67,941
def SetAnswersAndReportsOnFeatures(features, map_root, topic_id, qids): """Sets 'status_color', 'answers', and 'answer_text' on the given Features.""" map_id = map_root.get('id') or '' topic = GetTopic(map_root, topic_id) or {} radius = topic.get('cluster_radius', 100) questions_by_id = {q['id']: q for q in ...
6a0594d91ea18cacefede3ca3679e5e73e2b3600
67,942
import os import sys def read_images(path, sz=None): """Reads the images in a given folder, resizes images on the fly if size is given. Args: path: Path to a folder with subfolders representing the subjects (persons). sz: A tuple with the size Resizes Returns: A tuple of (images,...
17a28129ba18c81b20d8bcf63fa57da13bae0199
67,943
from typing import List def get_bond_type_one_hot(bond: RDKitBond, allowable_set: List[str] = DEFAULT_BOND_TYPE_SET, include_unknown_set: bool = False) -> List[float]: """Get an one-hot feature of bond type. Parameters --------- bond: rdkit.Chem.rdchem.Bond...
f56dd1d1bdd3e8643c413f419dcfa1153400ed6e
67,944
def get_neurons_sink(model, connection): """Get the sink for connections into the neurons of an ensemble.""" ens = model.object_operators[connection.post_obj.ensemble] return spec(ObjectPort(ens, EnsembleInputPort.neurons))
a6b0303942e381dcb42bd4b9235a261fdb795e16
67,945
def calc_Q_max_H_RAC_d_t(region, A_HCZ): """ルームエアコンディショナーの最大暖房出力 Args: region(int): 省エネルギー地域区分 A_HCZ(float): ルームエアコンディショナー付温水床暖房を設置する暖冷房区画の面積 (m2) Returns: ndarray: ルームエアコンディショナーの最大暖房出力 """ # 外気温度・湿度の取得 outdoor = load_outdoor() Theta_ex_d_t = get_Theta_ex(region, outdoor...
064ea0b919dfddfe654f4b9132f56f16af66d1c3
67,946
def _sub_str_plot_fields(val, f, field_filter): """recursive helper function for _str_plot_fields""" # CSV type_ = type(val) if type_ in (bool, int, long, float) or \ isinstance(val, genpy.TVal): return f # duck-type check for messages elif hasattr(val, "_slot_types"): ...
440c59c1587e739f4ae488414b28e8928bc650b2
67,947
from typing import List def get_filtered_schemes(filter_to_apply: SchemeFilterType, schemes: List[Scheme]): """Apply filter on schemes and return the filtered list""" return list(filter(filter_to_apply, schemes))
dee2142f061d0d742d94c9253dfa3d11ac5f9b6d
67,948
import os import logging def take_screenshot(url, name): """Take screenshot of url and save to file, return path.""" driver = webdriver.PhantomJS(executable_path=C["phantomjs_exe"]) filename = os.path.join(C["image_dir"], "%s.png" % (name)) driver.set_window_size(*C["viewport"]) logging.info("Taki...
9893ed3519e063a9bf4cd354e2645f1da05fbc15
67,949
def view_and_manage_application(request, pk): """Displays the detail page for a specific application. Login required. Parameters: pk: Application id (primary key of Application instance) """ if request.user.uapuser.is_student: messages.warning(request, 'You do not have the permissions t...
82822fda09d6ce87fdbaa3df2e2ec03b5a58f925
67,950
def get_sigmas(dist): """Gets + and - sigmas from a distribution (gaussian or not). Ignores nan values. Parameters ---------- dist: np.array Distribution from which sigmas are needed Returns ------- sigma_minus: float - sigma sigma_plus: float + sigma """ ...
b25a1a6a90ae16a678b159ad7fbc09b7b0cb8cf6
67,951
def file_is_pdf(filename: str) -> bool: """ Check if `filename` has the .pdf extension. Args: filename (str): Any filename, including its path. Returns: True if `filename` ends with .pdf, false otherwise. """ return filename.endswith(".pdf")
ba9a540a1f0edd33e48010a001de4493bdff80d9
67,952
def get_logs_schema() -> graphene.Schema: """ Get a graphene Schema instace for a nydata.logs schema. """ logs_schema = graphene.Schema(query=Query, auto_camelcase=False) return logs_schema
faf9234169e51cee4d5e661bbab73d7c7336079d
67,953
import re def _convert_epytext(line): """ >>> _convert_epytext("L{A}") :class:`A` """ line = line.replace('@', ':') for p, sub in RULES: line = re.sub(p, sub, line) return line
49355ff1a30ef029a611fb948a15dcd6778017fb
67,954
def sender(address, use_queue=True, **kwds): """ :param str address: a pair (ip_address, port) to pass to socket.connect :param bool use_queue: if True, run the connection in a different thread with a queue """ return QueuedSender(address, **kwds) if use_queue else Sender(address)
2af4a64b05a3ff27c58723107bff73d153f1bf77
67,955
import time def currentTime(): """ Gets the current time in seconds from the epoch (i.e. time.time()) arguments: none returns: float - time in seconds since January 1, 1970 """ printDebug("In currentTime", DEBUG_INFO) return time.time()
3c21470e398aa032c555b4ea2190ebd8dbc63c92
67,956
import glob import os def isempty(path): """Determine whether the given directory is empty.""" flist = glob.glob(os.path.join(path,'*')) return flist == []
6f18b4f3956d25af20ee43c6177d76ac001db699
67,957
from typing import Callable from typing import Iterator from typing import Optional def mk_omit(skip_func: Callable) -> Callable: """The skip function is either minleq or maxgeq""" def omit_(pot: int, seqs: Iterator[Iterator[int]]) -> Iterator[Optional[int]]: """Given an iterator of ite...
ce1aafd0a67dd1acfbc9fc7b966fd14a76b1e85d
67,958
def reflection_matrix(U): """ https://en.wikipedia.org/wiki/Transformation_matrix#Reflection u = np.ndarray (2,Nvec) Returns ------- M : nd array (2,2,Nvec) u = np.array([2,2]) U=np.vstack((u,u/2.,2*u)).T """ diag_term = (U[0,:]**2)-(U[1,:]**2) anti_diag = 2*...
65fb16253293f4f0ecfa4cfd90c9a69f88f5b8e1
67,959
import random def generate_password(): """ Generate a random password of 12 to 15 characters""" nr_letters = random.randint(8, 10) nr_symbols = random.randint(2, 4) nr_numbers = random.randint(2, 4) random_char = [random.choice(characters) for char in range(nr_letters)] # Holds random alphabets ...
4386d062f7a2bdf3498a9bc6b34045108b264deb
67,960
def convert_to_boolean(data): """Converts categorical series or dataframe to boolean.""" if isinstance(data, pd.DataFrame): return _convert_frame_to_boolean(data) elif isinstance(data, pd.Series): return _convert_series_to_boolean(data) else: raise ValueError('Unknown data type ...
bfaa724d8b617840424a9925364a0a8ffc7d9426
67,961
def generateClosures(transactions, generators): """ Generate the closures of the generators transactions : list of sets The list of transactions generators : lists of lists The list of generator itemsets whose closures need to be computed Returns ...
452f12fec6dff0e3c8903344976fcb44728fa563
67,962
def _conv(layer_name, inputs, out_channels, kernel_size=[3, 3], strides=[1, 1], paddings=[1, 1], trainable=True, reuse=None): """convolution layer with relu and batch normalization Args: layer_name: e.g. conv1, conv2 x: input_tensor, [b, h, w, c] reuse: if reuse==tf.AUTO_REUSE: this conv...
bd3a764ef1a838ac91a8106c7ebcb5710b88b59c
67,963
def get_bad_devops_days(): """Return records for bad devops days.""" query = """SELECT stats.date, (CAST(stats.error as FLOAT) / CAST(stats.all as FLOAT) * 100) FROM ( SELECT DATE(time) as date, count(*) AS all, count(*) FILTER (WHERE status != '200 O...
fc2b68d09d2d2c2a9e9a3844d1748924406c419d
67,964
import numpy def voxelize(mesh, bounding_box, padding=True): """ Voxelize a mesh with a given bounding box """ # Note: voxels should be addressed with voxels[z][x][y] voxels = numpy.zeros((bounding_box[2], bounding_box[ 0], bounding_box[1]), dtype=bool) for height in r...
e411a81338f8cc16c8aadd13eaa60ed2acefc49a
67,965
import argparse import sys def parse_command_line(args): """Command line argument parser for configure.""" description="""Within build_directory (--build-dir), runs cmake on test specification directories (from --test-spec-dir or --xml-test-list), then builds and runs the tests defined via CMake.""" parse...
f96cb0ce072a97a8084ea975f727a73381f91e56
67,966
import torch def torch_hilbert(x_real, n_fft=None): """ Obtain imaginary counterpart to a real signal such that there are no negative frequency components when represented as a complex signal. This is done by using the Hilbert transform. We end up with an analytic signal and return only the imaginary ...
33bb230c78beb84ca5569c5fca8ebb61a36fd7c5
67,967
from typing import Tuple def validate(modal: Modal, loader: DataLoaderIAM, line_mode: bool) -> Tuple[float, float]: """Validates NN.""" print('Validate NN') loader.validation_set() preprocessor = Preprocessor(get_img_size(line_mode), line_mode=line_mode) num_char_err = 0 num_char_total = 0 ...
50f2b91004f7d75a6f93a3e7dc66f8ea18390ac0
67,968
import numpy def measured_area_correction(data, rebin=False): """ Given a detector measurement (either a flood fill or a main beam scan) return an area correction based on the pixel widths estimated from the data. The resulting correction will scale the pixels to counts per unit area, so must...
2d5dbd2f92c00eeec2628ec3b8f527f2705755be
67,969
def alert_if_no_copyright(glob, comment_prefix): """Prints names of all files missing a copyright message. Finds all glob-matching files under the current directory and checks if they contain the copyright message. Prints the names of all the files that don't. Returns the total number of file nam...
43235e6ac9a0484586c89c88715326ffe6683a1f
67,970
from typing import Callable def _get_ch(excel_list: list, title_slice: tuple, lvl, nesting, normalize: Callable) -> list: """ Recursively get a list of children :param excel_list: excel data :param title_slice: root category slice :param lvl: current level :param nesting: number nested levels ...
47cb7c6ce62d87b719658687baa5bf5b03d5afe1
67,971
def _add_padding(df: pd.DataFrame) -> pd.DataFrame: """ Add padding to name1 and name2 :param df: input dataframe :return: input dataframe with name1 and name2 columns padded """ df.loc[:, "name1"] = df.loc[:, "name1"].map(add_padding) df.loc[:, "name2"] = df.loc[:, "name2"].map(add_padding)...
ded1467fb27b27ef543ff22eb7eee476f5855bfa
67,972
from typing import Dict from typing import Any async def batch_upsert_samples( samples: SampleBatchUpsertBody, connection: Connection = get_project_write_connection, ) -> Dict[str, Any]: """Upserts a list of samples with sequences, and returns the list of internal sample IDs""" # Convert id in sample...
a11da3318c46407a8c7146df02b66f1aac2c5dce
67,973
def read_em(path_to_emfile: str) -> tuple: """ Function that reads a .em dataset (in the tom format). :param path_to_emfile: str, pointing to the .em file :return: tuple header, value where header is a dictionary specifying 'Machine_Coding' 'version' 'old_param' 'data_type_code' ...
ad6408e637dc2759d394e875392d52a6270038c2
67,974
def get_uptime(): """ Returns system uptime. Uptime is read from /proc/uptime file and converted to human readable format. """ try: file = open('/proc/uptime', 'r') data = file.read().split() file.close() except IOError: raise OSInfoError('Unable to open file: /...
0269df048bdee166d92cb00aed567284cc53ec98
67,975
import collections def merge(qrels, run, queries): """Merge qrels and runs into a single dict of key: query, value: tuple(relevant_doc_ids, candidate_doc_ids)""" data = collections.OrderedDict() for query_id, candidate_doc_ids in run.items(): try: query = queries[query_id] ...
8d30a82dd789d01a03101e0dfc30b8df3f4261cb
67,976
def index(): """ Input form """ # TODO: Think about adding drag and drop plugin # TODO : separate the form session.job = "" dbLinkBudget.Job.user_id.writable = False dbLinkBudget.Job.user_id.readable = False if auth.is_logged_in(): record = dbLinkBudget.Job((dbLinkBudget.Job.id...
258ce98ab60f6a2a4934ebf3c8ac6f49a5f6811a
67,977
def update_Domain_disable( ctx, dbDomain, dbOperationsEvent=None, event_status="Domain__mark__inactive", action="deactivated", ): """ Disables a domain :param ctx: (required) A :class:`lib.utils.ApiContext` instance :param dbDomain: (required) A :class:`model.objects.Domain` object ...
405bb4054552c70aa3b46ecb9dd460ce6920cf36
67,978
def rolling_max_drawdown_nb(returns, window, minp): """Rolling version of `max_drawdown_nb`.""" def _apply_func_nb(i, col, _returns): return max_drawdown_1d_nb(_returns) return generic_nb.rolling_apply_nb( returns, window, minp, _apply_func_nb)
b1c0c2aba3ae5f4aedfa1fc50ab1114d37bd0c22
67,979
from datetime import datetime import uuid async def register_output(conn: asyncpg.connection, data: schemas.MsCreateOutput): """ This function registers mass_spec processed data. It registers results of derivation with a given methodcode in the result table and and the corresponding action of derivati...
b69e08be1577752f767f63f805303501176f9718
67,980
import requests import time def make_request(url, timeout=60, *args, method='GET', **kwargs): """ Failure-resistant HTTP GET/HEAD request helper method. """ retry_count = 0 max_retries = 5 while True: try: response = SESSION.request(method, url, *args, timeout=timeout, **kw...
a7c2c9a66ca6f92036a03705d61b71f5035221d8
67,981
def _merge(source, destination): """ https://stackoverflow.com/a/20666342/3639005 >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } } >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } } >>> _merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail...
237e66acdf108dcf201d5650737b105f18d8561e
67,982
import math def calcCirclePos(robotIdx, numRobots, radius=3, center=(0,0)): """ Helper function to distribute robot positions on a circle. """ gamma = 2*math.pi / numRobots x = radius * math.cos(gamma * robotIdx) + center[0] y = radius * math.sin(gamma * robotIdx) + center[1] phi = gamma *...
393c044dcb4016c34b8efe2a7acd185b45c52467
67,983
import json def getToken(username, password): """ getToken - Get authentication bearer token. Get 'username' and 'password', request data on auth endpoint and return token object. Parameters: username (str): Username to login (cpf). password (str): Password of given username (born da...
61657545b8de2fd3251bec480c90540f2eb7c33b
67,984
def eiffel_activity_triggered_event(): """Eiffel activity triggered event.""" return { "meta": { "version": "3.0.0", "source": {"name": "eiffel-graphql-api-tests"}, "type": "EiffelActivityTriggeredEvent", "id": "693c3bac-10a6-4b77-82d7-430139195c1e", ...
8ab4b52e105708cd70746feb13f8c12522d505ee
67,985
def load_content(key): """ Returns the value of site content """ content = SiteContent.objects.get(variable = key) return content.val
1ff77288c97b12cdc8fa88d8b9139ba35aacc7d8
67,986
def _valley_kernels(size, flat_list): """Generate normalized V-shape and U-shape kernels to compute valley index. Parameters ---------- size : int Size of the kernel. flat_list : list of floats in [0,1[ Fractions of flat along the center line of the V-shape kernels. A certain ...
58dfaa8bc7de9b164a9c2dca828754a189b6ba81
67,987
from typing import Dict from typing import List def _encode_by_batch(documents: Dict[str, List], tokenizer: Tokenizer, nlp: English, dataset_info: DatasetInfo, bos_token="<BOS>", sep_token="<SEP>", ...
f5f5e0d759b2bb3cc57e1f627494a1d9e3d41681
67,988
def index(lhs, rhs, ctx): """Element i (any, num) -> a[b] (Index) (str, str) -> enclose b in a # b[0:len(b)//2] + a + b[len(b)//2:] (any, [x]) -> a[:b] (0 to bth item of a) (any, [x,y]) -> a[x:y] (x to yth item of a) (any, [x,y,m]) -> a[x:y:m] (x to yth item of a, taking every mth) (num, any...
808c84d1401aaf9b85150fe91f9f2fabb543c93c
67,989
import typing def read_write_read(pv_name: str, data: dict, *, options: typing.Optional[dict] = None, pvrequest: str = 'field()', cancel_on_keyboardinterrupt: bool = False, timeout=1): """ Write to a Channel, but sandwich the writ...
c38d14090c5b25fd8b8d5e1e1277e6494e497b80
67,990
def open_file_handler(file_name): """ function returning opened file handler :param file_name: :return: """ return open(file_name, mode='r', encoding='utf8')
9f78ba9e11060cff515405ffc87d48a585fdc2ed
67,991
import logging import base64 import six def config(conf): """ The config callback will get configuration details from 'conf' object. 'conf' object contains information like host, port, username, password etc. The read method is registered as read callback along with module_config. """ plugin_c...
11507a33aaedc0af34ba29a210c3100b8c08e4e1
67,992
def pdf_from_cf_with_fft(cf, h=0.01, q=9, level=3): """Calculates pdf from characteristic function. Uses fast Fourier transform with Newton-Cotes integration following [WZ]. Defaults to using Simpson's method (3-point Newton-Cotes integration). Parameters ---------- cf : callable Singl...
f2d8e95deeeb73269fa9a57c0bbe0e09dfbe9c87
67,993
import os def CalculateHostMd5Sums(paths): """Calculates the MD5 sum value for all items in |paths|. Directories are traversed recursively and the MD5 sum of each file found is reported in the result. Args: paths: A list of host paths to md5sum. Returns: A dict mapping file paths to their respecti...
1adce12ab3b940872139a187817ed4375396a327
67,994
def make_polyadic_sampler(input_dim: int, kappa: int = 2) -> XGenerator: """Samples with local structure centered around kappa N(0, 1) anchor points. To make this work in jax we actually implement this by first sampling kappa anchor points, then randomly the tau batch points from these kappa anchors (with repl...
1e38512749cf61ad001f0f9442ef81c1362f1ac8
67,995
import re def is_valid_vlive_url(url: str) -> bool: """Uses a regex to check if the given url is a valid 'vlive.tv./video/' address.""" # VLIVE videos are only identified by numbers in the url (unlike Youtube IDs, # for example) vlive_url_regex = r"(vlive\.tv\/video\/[0-9]*)" if not re.search(vl...
35c741ea512cad5edd791ebbb8acef99b19d84d3
67,996
import functools def setup_required(func): """Decorator to handle routes that need setup to have been completed This decorator should be applied to nearly all routes""" @functools.wraps(func) def decorated_function(*args, **kwargs): config = get_user_config() if not config.isConfigured: raise c...
908fb802187ec1b2e0fc701c00aff37c15bfe0c7
67,997
import urllib def test_http_access(by_ip=False): """ Test plain HTTP access and return three values: 1. The result - one of the HTTP_ACCESS_* constants 2. isup.me info - one of the HTTP_ISUP_* constants 3. Subdomain block result """ sites = http_list proxy = proxy_addr print("[O]...
a748331e800f139c8832ffd3c7054ad2cd64c802
67,998
from typing import Tuple import argparse def loadbuild_cli() -> Tuple[bool, bool]: """ Convenience CLI args for rebuilding data using `load_or_build` """ parser = argparse.ArgumentParser() parser.add_argument('--rebuild', action='store_true') parser.add_argument('--rebuild-down', action='store_true') ...
a99515b4fdadb733fe398f64b919b531787dade1
67,999