content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def ref_properties_from_header(filename): """Look inside FITS `filename` header to determine instrument, filekind. """ # For legacy files, just use the root filename as the unique id path, _parts, ext = _get_fields(filename) serial = os.path.basename(os.path.splitext(filename)[0]) h...
1444fe700a7b1581092431b70479379a0dc37950
3,620,900
import requests import sys def auto_buy_item(info, ordered_items, place, settings): """ Proceeds to auto-buy the item that is in stock. Notifies the user if notifications are enabled. """ if delegate_purchase(info.get('webshop'), info.get('url'), settings): print("[=== ITEM ORDERED, HOORAY...
ba32f25d61acd3e754928718f1a9903d447574cb
3,620,901
def accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float: """ Calculate accuracy of given predictions Parameters ---------- y_true: ndarray of shape (n_samples, ) True response values y_pred: ndarray of shape (n_samples, ) Predicted response values Returns ------- ...
f01ec6dc97cf4ec171629e52810d3ed285d5c003
3,620,902
import sys import traceback import json import os import hashlib import io import subprocess def update_self(to_screen, verbose): """Update the program file with the latest version from the repository""" UPDATE_URL = "https://rg3.github.io/youtube-dl/update/" VERSION_URL = UPDATE_URL + 'LATEST_VERSION' ...
1642c5a3907dd1713b1acfd623afb29dff5340c7
3,620,903
def write_temp_file(content, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True): """写临时文件 .""" with NamedTemporaryFile(mode, buffering, encoding, newline, suffix, prefix, ...
6b276ffa8c7bbc1187bb97f0ec5da9d407f027ee
3,620,904
import subprocess import os def check_for_updates() -> None: """Identifies whether the track instance is git versioned, fetches from upstream and checks whether there are updates to pull""" log().info("Check for remote app updates on git remote..") def git_cmd(cmd) -> str: result = subprocess....
f258a33a5664b15b73bf10b9039db0635c470f4c
3,620,905
def create_metadata_table(ifu_list): """Build a FITS binary table HDU containing all the meta data from individual IFU objects.""" # List of columns for the meta-data table columns = [] # Number of rows to appear in the table (equal to the number of files used to create the cube) n_rows = ...
44558635546fcfc7cdb346a19c3f00acd3bec051
3,620,906
def set_layout_properties(layout_name, properties_dict, base_url=DEFAULT_BASE_URL): """Sets the specified properties for the specified layout. Unmentioned properties are left unchanged. Run ``getLayoutNames`` to list available layouts. Run ``getLayoutPropertyNames`` to list properties per layout. Arg...
50a90e8369bbedef9adf3aeae2ccc70c96b315f3
3,620,907
def get_data(query): """ Author - Jonathan Steward Function - Used to get data from the Database based on a pre-defined SQL Query Inputs - string - query to use when getting data returns - list - resulting data """ try: DBconnection = connector.connect( user="root", ...
ab5118825120892cab720fc751e1f4c539902277
3,620,908
import pickle def load_pickle(filename): """ Loads a serialized object Parameters: ----------- filename : string """ return pickle.load(open(filename,'rb'))
6525b73e211947ea0b2f76ec5f071d46bb806f06
3,620,909
def fasta_pred(fasta_file,pred_file,cutoff=-3,hits_only=False): """ """ pred_dict = read_predictions(pred_file) kmer_size = len(list(pred_dict.keys())[0]) all_kmers = {} seq_name = None current_sequence = [] header = ["#-->"] header.append("binds") header.append("best") ...
83099e19bb68fc5913c3639a296ea2038895d028
3,620,910
import argparse def parse_args(): """Parse arguments. Returns: argument namespace """ # Parse arguments parser = argparse.ArgumentParser() parser.add_argument('--load-model', help=("Path from which to load parameters and model weights " "for model found b...
8ba6661ad3927ce7e897da8da9de6b65b4a4d802
3,620,911
def clientsNamed(app): """A dictionary of client fixtures for all authenticated users. Keyed by user (eppn), the values are corresponding client fixtures. """ return {user: makeClient(app, user) for user in NAMED_USERS}
93c7538d6ba3f3200fc009d9cacb749a6d0ef33e
3,620,912
from typing import Union from typing import Iterable def to_np_tuple(prop: Union[int, Iterable]) -> np.ndarray: """Creates a np array of length 2 from a Conv2D property. E.g., stride=(2, 3) gets converted into np.array([2, 3]), where the height_stride = 2 and width_stride = 3. stride=2 gets converted int...
9d67cf2e608e01c41f7eeaf146b98ea61bec8dd1
3,620,913
def tetrode_identity_shuffle(multiunit): """Shuffle the correspondence between tetrodes and spike time """ n_tetrodes = len(multiunit.tetrodes) rand_tetrode_index = np.random.randint( low=0, high=n_tetrodes, size=n_tetrodes) return multiunit.isel(tetrodes=rand_tetrode_index)
e5dcb824f2081921befb9b407a561e90b3ea1317
3,620,914
import os def ceph_version(): """Retrieve the local version of ceph.""" if os.path.exists('/usr/bin/ceph'): cmd = ['ceph', '-v'] output = check_output(cmd).decode('US-ASCII') output = output.split() if len(output) > 3: return output[2] else: retu...
a05e3ace33d1e383897cad352cf19ffd9932fa37
3,620,915
def is_silent(data_chunk): """Returns 'True' if below the 'silent' threshold""" return max(data_chunk) < THRESHOLD
18e1108bab8edbc0b6f258af6ae24893795d15b6
3,620,916
def get_properties(value): """ Converts the specified value into a dict containing the NVPs (name-value pairs) :param value: :return: """ rtnval = None if isinstance(value, dict): # value is already a Python dict, so just return it rtnval = value elif '=' in value: ...
03f75e85e54a08b75b8d6e25b5d1dd65f7e987db
3,620,917
def union(llist_1, llist_2): """ Returns union of two provided LinkedLists Args: - llist_1(LinkedList): data to be written into the new block - llist_2(LinkedList) Returns: - True if the block was added. Otherwise False """ if llist_1 is Non...
503dc99cde100dd5986498d22649555e4caeae4f
3,620,918
import math def qft(qubits): """ Performs an in-place quantum fourier transform on the given register. Parameters: qubits (list[QubitPlaceholder]): The register to apply the QFT to Returns: A program containing the QFT gates. Remarks: Note that by the established convent...
6081fbe0bb1ed428a715c18db045863437024f24
3,620,919
def pay_worker_bonus(job_id, worker_id, api, con=None, assignment_id=None, send_notification=False): """ :param job_id: :param worker_id: :param bonus_cents: :param api: :param overwite: :param con: :param assignment_id: :returns True if payment was done, False otherwise """ ...
80e8c4e0a1b5526c1ad83b3e2ea104769abb999e
3,620,920
def policy_and_value_opt_step(i, opt_state, opt_update, get_params, policy_and_value_net_apply, log_probab_actions_old, value_predictions_ol...
dba007c50cd913a80e18f65d768533915dff4e83
3,620,921
def check_hits_in_ellipse(ellipses: np.array, hits: np.array) -> np.array: """Returns mask for specified hits, True if hit in ellipse, False otherwise """ k_hits = len(hits) / len(ellipses) duplicated_ellipses = np.repeat(ellipses, k_hits, axis=0) centers = duplicated_ellipses[:, :2] ...
2276b108b5d15fbf76c7d1ff907df029d9d9c56f
3,620,922
from typing import Dict from typing import Optional def get_optional_boolean_arg(args: Dict, argument_name: str) -> Optional[bool]: """ Extracts the argument from Demisto arguments, and in case argument exists, returns the boolean value of the argument. Args: args (Dict): Demisto arguments. ...
b4ab14557af2deb88b12c23405f4f09b53053672
3,620,923
def get_jaddr_from_comments(pp_lst, comment_lst): """ @brief reads in jump addresses wich were set by the reverse engineer @param pp_lst List of PseudoInstructions in push/pop represtentation @param comment_lst List of comments @return List of tuples (set jump address, address of jump instr...
7784c5cdab33ede4b5dbe76fe218095ce7d70bc9
3,620,924
def CalculateMeanValue(str_lengths:list): """ This function calculates the mean over all values in a list. :param str_lengths:list: lengths of all strings """ try: return int(round(sum(str_lengths)/len(str_lengths))) except Exception as ex: template = "An exception of type {0...
001acb0b9378befcd1f1ac5ed5392822fac0067d
3,620,925
import math def radangle(p0,p1): """ Radian angle between two points on a sphere in lon-lat (x,y) Parameters ---------- p0 : first point as a lon,lat tuple p1 : second point as a lon,lat tuple Returns ------- d : radian angle in radians Example ------- >>> ...
252b3be7cb41571cf26ba266b544d403f6413179
3,620,926
def annToMask(anno, height, width): """ Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask. :return: binary mask (numpy 2D array) """ rle = annToRLE(anno, height, width) mask = maskUtils.decode(rle) return mask
b5d8f92a2e284b9326946945af234294bfc33c96
3,620,927
def get_pdm_terms(site_index, n, adj_sites=4, shift=0): """ inputs: site_index (int): center site index n (int): number of sites in lattice (for enforcing periodic boundary conditions) adj_site (int): how many adjacent sites to collect pop and coherence values from shift (int): r...
34d7914ddd751cb75b04e855d68edb156c1defda
3,620,928
def clean_transcription(raw_string: str) -> str: """ Cleans up input transcriptions to replace any special characters with text :param raw_string: Input string to be cleaned :return: Cleaned string of alphas """ if not raw_string: raise ValueError parsed = raw_string.lower().replace(...
4e61a307547ee5ddc2e42ebcf8b49733bae49f5c
3,620,929
import subprocess def system(cmd, stdin=None, **kwargs): """A simple front-end to python's horrible Popen-interface which lets you run a single shell command (only one, semicolon and && is not supported by os.execvp(). Does not catch OSError! :param cmd: command to run (a single string or a list of s...
d85af1b90a3679ad268849e4c5769f519f67b49c
3,620,930
def glass(number): """ Return an array of Sellmeier coefficients for glass. The glasses all have a number. This number is used to look up the Sellmeier coefficients for glass. The number can be looked up with `ofiber.glass_name`. Use like this:: num = ofiber.glass_index("SiO2") ...
b274ec7a916aaad60e89a4b5563385a65a771acb
3,620,931
def isnan(x: _cpp.Variable) -> _cpp.Variable: """ Element-wise isnan (true if an element is nan). """ return _call_cpp_func(_cpp.isnan, x)
bedf9e3c2af9b557fa3c429d535a1a48d57d5419
3,620,932
import os from pathlib import Path def get_api_key(project_name, sh_env_var="CWL_ICA_API_KEY_SH", key_path_env_var="PROJECT_API_KEY_PATH"): """ Create a file using the contents of sh_env_var, run said file with key_path_env_var set to project_name This should then return an api-key. This is done with a s...
6f0d92a4b7b1318e7644d60c34c6fe2373eb97c8
3,620,933
def supply(request, page_name): """supply view_objects for user status.""" _ = page_name _ = request #todays_users = Profile.objects.filter(last_visit_date=datetime.datetime.today()) rounds_info = challenge_mgr.get_all_round_info() start = rounds_info["competition_start"] daily_status = Da...
4521dd68f5f2483932e2c4d7b40ae592fbd0eb38
3,620,934
import inspect def get_default_args(func): """ returns a dictionary of arg_name:default_values for the input function """ if not callable(func): raise TypeError("%s is not callable" % type(func)) if inspect.isfunction(func): print('a') spec = inspect.getargspec(func) el...
516cebc2f071a4f13b3784df0c3b5825b5fc21ba
3,620,935
import email def git_am_patch_split(f, encoding=None): """Parse a git-am-style patch and split it up into bits. :param f: File-like object to parse :param encoding: Encoding to use when creating Git objects :return: Tuple with commit object, diff contents and git version """ encoding = encodi...
7d7dfa1cdd6c84a5911c4cfea4d2e67026fb84ee
3,620,936
from typing import Tuple from typing import Dict def compute_retrieval_cosine(dot_product: np.ndarray) -> Tuple[Dict[str, float], np.ndarray, np.ndarray]: """ Args: dot_product: Result of computing cosine similarity between two sets of embeddings (emb1 @ emb2.T) with shape (num_datapoints,...
f18d74e015ac1ce9e1d6c095e2dc378b8a85465f
3,620,937
from io import StringIO def makeSVGedge(e): """ """ cs = StringIO.StringIO() curve = e._geomAdaptor() # adapt the edge into curve start = curve.FirstParameter() end = curve.LastParameter() points = GCPnts_QuasiUniformDeflection(curve, DISCRETIZATION_TOLERANCE, start, end) if poin...
ff08e5bebeb936f820f858a53d8cf322f07c1d3b
3,620,938
import os def create(dst, creator='Pyth'): """Create output file. Return handle and first id to use.""" try: os.unlink(dst) except os.error: pass Res.FSpCreateResFile(dst, creator, 'rsrc', smAllScripts) return open(dst)
8055ca3c5910ca489c86c939d29d9f4e85ac373c
3,620,939
from typing import Mapping from typing import Any from typing import Optional from typing import Iterable def create_and_join_world( connection: dm_env_rpc_connection.Connection, create_world_settings: Mapping[str, Any], join_world_settings: Mapping[str, Any], requested_observations: Optional[Iterable...
4a80f24bf67475b109b5e6d5e468243384732cc7
3,620,940
import logging import sys def setup_stream_handlers(conf): """Setup logging stream handlers according to the options.""" class StdoutFilter(logging.Filter): def filter(self, record): return record.levelno in (logging.DEBUG, logging.INFO) log.handlers = [] stdout_handler = logging...
c3a89bd91bfbe748774d87663709ad18afa3b1be
3,620,941
from sklearn.externals import joblib from sklearn.ensemble import RandomForestRegressor def Hyperparameter_Tune_model(use_choosen_model=True, model=None, RFR_dict=None, df=None, cv=3, testset='Test set (strat. 20%)', target='Iodide', ...
181f23885a48736e0022cfabbffe33d3af50af90
3,620,942
def process_id(input_ids, vocab_table, PAD, max_len=None, min_len=None): """Converts input ids (in text string) into their indices in vocab :param input_ids Tensor Id features. Shape=[group_size] :param vocab_table TFLookupTable Vocab table for id...
a9f710d497f483a1e3aa44cdc6125086f5b224a9
3,620,943
import time def test_recurring_jobs_when_volume_detached_unexpectedly(settings_reset, set_random_backupstore, client, core_api, apps_api, pvc, make_deployment_with_pvc): # NOQA """ Test recurring jobs when volume detached unexpectedly Context: If the volume is automatically attached by the recurrin...
8e8e352f8d5954c4b86f0a593bc378fbb34707f5
3,620,944
def dlcs_parse_xml(data, split_tags=False): """Parse any del.icio.us XML document and return Python data structure. Recognizes all XML document formats as returned by the version 1 API and translates to a JSON-like data structure (dicts 'n lists). Returned instance is always a dictionary. Examples:: ...
2eae1133557a094c1862d733553ac97ac124a672
3,620,945
from datetime import datetime def now_datetime(offset = 0): """ A function to return the current datetime. """ return adddays(offset, datetime.datetime.today())
6633f788e02bef6d8e0ab51ae6bffe0e2d3970f7
3,620,946
def generate_data(num_students=NUM_STUDENTS, num_items=NUM_ITEMS, num_responses=NUM_RESPONSES, prob_correct=PROB_CORRECT): """ Simulate student response data (independently of any parameters). :param int num_students: Number of unique student ids. :para...
bc81666a5e5552223a12a0f611099e2696f0481a
3,620,947
import ast def ast_name_node(**props): """ creates a name ast node with the property names and values as specified in `props` """ node = ast.Name() for name, value in props.items(): setattr(node, name, value) return node
880d9527d63c7b2c97a4bc616bf245dab6583f81
3,620,948
def _prepend_min(arr, pad_amt, num, axis=-1): """ Prepend `pad_amt` minimum values along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to prepend. num : int Depth into `arr` along `axis` to calculate minim...
7a5c0c22d6358197b659b7fa1c0526f4a4a0a4aa
3,620,949
def buildX(traj_file, t, X): """ Builds the node attribute matrix for a given time step. Inputs: traj_file : string indicating the location of the ground truth trajectory data t : scalar indicating current time step X : empty node attribute matrix in shape [n_nodes, n_features] Outputs: ...
3b0d3b18d9897364e1140103d7f049d5502d302a
3,620,950
import sys import ctypes import os def get_surface_id_from_canvas(canvas): """Get an id representing the surface to render to. The way to obtain this id differs per platform and GUI toolkit. """ win_id = canvas.get_window_id() if sys.platform.startswith("win"): # no-cover struct = ffi.ne...
301e2b4396f6ffd0135d47ca96d118832e9cd017
3,620,951
def get_answer_feedback(answer, player): """ Render the feedback text, if a review by player was given to answer """ qs = Review.objects.filter(answer=answer, reviewer=player) if not qs.count(): return '' return qs.get().feedback
6b5767740931504837fa149e57a0780d04572af6
3,620,952
def get_token_by_id(ikey, skey, host, token_id, ca=None): """ Returns a token. ikey - Admin API integration ikey skey - Admin API integration skey host - Duo host token_id - Token ID ca - Optional CA cert Returns a token object. """ url = '/admin/v1/tokens/' + token_id resp...
3f133dfe733286c55115cf8ef8c2faf56278b316
3,620,953
from typing import Dict import os import sys import stat def tree_info(folder_path, verbose=False) -> Dict[str, TreeInfo]: """Get the total disk space and disk space contributions of all subfolders in the given path. Returns: Dictionary: (totals, contributions) Both are in the form {folder_na...
58ac3b33f1234e0a20182a8d60e6bc2db75e465c
3,620,954
def frac_prop_calc(df_bin_org, prop, param_dict, catl_keys_dict): """ Computes the quenched fractions of satellites in a given mass bin. Parameters ---------- df_bin_org: pandas DataFrame Dataframe for the selected group/halo mass bin prop: string galaxy property being evaluate...
7c04878dca8f4841d445cf4ee3870ad230e5d69d
3,620,955
def move_left(board, row): """Move the given row to one position left""" board[row] = board[row][1:] + board[row][:1] return board
a0dc74f65abd5560db7c2fe602186d15b8fda3d2
3,620,956
def find_connected_continuations(continuation_arr, max_face_shape=(1152, 1152)): """ Finds the edges of a graph which describes the continuation connectivity """ sizes = continuation_arr.shape face_checked = np.zeros((6,) + continuation_arr.shape, dtype=np.bool) ...
bfc9a50dc83c9b527338c13d4f466ec9235bd7e4
3,620,957
def acp_account(): """Manage the user account of currently-logged-in users. This does NOT accept admin-specific options. """ if request.args.get('status') == 'pwdchange': alert = 'You must change your password before proceeding.' alert_status = 'danger' pwdchange_skip = True ...
d434f46e595a0579653ae045c655dcbdcd2c91fb
3,620,958
import re import torch def embed_seq(sequence, tokenizer, prottrans_model, device="cpu"): """ Embed a single sequence from the tokenizer and prottrans model. """ sequences = [sequence] sep_sequences = [] for seq in sequences: sep_sequences.append(" ".join([x for x in seq])) #print(...
2c8182e67aa2fe8fa1bf0dff332d8bd8a25a5fb2
3,620,959
from typing import Any def get_tile_from_info_dict(slide: Slide, info: Any): """ Get a tile from an info dict. Args: slide: info: info dict Returns: patch (PIL image) """ patch = slide.get_tile(info['w'], info['h'], info['mag'], info['size']) return patch
247e201cda88875d606dd7a4cdfdf56bee853d81
3,620,960
def rotate_via_numpy(xy, radians): """Use numpy to build a rotation matrix and take the dot product.""" x, y = xy c, s = np.cos(radians), np.sin(radians) j = np.array([[c, -s], [s, c]]) m = np.dot(j, np.array([x, y])) return m[0], m[1]
3567c8732a43d8a36dc92828d9d353822667b9f1
3,620,961
def get_quadrant(x, y): """ Returns the quadrant as an interger in a mathematical positive system: 1 => first quadrant 2 => second quadrant 3 => third quadrant 4 => fourth quadrant None => either one or both coordinates are zero Parameters ---------- x : float x coordina...
8650edb7a3e854eed0559f633dcf5cd0c7310db4
3,620,962
import pathlib def get_python_script_path(conn: fabric.Connection, envdir: pathlib.Path, scriptname: str = 'python') -> pathlib.Path: """Get path to specific script from Python/Anaconda environment.""" if not is_windows(conn): path = envdir / 'bin' / scriptname else: path = None p...
165e791f770999dad1df3a34767d4fdbdfdde8ab
3,620,963
import torch def get_nn_avg_dist(emb, query, knn): """ Compute the average distance of the `knn` nearest neighbors for a given set of embeddings and queries. Use Faiss if available. """ if True: # emb = emb.cpu().numpy() # query = query.cpu().numpy() if hasattr(faiss, '...
bdae7eccc624c04a766d2d905719204838efee36
3,620,964
def days_in_month(year, month): """ Inputs: year - an integer between datetime.MINYEAR and datetime.MAXYEAR representing the year month - an integer between 1 and 12 representing the month Returns: The number of days in the input month. """ leapyear=0 if(year%4 ...
b2988e9a6b1413ef0957413c10e5e4f5ef225d8b
3,620,965
def calculateUsedWater(temp_tank_before, temp_tank_after): """Calculate amount of used water based on temperature change and tank volume. :param temp_tank_before: float number :param temp_tank_after: float number :return: float used water volume in liters """ used_w = (tank_volume * (temp_tank_...
d737509368163112609e989cfe0f4f577eb4ff84
3,620,966
from re import DEBUG def newt_eval( x, coefficients, exponents, generating_points, verify_input: bool = False ): """Iterative implementation of polynomial evaluation in Newton form This version able to handle both: - list of input points x (2D input) - list of input coefficients (2D input...
344f1115bce9d7a3c193555f56a9fd7352edf07f
3,620,967
import requests import json def _get_token(user, password, host, port): """ Gets auth token. """ token_url = "{}:{}/api/token/".format(host, port) response = requests.post(token_url, json={ "username": user, "password": password }) if response.ok: return json.loads(response...
701bb7c1a740cfeca5c321bb6662b8f4e701cd81
3,620,968
def get_gin_confg_strs(): """ Obtain both the operative and inoperative config strs from gin. The operative configuration consists of all parameter values used by configurable functions that are actually called during execution of the current program, and inoperative configuration consists of all p...
e803bb988e7376997df0fd91febdbdd4d8353255
3,620,969
def post_queries_for_all_snapshots(network) -> Response: """Post query request for all snapshots Args: network (str): Network name Returns: Response: List[WholeQuerySummaryDict] Note: POST parameter: * query (str): Optional: target query (limit a query) """ req = ...
65c24abea9b6eeca0759a37877a8a490fd0ca9b9
3,620,970
import random def random_point(): """Returns a random point on a 100x100 grid.""" return (random.randrange(100), random.randrange(100))
6a2a2c3a4bc3f8347d538984354c2d9688989e14
3,620,971
def list_sharepoint_sites_command(client, *_): """ This function runs list tenant site command :return: human_readable, context, result """ result = client.list_sharepoint_sites() parsed_sites_items = [parse_key_to_context(item) for item in result["value"]] human_readable_content = [ ...
256928baedbeb5cbd350af40187a47a871dbf793
3,620,972
def explode_list_columns(df,explode_cols): """Own implementation of pandas explode we need an older version of pandas to run the code""" no_explode_cols = list(np.setdiff1d( df.columns , explode_cols)) df = df.set_index(no_explode_cols).apply(lambda x: x.apply(pd.Series).stack()).reset_index() return df
8a17ab140b7bd408ab0afa71b7d6ded21437620d
3,620,973
import _ctypes def _sparse_dense_vector_mult(matrix_a, vector_b, scalar=1., transpose=False, out=None, out_scalar=None, out_t=None): """ Multiply together a sparse matrix and a dense vector :param matrix_a: Left (A) matrix :type matrix_a: sp.spmatrix.csr, sp.spmatrix.csc :param vector_b: Right (B...
2dfd4ffc0d516860eb77f793cf4a5001b3880ca8
3,620,974
def get_prefix(bot, message): """ A callable prefix for the bot separeted into guilds and DM's Parameters ---------- bot commands.Bot message discord message """ prefixes = ['spektrumiter ', '!'] if not message.guild: return '!' return commands.when_me...
80f1d9b67f4bb766e5d841b1a9e0bc35e2d64e43
3,620,975
async def pergamum_login(session): """Logins the web session into the pergamum system.""" login_url = '/'.join([BIB_URL, 'pergamum/mobile/login.php']) data = { 'flag': 'renovacao.php', 'login': PERGAMUM_LOGIN, 'password': PERGAMUM_PASS, 'button': 'Acessar' } headers =...
16835cf3de7cc1dfd4964cdf75ce478d94e1f788
3,620,976
def ans(m, H, c=2, n=32): """Method of manufactured solutions test""" # setup grid d = H / n z = np.arange(n) * d + d / 2 zi = np.arange(n + 1) * d # setup solution rho = np.exp(-c * z / H) rhoi = np.exp(-c * zi / H) # rhoi = centered_to_interface(rho) w = np.sin(m * np.pi *...
41ae151b046c02128af021c07c200fd905781e42
3,620,977
def _align_for_coadd(imglist): """ Algin a group of images for coadding with astroalign. Parameters ---------- imglist : list list of images to align Returns ------- newlist : list list of new SingleImage instances with aligned images Notes ----- We wil...
d49659f0536ca3bbc4798a0f169a5edbcc0865da
3,620,978
from io import IOBase import json def create_from_json_file(filename, **kwargs): """Create a dlapp instance from JSON filename. Parameters ---------- filename (str): JSON filename. kwargs (dict): keyword arguments which would use for JSON instantiation. Returns ------- DLQuery: a DLQ...
bf2944660f704c9d2078dc44940121552ff95815
3,620,979
def control( year: int, month: int = 1, day: int = 1, hour: int = 1, minute: int = 1, half: int = 1, quarter: int = 1, week: int = 1): """Control function. Controls if the given time is possible. :param year: the year to control :param month: the month :param day: the day :param hou...
05bb25be10613fcdb0e4a7aba7a07646eb8118f5
3,620,980
def repeat(s, n): """ (str, int) -> str Return s repeated n times; if n is negative, return empty string. >>> repeat('yes', 4) 'yesyesyesyes' >>>repeat('no', 0) '' """ return (s * n)
b44b56b9e69783c7f57e99b61cc86e975c575a59
3,620,981
def convert_to_issues(statements): """Produce list of offending statements in set of files. :param statements: one item from list created by add_statement """ files = dict() for statement, path in statements: if path in files: files[path].update(statement) if statem...
681026d36b384a062c8420ad7ec8aa117d3d7097
3,620,982
from sklearn.mixture import GaussianMixture import warnings def gaussian_mixture_sm(eigvals, eigvecs, n_clusters, n_components=None, weight_by_eigval=False, keep_first=True, positive_eigs=False): """ Extends the Shi and Malik method to a GMM with no covariance constraints. * Use the eigenvectors of L_rw ...
9bef37ed06a61505ef46730aed60c3922de8fe63
3,620,983
def can_translate(user): """Checks if a user translate a product""" return user.permissions['perm_translate']
c6797346d8bd61637927af808bb9355a9220a91e
3,620,984
def read_xml_file_line_basis(xml_file, element): """ Read the xml file and capture only the elements we need. """ start_tag = f'<{element}>' # 3 end_tag = f'</{element}>' # 2 start_tag_identified = False # 3 captured_records = list() # 4 captured_line = '' with open(xml_file) as f: #...
be45d97bd3ca051f06c775b21184c158472cd824
3,620,985
def findDeque(code): """ Find the use of deque in the code Documentation: Fluent Python page 54 https://docs.python.org/2/library/collections.html#collections.deque https://pymotw.com/2/collections/deque.html """ dequeToken = (Token.Name, '^deque$') dequeIdi...
19a99c918311c3431a2499125725aaee83c99aa3
3,620,986
import html def create_footer(): """page footer""" footer = html.Footer( [ html.Div( [ html.P( [ html.Span( "{0}, version 0.1.0".format(app_name), ...
35ea610235749332fb7128afeadd9fcabde6b78d
3,620,987
def xyz_string(labels, coords): """ .xyz format string for this cartesian geometry :param labels: optional labels for the beginnings of atom lines, by index :type labels: dict """ assert len(labels) == len(coords) dxyz = '\n'.join( '{:s} {:s} {:s} {:s}'.format(asymb, *map(repr, xyz)) ...
be2d34fe41a3468c0764bbfd9d6960dc377375cc
3,620,988
def lazydict(f): """Decorator for constructing lazy dicts from a function.""" return LazyDict(f, f.__globals__, f.__name__)
633d62ac22c7253c753fbd9cc645cc6f1eb676a9
3,620,989
import pandas def Protein_translation_Amb(t, y, data, mRNAData): """ Defines ODE function Conversion of Amb_mRNA to protein p1,p2,p3....: Protein concentrations for all ODEs It will have list of all parameter values for all my ODEs, so 36 values : L, U, D for each mRNA to protein conversion equation ...
1730cf15d57566dc9ec461f3631fe0feeddd4b49
3,620,990
import logging import asyncio import inspect def allow_sync_invocation(): """ A class decorator, used to make all public async methods of the class to be invoke synchronically This action would take place only if the class has async_mode=False attribute """ def allow_sync_mode(func): def ...
7683001f7994d39b44747a0858c8663de2e202f3
3,620,991
def IssueRetryableCommand(cmd, env=None): """Tries running the provided command until it succeeds or times out. Args: cmd: A list of strings such as is given to the subprocess.Popen() constructor. env: An alternate environment to pass to the Popen command. Returns: A tuple of stdout and stde...
52cedab55d28c9f6cda2bcba7284dce5ced9afa7
3,620,992
import os def _get_abs_path(path): """Return the absolute path for a given path. :param path: ``str`` $PATH to be created :returns: ``str`` """ return os.path.abspath( os.path.expanduser( path ) )
3420a9624470c9a2129865356277864a6d930046
3,620,993
def square(num): """ Return the square values of the input number. The input number must be integer. """ return num ** 2
e4f88e5f00de7c469d372d9ce1a7e539941b3857
3,620,994
import requests def run_ticket_validation(provider_details, key_url=None, key=None, appid=None): """ Validates Steam session ticket. 'key' is the access key for Steam API. If not set, then 'key_url' must point to it. 'appid' is the Steam App ID for this application. Returns a unique ID for this p...
99fbeb6941a07084f115dc34010c4dad92b67b56
3,620,995
import math def timestamp_to_hex(timestamp): """ # 时间戳数转化为十六进制字符串 :param timestamp: 时间戳数 :return: 时间戳对应的十六进制字符串 """ if timestamp < 0: # 如果输入的时间戳数是负值 timestamp *= -1 # 则转化为正数 timestamp_list = math.modf(timestamp) # 分割整数位和小数位成为元组,第一个位置是小数位,第二个位置是整数位 four_byte_second = hex(int...
ba5c1118e3a0a9a55157a98cf5b7693d6540b151
3,620,996
import threading import time def launch_file_toucher(f): """Launch a loop to touch the given file, and return a function to call to stop and join it.""" halt = threading.Event() def file_toucher(): while not halt.isSet(): touch(f) time.sleep(1) thread = threading.Thread(target=file_toucher) ...
4581fb5906000f1c5032e1e40b4f9666d430f65e
3,620,997
def parse_gcov_file(gcov_file): """Parses the content of .gcov file written by gcov --intermediate-format Returns: str: Source file name dict: coverage info { line_number: hits } """ count = {} with open(gcov_file) as fh: for line in fh: tag, value = line.split(':') ...
878b51b9ee2e11aa7e2364229d1fbe61b9558e0d
3,620,998
def get_default_ophys_metadata(): """Fill default metadata for optical physiology.""" metadata = get_default_nwbfile_metadata() metadata.update( Ophys=dict( Device=[dict(name="Microscope")], Fluorescence=dict( roi_response_series=[ dict( ...
f50e23117d79f0d1d0b9e5c401e8bb2f60ed996d
3,620,999