content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def SetDocTimestampFrequency(doc:NexDoc, freq:float): """Sets the document timestamp frequency""" return NexRun("SetDocTimestampFrequency", locals())
dceb766792b6ca34d5f5759b0079acc5b70da5a9
3,640,800
def rsqrt(x:np.ndarray): """Computes reciprocal of square root of x element-wise. Args: x: input tensor Returns: output tensor Examples: >>> x = np.array([2., 0., -2.]) >>> rsqrt(x) <tf.Tensor: shape=(3,), dtype=float32, numpy=array([0.707, inf, nan], dtyp...
f219ae71b5136bc1b34a2bb06ec76dcdb7ee20bb
3,640,801
def is_card(obj): """Return true if the object is a card.""" return obj in CARDS_SET
21f155feadde94d652e120224a2712f2470a9926
3,640,802
def plot_lines( y: tuple, x: np.ndarray = None, points: bool = True, x_axis_label: str = 'Index', y_axis_label: str = 'Value', plot_width: int = 1000, plot_height: int = 500, color: tuple = None, legend: tuple = None, title: str = 'Graph li...
b938151b90005bc23bb9ed2f795dbf4620b26251
3,640,803
import re def obtain_csrf(session): """ Obtain the CSRF token from the login page. """ resp = session.get(FLOW_LOGIN_GET_URL) contents = str(resp.content) match = re.search(r'csrfToken" value="([a-z0-9\-]+)"', contents) return match.group(1)
a091ca33b6b0a43608261e46c54c7ae164a9d3af
3,640,804
def get_distance_curve( kernel, lambda_values, N, M=None, ): """ Given number of elements per class, full kernel (with first N rows corr. to mixture and the last M rows corr. to component, and set of lambda values compute $\hat d(\lambda)$ for those values of lambda""" d...
e085ea6b2122b052625df1c7b60115552112ffab
3,640,805
def _process_labels(labels, label_smoothing): """Pre-process a binary label tensor, maybe applying smoothing. Parameters ---------- labels : tensor-like Tensor of 0's and 1's. label_smoothing : float or None Float in [0, 1]. When 0, no smoothing occurs. When positive, the binary ...
5a71ded8ac9d3ef4b389542814a170f35ef18fdd
3,640,806
def guess_digit(image, avgs): """Return the digit whose average darkness in the training data is closest to the darkness of ``image``. Note that ``avgs`` is assumed to be a defaultdict whose keys are 0...9, and whose values are the corresponding average darknesses across the training data.""" ...
055a0d31f85ce6f5786d6bd6dfaed75bdb3ff5d6
3,640,807
import time def multiple_writes(self, Y_splits, Z_splits, X_splits, out_dir, mem, filename_prefix="bigbrain", extension="nii", ...
b2a7048628c54bf8976f9b3182fe4cecc18468e7
3,640,808
def new_parameter_value(data, parameter_key: str): """Return the new parameter value and if necessary, remove any obsolete multiple choice values.""" new_value = dict(bottle.request.json)[parameter_key] source_parameter = data.datamodel["sources"][data.source["type"]]["parameters"][parameter_key] if sou...
41160804aba582ce0c588762bb1a96ea53e258df
3,640,809
from typing import Sequence from typing import Optional def rotate_to_base_frame( pybullet_client: bullet_client.BulletClient, urdf_id: int, vector: Sequence[float], init_orientation_inv_quat: Optional[Sequence[float]] = (0, 0, 0, 1) ) -> np.ndarray: """Rotates the input vector to the base coordinat...
5651e0183cd61555f90fe6af1e5c5dc2bec6e8b5
3,640,810
def show_page_map(label): """Renders the base page map code.""" return render('page_map.html', { 'map_label': label.replace('_', ' '), })
623d47c4de57c1810c07475a70e501d55ee5e9ae
3,640,811
def create_clf_unicycle_position_controller(linear_velocity_gain=0.8, angular_velocity_gain=3): """Creates a unicycle model pose controller. Drives the unicycle model to a given position and orientation. (($u: \mathbf{R}^{3 \times N} \times \mathbf{R}^{2 \times N} \to \mathbf{R}^{2 \times N}$) linear_velo...
4d75c85079ca5350473c058019ae6f4763fdd97b
3,640,812
import sys import subprocess def cluster_pipeline(gff3_file, strand, verbose): """ here clusters of sequences from the same locus are prepared """ cat = CAT % gff3_file btsort1 = BEDTOOLS_SORT if strand: btmerge1 = BEDTOOLS_MERGE_ST sys.stdout.write("###CLUSTERING IN\033[32m ...
60f642e90e73b8cf53c0261e5fd2aa5f79637e1a
3,640,813
from typing import Tuple def stft_reassign_from_sig(sig_wf: np.ndarray, frequency_sample_rate_hz: float, band_order_Nth: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarr...
90aa2b019ace90500c38feb5e643a8ca3c02360a
3,640,814
from typing import List def download(*urls, zip: str=None, unzip: bool=False, **kwargs) -> List[File]: """ Download multiple zippyshare urls Parameters ----------- *urls Zippyshare urls. zip: :class:`str` Zip all downloaded files once finished. Zip filename will be tak...
a1197d264fa3305fb545a60e5963be2fc326aa5d
3,640,815
def pop_arg(args_list, expected_size_after=0, msg="Missing argument"): """helper function to get and check command line arguments""" try: value = args_list.pop(0) except IndexError: raise BadCommandUsage(msg) if expected_size_after is not None and len(args_list) > expected_size_after: ...
90b1f1ae596a9257d15cc189e87223b166252c9a
3,640,816
def d4s(data): """ Beam parameter calculation according to the ISO standard D4sigma integrals input: 2D array of intensity values (pixels) output: xx, yy: x and y centres dx, dy: 4 sigma widths for x and y angle: inferred rotation angle, radians """ gg = data dimy, dimx = np.sha...
f10c0792a2e200c980ccd6ffb286bdfabc90bb32
3,640,817
from astropy.utils import iers import warnings import six def checkWarnings(func, func_args=[], func_kwargs={}, category=UserWarning, nwarnings=1, message=None, known_warning=None): """Function to check expected warnings.""" if (not isinstance(category, list) or len(catego...
58a40594f48b1f47350e9b6a1ca1d956dfd63d04
3,640,818
from omas.omas_utils import list_structures from omas.omas_utils import load_structure def extract_times(imas_version=omas_rcparams['default_imas_version']): """ return list of strings with .time across all structures :param imas_version: imas version :return: list with times """ times = []...
2b13361dc713d90a946554383b556a8ced24ac55
3,640,819
import json def load_appdata(): """load application data from json file """ try: _in = open(FNAME) except FileNotFoundError: return with _in: appdata = json.load(_in) return appdata
afb3a69a5abf72cd14a8ae0c8c99ccc3350899a1
3,640,820
def compute_couplings(models_a, models_b): """ Given logistic models for two multiple sequence alignments, calculate all intermolecular coupling strengths between residues. The coupling strength between positions i and j is calculated as the 2-norm of the concatenation of the coefficient submatrices...
761c1987a7e230f70e123ce8d1746881b1b26cae
3,640,821
def update_checkout_line(request, checkout, variant_id): """Update the line quantities.""" if not request.is_ajax(): return redirect("checkout:index") checkout_line = get_object_or_404(checkout.lines, variant_id=variant_id) discounts = request.discounts status = None form = ReplaceCheck...
9394699c50bc3724ac253f288e23cc77eac05a3a
3,640,822
from typing import Optional def merge_df( df: Optional[pd.DataFrame], new_df: Optional[pd.DataFrame], how="left" ): """ join two dataframes. Assumes the dataframes are indexed on datetime Args: df: optional dataframe new_df: optional dataframe Returns: The merged dataframe ...
783111942086a23fbb13b1e96f2d098c7db0f963
3,640,823
import os import yaml def load_settings(settings_path: str = CHAOSTOOLKIT_CONFIG_PATH) -> Settings: """ Load chaostoolkit settings as a mapping of key/values or return `None` when the file could not be found. """ if not os.path.exists(settings_path): logger.debug( "The Chaos To...
43a7f8e83827df26a840a13a53d6c87e6bddf5ff
3,640,824
def _is_leaf(tree: DecisionTreeClassifier, node_id: int) -> bool: """ Determines if a tree node is a leaf. :param tree: an `sklearn` decision tree classifier object :param node_id: an integer identifying a node in the above tree :return: a boolean `True` if the node is a leaf, `False` otherwise ...
bdc5affe82c1c7505668e0f7c70dbb548170b6e1
3,640,825
async def commission_reset(bot, context): """Resets a given user's post cooldown manually.""" advertisement_data = await _get_advertisement_data(bot, context.guild) deleted_persistence = data.get( bot, __name__, 'recently_deleted', guild_id=context.guild.id, default={}) user_id = context.argumen...
06666421569b92fdf8a943351058e3f53c7d0777
3,640,826
def test_sample_problems_auto_1d_maximization(max_iter, max_response, error_lim, model_type, capsys): """ solve a sample problem in two different conditions. test that auto method works for a particular single-covariate (univariate) function """ # define data x_input = [(0.5, 0, ...
3db394c4b1cccb276d3efe80ff7561830fc82b7a
3,640,827
import logging def partition_round(elms, percent, exact=-1, total=100, *args, **kwargs): """ Partitions dataset in a predictable way. :param elms: Total Number of elements :type elms: Integer :param percent: Percentage of problem space to be processed on one device :param type: Integer :p...
c3d83a9da0d25d9e9a1f688620fc9a925535cb6a
3,640,828
def heatmap_numeric_w_dependent_variable(df, dependent_variable): """ Takes df, a dependant variable as str Returns a heatmap of all independent variables' correlations with dependent variable """ plt.figure(figsize=(10, 5.5)) figure = sns.heatmap( df.corr()[[dependent_variable]].sort_v...
46919deb37ee1f641983761a81ffeb830dac8217
3,640,829
from typing import Set from typing import Tuple import timeit def _handle_rpm( rpm: Rpm, universe: str, repo_url: str, rpm_table: RpmTable, all_snapshot_universes: Set[str], cfg: DownloadConfig, ) -> Tuple[Rpm, MaybeStorageID, float]: """Fetches the specified RPM from the repo DB and downl...
107d3e9b0d139663d33a415be8eccfb6541e1b4a
3,640,830
def numpy2seq(Z, val=-1): """Appends the minimal required amount of zeroes at the end of each array in the jagged array `M`, such that `M` looses its jagedness.""" seq = [] for z in t2n(Z).astype(int): i = np.where(z==val)[0] if i.size == 0: seq += [z.tolist()] else...
b46f6379a3eba0c5754c1a824dc28a43a10dc742
3,640,831
def winner(board): """Detirmine the game's winner.""" WAYS_TO_WIN = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) for row in WAYS_TO_WIN: if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: winner = board[row[0]] return winner if EMPTY not i...
6adb31e668c1d7e2723df7d65ab34246748c3249
3,640,832
def compute_inv_propensity(train_file, A, B): """ Compute Inverse propensity values Values for A/B: Wikpedia-500K: 0.5/0.4 Amazon-670K, Amazon-3M: 0.6/2.6 Others: 0.55/1.5 """ train_labels = data_utils.read_sparse_file(train_file) inv_propen = xc_metri...
df8f45cf48f056cee6f3f9026f546dcea0f9ee75
3,640,833
def tanh(x): """ Returns the cos of x. Args: x (TensorOp): A tensor. Returns: TensorOp: The tanh of x. """ return TanhOp(x)
bef86675a70714f3e33a6828353e1f71958c3057
3,640,834
def importBodyCSVDataset(testSplit: float, local_import: bool): """Import body dataset as numpy arrays from GitHub if available, or local dataset otherwise. Args: testSplit (float, optional): Percentage of the dataset reserved for testing. Defaults to 0.15. Must be between 0.0 and 1.0. """ asse...
411d8c1aa3e1d741e2b169f1a4c3065af8f5e82c
3,640,835
def mvstdtprob(a, b, R, df, ieps=1e-5, quadkwds=None, mvstkwds=None): """ Probability of rectangular area of standard t distribution assumes mean is zero and R is correlation matrix Notes ----- This function does not calculate the estimate of the combined error between the underlying multi...
2b15e3ce209d01e4790391242cbd87914a79fa5d
3,640,836
from typing import Union from typing import Iterable from typing import Dict from typing import Callable import random import os import warnings import functools def build_dataloaders( cfg: CfgNode, batch_size: Union[int, Iterable[int]], ) -> Dict[str, Callable]: """ Get iterators of built...
b878f0553c2491e9cc208ba500b02bc2d0f2226c
3,640,837
import functools def get_activity( iterator, *, perspective, garbage_class, dtype=np.bool, non_sil_alignment_fn=None, debug=False, use_ArrayIntervall=False, ): """ perspective: Example: 'global_worn' -- global perspective for...
4bb771f80beba242f59b54879563c4462d5ca0c6
3,640,838
import re def dropNested(text, openDelim, closeDelim): """ A matching function for nested expressions, e.g. namespaces and tables. """ openRE = re.compile(openDelim, re.IGNORECASE) closeRE = re.compile(closeDelim, re.IGNORECASE) # partition text in separate blocks { } { } spans = [] ...
dd77b86533dd43bcecf2ef944a61b59c4150aaae
3,640,839
import os def is_rotational(block_device: str) -> bool: """ Checks if given block device is "rotational" (spinning rust) or solid state block device. :param block_device: Path to block device to check :return: True if block device is a rotational block device, false otherwise ""...
caf6203160e637ab39152d84d2fff06e79fc3083
3,640,840
import sys import traceback def format_exc(limit=None): """Like print_exc() but return a string. Backport for Python 2.3.""" try: etype, value, tb = sys.exc_info() return ''.join(traceback.format_exception(etype, value, tb, limit)) finally: etype = value = tb = None
29bdbfbff4a1ce2d399a95c3a4685467a4022eaf
3,640,841
import random def make_dpl_from_construct(construct,showlabels=None): """ This function creats a dictionary suitable for input into dnaplotlib for plotting constructs. Inputs: construct: a DNA_construct object showlabels: list of part types to show labels for. For example, [AttachmentSite,Terminat...
2391ccb2e5ee73e083c116d369fbffeac964081d
3,640,842
import yaml import os def load_config(path: str, env=None): """ Load a YAML config file and replace variables from the environment Args: path (str): The resource path in the form of `dir/file` or `package:dir/file` Returns: The configuration tree with variable references replaced, or ...
ffe9944194bfe3e5be1ce4dbf0c9f1073c2d26f4
3,640,843
def update_service( *, db_session: Session = Depends(get_db), service_id: PrimaryKey, service_in: ServiceUpdate ): """Update an existing service.""" service = get(db_session=db_session, service_id=service_id) if not service: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND,...
0471c4bd496004a9c1cc5af4d806bd8109f62ca7
3,640,844
def import_flow_by_ref(flow_strref): """Return flow class by flow string reference.""" app_label, flow_path = flow_strref.split('/') return import_string('{}.{}'.format(get_app_package(app_label), flow_path))
c2f9fe0b9ccc409b3bd64b6691ee34ca8d430ed6
3,640,845
def _escape_value(value): """Escape a value.""" value = value.replace(b"\\", b"\\\\") value = value.replace(b"\n", b"\\n") value = value.replace(b"\t", b"\\t") value = value.replace(b'"', b'\\"') return value
b58a3236c0686c7fb6a33859986123dc2b8089cc
3,640,846
from typing import Iterable def find(*objects: Iterable[object]): """Sometimes you know the inputs and outputs for a procedure, but you don't remember the name. methodfinder.find tries to find the name. >>> import methodfinder >>> import itertools >>> methodfinder.find([1,2,3]) == 6 sum([1, 2...
fcfc3c4d0e6d72b6d9f1d7b7bfd46146d8bbf027
3,640,847
def join_returns(cfg, arg_names, function_ast=None): """Joins multiple returns in a CFG into a single block Given a CFG with multiple return statements, this function will replace the returns by gotos to a common join block. """ join_args = [ir.Argument(function_ast, info=n, name=n) for n in arg_na...
0a89c2c6df39e0693597358f01704619cbd1d0bd
3,640,848
def get_all(): """ Returns list of all tweets from this server. """ return jsonify([t.to_dict() for t in tweet.get_all()])
a8803f46ca4c32ea3a0f607a7a37d23a5d97c316
3,640,849
from carbonplan_trace.v1.glas_preprocess import select_valid_area # avoid circular import def proportion_sig_beg_to_start_of_ground(ds): """ The total energy from signal beginning to the start of the ground peak, normalized by total energy of the waveform. Ground peak assumed to be the last peak. """...
73fbbd90c8511433bcdae225daea5b7cba9e8297
3,640,850
import requests def post_file(url, file_path, username, password): """Post an image file to the classifier.""" kwargs = {} if username: kwargs['auth'] = requests.auth.HTTPBasicAuth(username, password) file = {'file': open(file_path, 'rb')} response = requests.post( url, fi...
b615e5a766e6ca5d0427bfcdbd475e1b6cd5b9bb
3,640,851
def bias_init_with_prob(prior_prob): """ initialize conv/fc bias value according to giving probablity""" bias_init = float(-np.log((1 - prior_prob) / prior_prob)) return bias_init
533f777df5e8346ab2eadf5f366a275bab099aec
3,640,852
def parse_number(s, start_position): """ If an integer or float begins at the specified position in the given string, then return a tuple C{(val, end_position)} containing the value of the number and the position where it ends. Otherwise, raise a L{ParseError}. """ m = _PARSE_NUMBER_VALUE.ma...
854e9290b5853e525ea1ba3f658f59cea37b117c
3,640,853
def training_data_provider(train_s, train_t): """ Concatenates two lists containing adata files # Parameters train_s: `~anndata.AnnData` Annotated data matrix. train_t: `~anndata.AnnData` Annotated data matrix. # Returns Concatenated Annota...
35016ecb6f57e2814dacc6e36408882025311bb9
3,640,854
import warnings def _build_trees(base_estimator, estimator_params, params, X, y, sample_weight, tree_state, n_trees, verbose=0, class_weight=None, bootstrap=False): """ Fit a single tree in parallel """ tree = _make_estimator( _get_value(base_estimat...
43259d71a5d666e371c90e15c1ca61241fbee8e0
3,640,855
def select_privilege(): """Provide a select Privilege model for testing.""" priv = Privilege( database_object=DatabaseObject(name="one_table", type=DatabaseObjectType.TABLE), action=Action.SELECT, ) return priv
721f8edd0b6777a082682e377a80c73f8dc2bb00
3,640,856
def plot_gaia_sources_on_survey( tpf, target_gaiaid, gaia_sources=None, fov_rad=None, depth=0.0, kmax=1.0, sap_mask="pipeline", survey="DSS2 Red", verbose=True, ax=None, outline_color="C6", # pink figsize=None, pix_scale=TESS_pix_scale, **mask_kwargs, ): """P...
e90d77cfd1f59dda5db8d6a4651acac0aeacc81e
3,640,857
def getLinkToSong(res): """ getLinkToSong(res): link to all songs :param: res: information about the playlist -> getResponse(pl_id) :returns: list of links to each song """ return res['items'][0]['track']['external_urls']['spotify']
e59fe598ed900a90dcf5376d265eedfc51d8e0a7
3,640,858
def entropy_sampling(classifier, X, n_instances=1): """Entropy sampling query strategy, uses entropy of all probabilities as score. This strategy selects the samples with the highest entropy in their prediction probabilities. Args: classifier: The classifier for which the labels are to be ...
ffc465a3e8a517e692927f051dea0162d3191cf9
3,640,859
def browser(browserWsgiAppS): """Fixture for testing with zope.testbrowser.""" assert icemac.addressbook.testing.CURRENT_CONNECTION is not None, \ "The `browser` fixture needs a database fixture like `address_book`." return icemac.ab.calexport.testing.Browser(wsgi_app=browserWsgiAppS)
a256b814a08833eec88eb6289b6c5a57f17e7d84
3,640,860
def parse_playing_now_message(playback): """parse_playing_now_message :param playback: object :returns str """ track = playback.get("item", {}).get("name", False) artist = playback.get("item", {}).get("artists", []) artist = map(lambda a: a.get("name", ""), artist) artist = ", ".join(l...
88d7c35257c2aaee44d1bdc1ec06640603c6a286
3,640,861
from datetime import datetime import json def test_in_execution(test_plan_uuid): """ Executor->Curator Test in execution: executor responses with the Test ID that can be used in a future test cancellation { "test-id": <test_id> }(?) :param test_plan_uuid: :return: """ # app.logger.debu...
147fd56af41c232fa874332e704c9e043f368d5c
3,640,862
import requests def load_remote_image(image_url): """Loads a remotely stored image into memory as an OpenCV/Numpy array Args: image_url (str): the URL of the image Returns: numpy ndarray: the image in OpenCV format (a [rows, cols, 3] BGR numpy array) """ respo...
a760e76df679cc15788332df02e5470ec5b60ec2
3,640,863
def evlt(inp : str) -> int: """ Evaluates the passed string and returns the value if successful, otherwise raises an error """ operand = [] # stack for operands operator = [] # stack for operators + parentheses i = 0 # loop variable, cannot do range because have to increment dynamically if i...
2c0ea8781e969f44fa0575c967366d69a19010eb
3,640,864
import os import argparse def is_dir(dirname): """Checks if a path is an actual directory""" if not os.path.isdir(dirname): msg = "{0} is not a directory".format(dirname) raise argparse.ArgumentTypeError(msg) else: return dirname
fc5f03f18ae6f37520dbff6c3143699ac234f6b6
3,640,865
def _create_preactivation_hook(activations): """ when we add this hook to a model's layer, it is called whenever it is about to make the forward pass """ def _linear_preactivation_hook(module, inputs): activations.append(inputs[0].cpu()) return _linear_preactivation_hook
7f4cc10f7e051ed8e30556ee054a65c4878f6c0f
3,640,866
import importlib def import_by_path(path): """ Given a dotted/colon path, like project.module:ClassName.callable, returns the object at the end of the path. """ module_path, object_path = path.split(":", 1) target = importlib.import_module(module_path) for bit in object_path.split("."): ...
939b3426f36b3a188f7a48e21551807d42cfa254
3,640,867
def ordered_links(d, k0, k1): """ find ordered links starting from the link (k0, k1) Parameters ========== d : dict for the graph k0, k1: adjacents nodes of the graphs Examples ======== >>> from active_nodes import ordered_links >>> d = {0:[1,4], 1:[0,2], 2:[1,3], 3:[2,4], 4:...
472e9e7d459e8a574de8edd5272c96b648b50207
3,640,868
def _exceeded_threshold(number_of_retries: int, maximum_retries: int) -> bool: """Return True if the number of retries has been exceeded. Args: number_of_retries: The number of retry attempts made already. maximum_retries: The maximum number of retry attempts to make. Returns: True...
c434e1e752856f9160d40e25ac20dde0583e50a6
3,640,869
import json def _get_and_check_response(method, host, url, body=None, headers=None, files=None, data=None, timeout=30): """Wait for the HTTPS response and throw an exception if the return status is not OK. Return either a dict based on the HTTP response in JSON, or if the response is not in JSON format, ...
559d85ee8f7d21445e5cfa0acc464b3e9ad98fe3
3,640,870
def moveb_m_human(agents, self_state, self_name, c, goal): """ This method implements the following block-stacking algorithm: If there's a block that can be moved to its final position, then do so and call move_blocks recursively. Otherwise, if there's a block that needs to be moved and can be moved...
f99fd14b2091a1e8d0426dcef57ce33b96fc1352
3,640,871
import os def create_initialized_headless_egl_display(): """Creates an initialized EGL display directly on a device.""" devices = EGL.eglQueryDevicesEXT() if os.environ.get("EGL_DEVICE_ID", None) is not None: devices = [devices[int(os.environ["EGL_DEVICE_ID"])]] for device in devices: display = EGL.eg...
5a0351936a6a4771869aed046da3f60ce1edd1bb
3,640,872
import tkinter def BooleanVar(default, callback=None): """ Return a new (initialized) `tkinter.BooleanVar`. @param default the variable initial value @param callback function to invoke whenever the variable changes its value @return the created variable """ return _var(tkinter.BooleanVar,...
451a43da5e9eb506fe8b928fa7f4e986c8da6b69
3,640,873
import re def parse_header(source): """Copied from textgrid.parse_header""" header = source.readline() # header junk m = re.match('File type = "([\w ]+)"', header) if m is None or not m.groups()[0].startswith('ooTextFile'): raise ValueError('The file could not be parsed as a Praat text file a...
ff47296868f93cbe55d15b29a2245ceb14ed5460
3,640,874
from datetime import datetime def create_amsterdam(*args): """ Creates a new droplet with sensible defaults Usage: [name] Arguments: name: (optional) name to give the droplet; if missing, current timestamp """ name = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S.%f") ...
ed01c67db180894bbcf2cdfee4cd2f45633cc637
3,640,875
def convert_inp(float_inp): """ Convert inp from decimal value (0.000, 0.333, 0.667, etc) to (0.0, 0.1, 0.2) for cleaner display. :param float float_inp: inning pitching float value :return: """ # Split inp into integer and decimal parts i_inp, d_inp = divmod(float_inp, 1) d_inp = d_in...
ce0e196ca570b02787842db3ec2efb6ac529685c
3,640,876
from matplotlib import pyplot as plt from typing import Dict from typing import Any from typing import Optional from typing import Set from typing import Tuple import warnings def plot(pulse: PulseTemplate, parameters: Dict[str, Parameter]=None, sample_rate: Real=10, axes: Any=None, ...
e417989116496e82aa6885f01e4ec864eb3cbd55
3,640,877
def is_ipv4(line): """检查是否是IPv4""" if line.find("ipv4") < 6: return False return True
bd602f5a9ac74d2bd115fe85c90490556932e068
3,640,878
def format_ica_lat(ff_lat): """ conversão de uma latitude em graus para o formato GGMM.mmmH @param ff_lat: latitude em graus @return string no formato GGMM.mmmH """ # logger # M_LOG.info(">> format_ica_lat") # converte os graus para D/M/S lf_deg, lf_min, lf_seg = deg2dms(ff_lat) ...
d1e6f111e70ec7bd532e3d14afe3c90dc99cb8f8
3,640,879
def loadData (x_file="ass1_data/linearX.csv", y_file="ass1_data/linearY.csv"): """ Loads the X, Y matrices. Splits into training, validation and test sets """ X = np.genfromtxt(x_file) Y = np.genfromtxt(y_file) Z = [X, Y] Z = np.c_[X.reshape(len(X), -1), Y.reshape(len(Y), -1)] np.ra...
18fb7269f2b853b089494e6021d765d76a148711
3,640,880
async def retrieve_users(): """ Retrieve all users in collection """ users = [] async for user in user_collection.find(): users.append(user_parser(user)) return users
914969f7beb75a9409e370b9e2453c681c37ff42
3,640,881
import hashlib def get_file_hash(path): """파일 해쉬 구하기.""" hash = None md5 = hashlib.md5() with open(path, 'rb') as f: data = f.read() md5.update(data) hash = md5.hexdigest() info("get_file_hash from {}: {}".format(path, hash)) return hash
a024b0002c019ec9bae4fca40e68919c6236b2fa
3,640,882
from nipy.labs.spatial_models.discrete_domain import \ def apply_repro_analysis(dataset, thresholds=[3.0], method = 'crfx'): """ perform the reproducibility analysis according to the """ grid_domain_from_binary_array n_subj, dimx, dimy = dataset.shape func = np.reshape(dataset,(n_s...
cffb667b80b0a049856dc7c11db6d81fd9521f49
3,640,883
def api_root(request): """ Logging root """ rtn = dict( message="Hello, {}. You're at the logs api index.".format(request.user.username), ) return Response(rtn)
b002724baefccdd0cd0dcc324fa23d9902186351
3,640,884
def load_data(filename: str): """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
412b197274ae4ca06e4cc7f9cd4b7d7b7c5934a0
3,640,885
def parse_esim_inst(line): """Parse a single line of an e-sim trace. Keep the original line for debugging purposes. >>> i0 = parse_esim_inst('0x000000 b.l 0x0000000000000058 - pc <- 0x58 - nbit <- 0x0') >>> ex0 = {'pc': 0, 'AN': False, 'instruction': 'b.l', 'line': '0x000000 ...
c9bc221d8658219edc3759584ece76a56954ccd4
3,640,886
def getcollength(a): """ Get the length of a matrix view object """ t=getType(a) f={'mview_f':vsip_mgetcollength_f, 'mview_d':vsip_mgetcollength_d, 'mview_i':vsip_mgetcollength_i, 'mview_si':vsip_mgetcollength_si, 'mview_uc':vsip_mgetcollength_uc, 'cmview_...
fe4b4c69f1631c0e571cd1590aa8eeb8fa5bc7bb
3,640,887
from unittest.mock import patch def test_coinbase_query_balances(function_scope_coinbase): """Test that coinbase balance query works fine for the happy path""" coinbase = function_scope_coinbase def mock_coinbase_accounts(url, timeout): # pylint: disable=unused-argument response = MockResponse( ...
d25d8d31ae5a7c22559c322edeed53404fc179ab
3,640,888
def process_phase_boundary(fname): """ Processes the phase boundary file, computed mean and standard deviations """ singlets = [] chem_pot = [] temperatures = [] with h5.File(fname, 'r') as hfile: for name in hfile.keys(): grp = hfile[name] singlets.append(np....
4e7f01e3265566f03fa4e7e21f13cb48a1777c9c
3,640,889
from sys import argv from argparse import ArgumentParser import os from re import DEBUG def main(): """Entry point for the check_model script. Returns ------- :class:`int` An integer suitable for passing to :func:`sys.exit`. """ desc = """Check actual files against the data model for ...
c82f3acef0cbca485611cb20b9b1121ea497306b
3,640,890
def blackman_window(shape, normalization=1): """ Create a 3d Blackman window based on shape. :param shape: tuple, shape of the 3d window :param normalization: value of the integral of the backman window :return: the 3d Blackman window """ nbz, nby, nbx = shape array_z = np.blackman(nbz)...
45ae8132aad01319e1728f0a4355dda4d5d7d145
3,640,891
def asset_movements_from_dictlist(given_data, start_ts, end_ts): """ Gets a list of dict asset movements, most probably read from the json files and a time period. Returns it as a list of the AssetMovement tuples that are inside the time period """ returned_movements = list() for movement in given_d...
b21355ad65c2603559ea00650d4ea6dd2a7d94f0
3,640,892
def update_work(work_id): """ Route permettant de modifier les données d'une collection :param work_id: ID de l'oeuvre récupérée depuis la page oeuvre :return: redirection ou template update-work.html :rtype: template """ if request.method == "GET": updateWork = Work.query.get(...
aed65c45d53fa9d7b551df6909fdece488f2ab65
3,640,893
def login_view(request): """Login user view""" if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, username=email, password=password) if user is not None: login(request, user) ...
702a3aa5a90cd5a5386a4fa3b74ab4b36d3748bb
3,640,894
import torch import random import os def set_seed(seed: int) -> RandomState: """ Method to set seed across runs to ensure reproducibility. It fixes seed for single-gpu machines. Args: seed (int): Seed to fix reproducibility. It should different for each run Returns: Rand...
af0117e54dd03751d1173f32ae495f1003cadb35
3,640,895
def mse(im1, im2): """Compute the Mean Squared Error. Compute the Mean Squared Error between the two images, i.e. sum of the squared difference. Args: im1 (ndarray): First array. im2 (ndarray): Second array. Returns: float: Mean Squared Error. """ im1 = np.asarray(im1)...
3d14472d3eb211855b53174990c3201bbae49086
3,640,896
import torch def bert_text_preparation(text, tokenizer): """Preparing the input for BERT Takes a string argument and performs pre-processing like adding special tokens, tokenization, tokens to ids, and tokens to segment ids. All tokens are mapped to seg- ment id = 1. Args: ...
f9b3de4062fd0cc554e51bd02c750daea0a8250c
3,640,897
def possibly_equal(first, second): """Equality comparison that propagates uncertainty. It represents uncertainty using its own function object.""" if first is possibly_equal or second is possibly_equal: return possibly_equal #Propagate the possibilities return first == second
12662df45d6ee0c6e1aadb6a5c4c0ced9352af35
3,640,898
def get_logs(): """ Endpoint used by Slack /logs command """ req = request.values logger.info(f'Log request received: {req}') if not can_view_logs(req['user_id']): logger.info(f"{req['user_name']} attempted to view logs and was denied") return make_response("You are not authoriz...
9708515dbd70c6e817f21c474fa1e96a26a1e9b4
3,640,899