content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def gcp_type_constraints(actions, smt_lib = False, enc = False): """ Builds GCP resource type constraints Args: actions (list): actions smt_lib (bool, optional): use SMT-LIB syntax. Defaults to False. enc (bool, optional): use action encoding. Defaults to False. R...
88f843f599ca5fd16586c8d539702e672a79f7a4
80,171
def createCurveFromJoint(joints, name="curve", ibtCVNum=0, degree=3): """ Create a nurbs curve along the given joints :param joints: `list` list of joint nodes :param name: `string` name of the built surface :param ibtCVNum: `int` number of cv points added inbetween the joint position :param deg...
1f02715af2cdb7088003c67c1362db1c03eec919
80,173
from bs4 import BeautifulSoup def tag(tagname, attrs=None, text=None, dtrs=None): """Return a soup Tag element.""" attrs = {} if attrs is None else attrs dtrs = [] if dtrs is None else dtrs newtag = BeautifulSoup('', features='lxml').new_tag(tagname, attrs=attrs) if text is not None: newta...
911ba6fe1d26b0acfd9ca0eec5f2bfb0369e6e2e
80,175
def fig_MT_ageing(simPa, file_figure, num_fig, c_times): """ Calculate the age-dependent microtubule catastrophe frequency Args: ------- simPa: parameter set Simulation parameters in "ParameterSet" format. file_figure: str Folder for storing figures and data. num_fig: int ...
74ac21600b5f927a69b5cd246b578b0d1b3c2fd4
80,176
def ent_fidelity_channel(K, d): """ Finds the entanglement fidelity of the channel given by the set K of Kraus operators. d is the dimension of the input space. """ Bell = MaxEnt_state(d) K_choi = (1.0 / d) * Choi_representation(K, d) return np.real(Tr((Bell) @ K_choi))
6e428b9991185cfcae1a07df3facb01ec96d527d
80,177
from re import T def prep(ist=None, soll=None, ignoreclass0=False, isautoencoder=False, clip=False): """ Function to prepare ist and soll variables for the selected loss function. :type ist: theano.tensor.var.TensorVariable :param ist: Source variable (output of the network) :type soll: theano.t...
cfe6cdea79332eaabd0c16ef2de20cdb554973c9
80,178
def create_food_row(food, selection_callback, register_dynamic_font_callback=None, image_height=50, display_string=None): """ Creates ListBoxRow to display food name and image. :param food: food dictionary :param selection_callback: function to be called when user is clicked :pa...
dc866117a1d69d7ae2ecbf362781966db7e40767
80,179
import threading def make_alert(id, timer_delay, bot, chat_id, message): """Создает событие оповещения""" print('make alert') t = threading.Timer(timer_delay, send_alert, args=(id, bot, chat_id, message)) t.start() return t
ec41fecec7ab5d7d1761e6c01d06e7bacb398813
80,180
import math def marginal_parameter_likelihood(p: float, lambda_: float, x: int, tx: float, T: float) -> float: """Computes the marginal likelihood of the parameters lambda and p, given the transaction history. See http://brucehardie.com/papers/018/fader_et_al_mksc_05.pdf equation (3). Args: p (fl...
a90140259da58247b13f4ce165f035076c9816be
80,182
import re def merge_onehot( dataset_df, col_name_no_x ): """Convert col_nameX features to single feature X means some integer value. Doesn't work with multiple calls - returns 0s for all col_name_no_x. """ dataset_df_cpy = dataset_df.copy() # 1. Identify columns all_df_columns = dataset_df...
d33ca7f9ba067b132620decae0961720ea9308d4
80,184
def is_heshehishers(node): """ Searches for pronouns "he", "she", "his", and "hers", returning True if found. """ if len(node) != 1: return False target = node[0].lower() pos = node.label() return ((pos == 'PRP') and (target == 'he' or target == 'she')) or \ ((pos ...
af2103b1e0ebe5b2ee495f52a1bd58079f2b929c
80,186
async def get_borrowing_users(): """returns a list of all Books together with the user that borrows it""" session = Session() ret = session.query( BorrowingUserTable.key, BorrowingUserTable.book_key, BorrowingUserTable.user_key, BorrowingUserTable.return_date, Borrowi...
0797ea3206fcc2cea38992c2bd86b6443a5eb716
80,187
def parse_si_calc_file(fpath: str, non_equity: bool = False) -> pd.DataFrame: """Parse the Excel file at `fpath` and return a DataFrame. `non_equity` should be True if the Excel file is a "Non-equity" file as published by ESMA. The resulting DataFrame will have the ISIN column as its index. """...
5441ac23015727bc15181f480ba3e50fcb13f56f
80,188
def get_order_db(): """Obtain the order_db table from Mongo.""" client = MongoClient( DB_NAME, username=DB_USER, password=DB_PASSWD) return client.order_db
28af1a60a3fd04fafeb3d5ba815f9bb42d3ccad6
80,189
def task(func=None, pool=None, max_retries=0, priority=default_priority): """Task decorator - setus up a .delay() attribute in the task function""" if func is None: return partial(task, pool=pool, max_retries=max_retries) if pool is None: pool = default_pool def delay(*args, **kwargs)...
804284ccff888748c53e45f0b75afd4e10ba5593
80,190
def get_finetune_lfo_amount(header: bytes) -> float: """Return finetune LFO amount (0.0-1.0).""" assert isinstance(value := _unpack(header, "FINETUNE_LFO_AMOUNT"), float), type(value) assert 0.0 <= value <= 1.0 return value
6bd250791c363ec95c1af08c57eeea82ab9df588
80,192
def add_poster(request, contest_id): """ Renders the page for adding a poster. Dispatches to :func:`add_person` with :attr:`role` set to ``True``. :param request: the request object used :type request: HttpRequest :param contest_id: the contest ID :type contest_id: int """ return ad...
591e8f86c8d7b8513f9ced05653c328bc4ae3b92
80,193
def parse_lookup_expression(element): """ This syntax parses lookups that are defined with their own element """ lookup_grammar = r""" lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")" number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?" _ = ~r"[\s\\]*" # whitespace character ra...
04c2e0d94ee1bef21b7803ac88688f8fd54a9535
80,194
def tas_below_tasmin( tas: xarray.DataArray, tasmin: xarray.DataArray ) -> xarray.DataArray: """Check if tas values are below tasmin values for any given day. Parameters ---------- tas : xarray.DataArray tasmin : xarray.DataArray Returns ------- xarray.DataArray, [bool] Exampl...
5c89a1ce815af147de64eb6fd700f4a528b816cf
80,195
def task_id_ranges_format(value): """Space-separated number ranges in 'start-end' format.""" try: start, end = [int(i) for i in value.split('-')] except ValueError: message = ("Incorrectly formatted task ID range. " "Argument values should be numbers in the format 'start-e...
9081765efc6b6240a243798b635573d6a44be470
80,196
def std_scale_factor(dim, projection_type): """ Returns the multiplicative scaling that should be applied to the output of :func"`std_error_generators`, before using them as projectors, in order to compute the "standard" reported projection onto that type of error (i.e. the coefficient of the standa...
47e033602841f83427f64d133fa07180e6e50ed0
80,198
def plot_field( field, color='deep', threshold=0.2, alpha=0.7, show=True, title=''): """ This function takes a tensorfield and plots the field density in 3D space. The field describes an atomic "density" at each voxel. Parameters: field (pytorch t...
6d77dabe34f04439d9d8a7e6e1dcc98d7a214e06
80,199
import math def __rotate(origin: tuple, point: tuple, angle: float): """ Rotates a point counterclockwise by a given angle around a given origin. :param origin: Landmark in the (X, Y) format of the origin from which to count angle of rotation :param point: Landmark in the (X, Y) format to be rotated ...
af8acd38d07042c1ab8d9ae3fe05afb7a1fea623
80,200
from typing import Callable import functools def fold_by(fn: Callable[[T1, T2], T1], start: T1) -> Callable[[ActualIterable[T2]], T1]: """ >>> from Redy.Collections import Traversal, Flow >>> def mul(a: int, b: int): return a * b >>> lst: Iterable[int] = [1, 2, 3] >>> x = Flow(lst)[Traversal.fold_...
c66e1cd47eb14cb5a6ab66dc3a5907a182c2928c
80,201
def precision_ranges(result2rank, total_terms): """Computes precision at standard cutoff ranks: [5, 10, 15, 20, 30, 100, 200, 500, 1000] Args: result2rank: A dict of source to ranks of good translation candidates. total_terms: The expected term count. Returns: A dict containing a p...
7e1c60030933530c1d1b1bd09387270174ae2aad
80,202
def count_index(sequence): """ The index of `sequence` in a kMer profile. """ nucleotide_to_binary = { 'A': 0x00, 'a': 0x00, 'C': 0x01, 'c': 0x01, 'G': 0x02, 'g': 0x02, 'T': 0x03, 't': 0x03 } binary = 0x00 for b in sequence: binary = ((binary << 2) | n...
30821109c85aa36cf2cc7a6e2fbfe2145ecfc58f
80,203
def no_start_menu_music(on=0): """Remove a Opcao "Minhas Musicas" do Menu Iniciar DESCRIPTION Esta restricao remove a opcao "Minhas Musicas" do menu iniciar. COMPATIBILITY Windows 2000/Me/XP MODIFIED VALUES NoStartMenuMyMusic : dword : 00000000 = Desabilitado;...
3b280591822a31d7f78b6f8f76e44327db316bb1
80,204
import torch def loss_l2(pi: td.Distribution, dem: np.ndarray, max_range: float, max_safe_ratio: float) -> torch.Tensor: """ Args: pi (td.Distribution, dtype=torch.float32, BS=(B,), ES=(C,)): distribution predicted by policy. dem (np.ndarray, dtype=np.float3...
cdea257a64a1059bccde3076da66a2fb5f2d2571
80,206
def newends_OOM(adapters, ends): """Only works for small datasets like the examples""" while not all((val == adapters[-1] for val in ends)): result = [] for val in ends: if val == adapters[-1]: result.append(val) else: for n in range(1, 4):...
410a35a5107ba375fec4c9e247aa02ef34c2013f
80,207
def windowed_snp_counter(sample_snp_counts, introgression_pos_file, chromosome_length_bed_file, window_size): """This function uses a sliding window approach to count the number of SNP per window""" # Load files into dataframes for processing read_hybrid_pos_file = pd.read_csv( introgression_pos_fil...
baaed2a247ad050aae3398e4557b049218ed5cc1
80,209
def generate_graph_two(case_study, type="structure"): """ A graph with ALL the elements represented :param case_study: The case study to represent :param type: "structure", "sankey" :return: A string with the full HTML page, ready to be painted. Also, a name for the type of graph (for file name gene...
70968b6807c97f6e50f0909ce450201ca607e99a
80,210
def get_new_coins(coin_seen_dict, all_coins_recheck): """ This method checks if there are new coins listed and returns them in a list. The value of the new coins in coin_seen_dict will be set to True to make them not get detected again. """ result = [] for new_coin in all_coins_recheck: ...
96921c22f482ef41c7711445ff85734ec7e9dc4c
80,213
def transfer_value_with_the_fee(password, fee, decimal_point, to, amount, file_path, url): """ Transfer the value to the specific address with the fee. :param password: Password including alphabet character, number, and special character. If the user doesn't give password with -p, then CLI will show the pr...
c5747f2c8a5765eba64e795a061253f6b0964c88
80,214
def frames_extraction(video_path): """ This function extracts and saves the frames of a video """ video = cv2.VideoCapture(video_path) success, frame = video.read() count = 0 while success: cv2.imwrite("frame%d.jpg" % count, image) success, image = video.read() print(...
2bab068ecff292aea5ba05684e87479f8080cc22
80,215
def rz_target_s_min_stopper_factory(y0, s_min, atol=1e-6): """Stopper which returns the (squared) distance after a minimum traced length atol is subtracted from the distance to guarantee 0-crossing This should prevent early stopping by having the initial distance 0 A good estimate for s_min could be...
e4c7e32d181d9a2b1d6dc97228de50c251a0cf6e
80,216
def get_min(data, **kwargs): """ Assuming the dataset is loaded as type `np.array`, and has shape (num_samples, num_features). :param data: Provided dataset, assume each row is a data sample and each column is one feature. :type data: `np.ndarray` :param kwargs: Dictionary of differential ...
a94759b2dcaa02687d64dbd39b9b825c3a4ba5b5
80,217
import re def extract_cursor(html) -> str: """ extract token for next page :param html: :return: """ cursor = re.findall('cursor=(\d+)', html) if len(cursor) > 0: return cursor[0] else: return ""
ec610ac123d0527c17eac56c83fa792d1f8bc1ff
80,218
def valid_ssn(kt: str) -> bool: """Validate Icelandic social security number""" if not kt or len(kt) != 11 or kt[6] != "-": return False m = 11 - sum((ord(kt[i]) - 48) * KT_MAGIC[i] for i in range(9)) % 11 c = ord(kt[9]) - 48 return m == 11 if c == 0 else m == c
dd383d4ea6bc8c757714c6d4ed1b2995a3a000f1
80,219
def maxent_causal(world, terminal, trajectories, discount=0.7, theta=None): """ Maximum Causal Entropy Inverse Reinforcement Learning """ # set up features: we use one feature vector per state features = World.state_features(world) # choose our parameter initialization strategy: # initializ...
b2a84e7df8ea639103517cb5419f92d7b4582bce
80,220
def _convert_dataframe_to_spark(dataframe): """ Helper method for converting a user-provided dataframe into a spark dataframe Args: :dataframe: the input dataframe (supported types are spark rdds, spark dataframes, pandas dataframes, python 2D lists, and numpy 2D arrays) Returns: the d...
7ca0435b9251c283d2f2d25399771a8d4065a6de
80,221
def load_filters(filternamelist, **kwargs): """Given a list of filter names, this method returns a list of Filter objects. :param filternamelist: List of strings giving names of the filters. :returns filterlist: A list of filter objects. """ return [Filter(f, **kwargs) for f in...
c19eb50002ce2aa4c89f333e6e718f012bf92b19
80,223
import socket def get_local_network(private=False, subnet=100): """ Returns the IP address of the local network Defaults to the local area network. If 'private", defaults to '100' for the ROACH network. """ if private: IP = socket.gethostbyname("192.168."+str(subnet)+".1") else: IP = socket....
c007005bcf2e377b0c1789b5eeb43fd43c4e46e4
80,224
def send_feedback_email_task(message): """sends an email when feedback form is filled successfully""" logger.info("Sent feedback email") #return send_feedback_email(email, message) message="HI It is our DBMS Project" print("Received : ",message) return message
2b835db80b134e6256a9e16c4bb28dc440bf4fef
80,225
def get_compete_info(oc_user,params): """获取用户的竞技首页 """ data = {} user_compete_obj = UserCompete.get_instance(oc_user.uid) data["my_rank"] = user_compete_obj.my_rank data["my_reward"] = user_compete_obj.get_my_reward data["compete_num"] = user_compete_obj.compete_info.get("compete_num",0) ...
6d4246bc34abdb25c69ab6a333ec4acfe5b921ed
80,226
import random def newid(): """ Generate a new random object ID. """ return ''.join([random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") for i in range(16)])
5d59b77e33712948ac30e2bbe5514dea992ab606
80,227
import calendar from datetime import datetime def apply_month_delta(date, month_delta=1, add_overlap=False): """ Add or subtract months from the date. By default if the new month has less days then the day of the date it chooses the last day in the new month. For example a date in the March 31st ...
213d24c061dbf57d19dd99c3c5e2e92d1bde37d4
80,228
def saturation(rgb: np.ndarray, alpha: float) -> np.ndarray: """彩度の変更。alphaの例:np.random.uniform(0.5, 1.5)""" rgb = rgb.astype(np.float32) gs = (rgb * np.array([[[0.299, 0.587, 0.114]]], dtype=np.float32)).sum(axis=-1) return alpha * rgb + (1 - alpha) * np.expand_dims(gs, axis=-1)
daff88f2ca1ad6bc600f2357eedf15f52c0d4438
80,229
def calculate_aniso_parameters(K,n_pos=6): """ calculate anisotropy parameters from n_pos positions plus optional baseline measurements ADD DOC STUFF HERE """ aniso_parameters = {} Matrices=get_matrix(n_pos) tmpH=Matrices['tmpH'] B = Matrices['B'] S_bs = np.dot(B, K)...
4a35fd4b26a2f8b0dd064b6a09fed47730451653
80,230
def _bytes_to_atom(name: bytes, encoding: str, options: dict): """ Recognize familiar atom values. """ if name == b'true': return True if name == b'false': return False if name == b'undefined': return None if options.get("atoms_as_strings", False): return name.decode...
b5a92d4ff3ec0f4a7ea59b496098f25f29a74036
80,231
def parseskydef(skydef_in): #---------------------------------------------------------------------- """ Parse a string that represents a sky definition. See documentation at function skyparser() A tuple with values is returned. If the sky system was empty as in {}, then return None """ #--------------------------...
726081e32fe56b23fa03e772bd1a25a58717ddd1
80,232
def bytes_ljust(x: bytes, width: int, fill: bytes) -> bytes: """Given a bytes object, a line width, and a fill byte, left-justifies the bytes object within the line. Compiling bytes.ljust compiles this function. This function is only intended to be executed in this compiled form. Checking the fill leng...
6059459dfd466720c38fa232424e9be932f288cd
80,234
import re def ValidateEmail(email, column_name=None, problems=None): """ checks the basic validity of email: - an empty email is considered valid and no error or warning is issued. - should start with any string not including @ - then should match a single @ - then matches any string not includi...
1d3c67496ecf206e5bcb29535bc4d0ab04a2e857
80,235
import random def add_anp_to_sentence(sentence_tokenized, noun_to_adj, rule='random_adjective'): """ Pick a noun of the sentence at that is a key of the noun_to_adj dictionary at random. Given the rule pick the corresponding adjective from the noun_to_adj and add it before the noun. Return the new sentence. ...
3beeb16d7b9ebb564a41f23a472bda2267b45914
80,236
def _get_gcs_client() -> storage.Client: """ Can potentially fail if credentials are available via file or environment variables. """ return storage.Client()
ce22abb887f99b5ea2fc9cea16c0ce45ca01734a
80,237
def make_text_objs(text, font, color): """ Function creates a text. text -> string; content of text font -> Font object; face of font color -> tuple of color (red, green blue); colour of text returns the surface object, rectangle object """ surf = font.render(text, True, color) ...
d5c0a41982f6d6979063dcb24aafc186ff132f1c
80,238
def validate_config(session, config, id_name, id_value, patch=True): """Validates config. Validates the given config value according to the config metadata of the asscoiated os_id or adapter_id. Returns a tuple (status, message). """ if id_name not in MAPPER.keys(): return (False, "Inva...
e1313cab1d0f168a8d4eb0b04ad7f5b426f87d9a
80,239
import six def fetch_globals_functions(): """Fetch the reference count for the global tags (function) in the database. Returns the tuple `(address, tags)` where the `address` and `tags` fields are both dictionaries containing the reference count for the addresses and tag names. """ addr, tags...
c75ec75062a042af3483e6ba8529b9c631e19ce3
80,240
def read_rating_curve(rating_curve_file): """ Reads the dam rating curve XML file, and returns a dictionary with pairs of a) location and b) a string (formatted for use with SWMM) """ try: tree = ET.parse(rating_curve_file) root = tree.getroot() curves = root.findall("pi:ratingCu...
5da95236652cc90fc6ae560921ea1da11e6678cb
80,241
def numActiveOperations(): """ Returns the number of active operations. """ _lock.acquire() try: return _numActiveOperations finally: _lock.release()
05b1fe5bf586601e890f16a8cc370ec7f3b91f61
80,242
def get_collector(objs): """ Create a collector for the given objects. The collector contains all the objects related to the objects given as input that would need to be modified if we deleted the input objects: - if they need to be deleted by cascade they are in `collector.data` (ordered dictionary...
0fb917f673fff314afdf8687a28065d20791d64d
80,243
def avatar( request: HttpRequest, user_profile: UserProfile, email_or_id: str, medium: bool = False ) -> HttpResponse: """Accepts an email address or user ID and returns the avatar""" is_email = False try: int(email_or_id) except ValueError: is_email = True try: realm = ...
f652ede7fbac0e1e408fd2a41672350b56cdfad2
80,245
def get_string(element): """Helper for safely pulling string from XML""" return None if element == None else element.string
ff2dbec31f9c3c91c8cf6ca08a36313839265bbd
80,246
def __iconcat__(self,*others) : """concat bits or bitstrings to self""" if self in others : # avoid mutating args before using them c = type(self)(self); # copy others = tuple(c if o is self else o for o in others); return _iconcat(self,*others);
2f3abb6fe5690dd90997471940da7e6cb439f60b
80,247
def dt_to_us_from_epoch(dt): """Convert datetime.datetime object to microseconds since the epoch. :param dt: datetime.datetime object. :returns: microseconds since the epoch as a string. """ return '{:.0f}'.format(dt.timestamp() * 1e6)
60d4befd19666ad4799bf45c00a083b3443e9c82
80,248
def largest_factor(n): """ *** write a proper docstring here *** >>> largest_factor(15) # factors are 1, 3, 5 5 >>> largest_factor(13) # factor is 1 since 13 is prime 1 *** add two more testcases here *** """ # *** YOUR CODE HERE *** return n
7c08ac97cfb5b39be35ac241279039c8485f51d5
80,249
def generate_and_print(): """ Generates a seed for a private key, and prints the mnemonic to the terminal. """ mnemonic = generate_mnemonic() print("Generating private key. Mnemonic (24 secret words):") print(mnemonic) print("Note that this key has not been added to the keychain. Run chia k...
247a93ab8152ba7e173db9024bd84b4fe641c8a1
80,250
def subparser_builder(subparser, subparser_id, description, options_func, exe_func): """ Util to add subparser options :param subparser: :param subparser_id: :param description: :param options_func: Function that will add args and options to Parser instance F(subparser) -> None :param exe_f...
68aa0fab3eb31125deef6f2c7dbc1b666e304d37
80,251
import socket def get_host_name(): """ Determine host-name for use in host-name-based addressing (e.g. XML-RPC URIs): - if ROS_IP/ROS_HOSTNAME is set, use that address - if the hostname returns a non-localhost value, use that - use whatever L{get_local_address()} returns """ hostname = ...
f5c04a80a0c698238dce8845fce46fb51fbe3155
80,252
def rxn_objs_from_zmatrix(rct_zmas, prd_zmas, indexing='geo'): """ Generate rxn obj """ rct_geos = list(map(automol.zmat.geometry, rct_zmas)) prd_geos = list(map(automol.zmat.geometry, prd_zmas)) return rxn_objs_from_geometry( rct_geos, prd_geos, indexing=indexing)
9e1cad7844840f23a313bdc8ea925288e14aec6b
80,253
def hazel_workspace(package_name): """Convert a package name to a valid and unambiguous workspace name. Makes the name unambiguous to case-insensitive file-systems and converts the package name into a valid Bazel workspace name. Args: package_name: string: Package name. Returns: string: Workspace n...
099262aab0c54feb2238f89272d0d85a8c726a37
80,254
from typing import List def reverse_points(points: List[int]) -> List[int]: """ e.g.) [4, 5, 4, 9, 8, 9, 8, 5, 4, 5] => [4, 5, 8, 5, 8, 9, 4, 9, 4, 5] """ reversed_points = [] for index, _ in enumerate(points): if index % 2 == 0: reversed_points.insert( 0, p...
b4b30c80c30cf54821b26e9b4ee3fc459de2ff69
80,255
import contextlib def eth_getBlockByNumber(block_number: int): """ See EthereumAPI#block_by_number. """ with contextlib.closing(EthereumAPI()) as api: return api.get_block_by_number(block_number)
1c421a0f708140b063e2f59638aa44c0f7652590
80,256
def average_gradient(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients....
366105ea80b35482f8546dd8d13b770dd34196ea
80,257
def form_errors(form): """ Displays errors on a form using the form_errors template""" return {"form":form}
762f8bd40d689e9846f970c47ef2d154c6503ace
80,258
def train_step(learning_rate_fn, optimizer, ema, batch, dropout_rng): """Perform a single training step.""" def loss_fn(params): """loss function used for training.""" pcnn_out = model(dropout_p=FLAGS.dropout_rate).apply( {'params': params}, batch['image'], rngs={'dropout': dropout_rng}) return...
f657ffae499e77dff75f758fdd9e40a25c8c9c74
80,259
async def json_request_validation_middleware(request, handler): """Middleware that converts json decoding and marshmallow validation errors into 400 responses w/ json bodies. """ try: return await handler(request) except errors.DataValidationError as ex: raise JsonHttpBadRequest( ...
1c7bfc96b9d3fd190da51472c99a20b26140e78d
80,260
def get_executor_shell_cmd(name, command, return_output=True, ctx=None): """ Return an executor(context) method that executes a shell command :param command: command to be given to default system shell :return: executor method """ return lambda match_result, child_results: execute_shell_cmd( ...
ebe046659ad0f3956619c097190845e220edbe21
80,261
def theoretical_yield(actual_yield, mole_ratio_top, mole_ratio_bottom): """Finds theoretical_yield\n actual_yield:\n\tThe yield given in the equation if it is grams convert it to moles before using it \n mole_ratio_top:\n\tFrom the balanced equation given, the number of moles of the wanted element\n mol...
a601732b073ad9c7adff63fb52739b819425fe7e
80,262
def move_from_san(san): """ Get move tuple from san """ from_square = index_of_square(san[0:2]) to_square = index_of_square(san[2:4]) if len(san) == 5: promotion = promotion_from_char(san[4]) else: promotion = None return (from_square, to_square, promotion)
d1d3040e3fefca0043f5c20b523a517985e042ce
80,263
def datastore_discover(agent, msg): """ Discover all pyVmomi.vim.Datastore managed objects Example client message would be: { "method": "datastore.discover", "hostname": "vc01.example.org", } Example client message which also requests additional propertie...
387982b216e3ce53ef64e2beea532bca160fee8c
80,265
from datetime import datetime def parse_rmc(gprmc): """Parsing NMEA-0183 $RMC record into more human set of values. Recommended Minimum Specific GPS/TRANSIT Data: parser library: https://github.com/Knio/pynmea2 """ valuez = pynmea2.parse(gprmc) lat = valuez.latitude lon = valuez.longitud...
6e166e00e65c4d5deae7839de335bed9395810ca
80,266
def add_addon_columns(df): """ Constructs additional indicator columns decribing the add-on/theme present in a given record. The columns are is_self_install is_shield_addon is_foreign_install is_system is_web_extension Which maps True -> 1 and False -> 0 :param df: SparkDF, ex...
81df98510d0f7c556eb17a27172f0abef5e18a62
80,267
def ldap_oldcsv_parser(entity, overwrite, verbosity, validate=False): """ Parses LDAP CSV dict and saves information to SP-object entity: LDAP CSV dict for one SP overwrite: replace/add data for existing SP verbosity: verbosity level for errors validate: automatically validate added metadata ...
e397cc22bfba3056aefecd9bb52025752760c2d2
80,268
def solve(lamb, n, beta, delta): """Find the solution to M x = ((n + 1) * (1 - beta * lamb), 0, ..., 0)^T, where M [i, j] = \\tilde f_j(\\hat z_i) for i, j = 0, ..., n, \\tilde f_j(z) = (z^j + ... + z^n), and \\hat z_0 = 1, \\hat z_1, ..., \\hat z_n are the zeroes of z^(n+1) - (lamb * z + 1 - lam...
e7308659dace089ad4db05f94dcc7d373ead599d
80,269
def filter_samples(X, method='density', return_indices=False, **kwargs): """ Filter core subset of samples. Parameters ---------- method: str, (allowed = ['density', 'random']) * how to filter the samples """ # Get indices based on method indices = np.arange(len(X)) if 'den...
cdd02ced595c886fbd6a3a36311c56d42dad93b9
80,270
def should_respond(data, username, only_respond_to_mentions): """ Takes the API response data from a single message. Returns true if the chat bot should respond. """ if data: unread = data.get('unread', False) if only_respond_to_mentions: if unread and _contains_mention(...
92224a902c104387ecae8d8656dd99228d0852d5
80,271
import unittest def tests(): """Used by test_suite below.""" return unittest.TestLoader().discover( "vaeseq/", "*_test.py", top_level_dir=".")
fb3680800ade9e55f596426eca7455d62f8903d2
80,272
import array def _mass_properties(model, elements, masses, reference_point, is_cg): """helper method for ``mass_properties``""" mass = 0. cg = array([0., 0., 0.]) I = array([0., 0., 0., 0., 0., 0., ]) no_mass = NO_MASS for pack in [elements, masses]: for element in pack: tr...
702221151f05217a2d6ed8a31e5ff20fb3aa9ae1
80,274
def as_component_created_listener( callback: EventCallback[ComponentCreatedEvent] ) -> ListenerSetup[ComponentCreatedEvent]: """Listener setup for ComponentCreatedEvent""" return (EVENT_ID_COMPONENT_CREATED, callback,)
c0b36ee232ce79bb69a3f54a559470edc986568a
80,275
def index(): """Returns the dashboard interface.""" return render_template('dashboard.html')
45adfdfc7e748829534fd4bfb6e9e7ccc79adfb9
80,276
async def get_task_children_lastruntime(name): """ Retrieve all the child tasks for a specified task but also include the status and runtime of the most recently run instance. """ child_tree = TASKS.get_child_tree(name) tasks_lastruntime = await get_tasks_last_run_time() data = {} for...
3671bd5858e02fa484c85bdd57754877f82d789c
80,277
def testFindNonGlobalDimensionSuggestionResult(client, mocker): """Method to test non global dimension index""" ESIndexingUtils.deleteAllIndex() connection = mixer.blend("dataset.connection") testDataset = mixer.blend( "dataset.dataset", name="orders", id=1, dimensions='...
9db9416e2551d98871ad444c66c1adfd33e7ff05
80,278
def rK_func(a,b): #Eq(22) """ Define Return as Function of Productivity and Previous Capital (Cobb-Douglas) """ return alpha*a*pow(b,alpha-1)
4fc4261c3847ab8e4e05a12ca2c5bf2662e07112
80,279
import pickle def load(to_file=""): """function load Args: to_file: Returns: """ dd = pickle.load(open(to_file, mode="rb")) return dd
b4351183e94b2ce2f40510e1af768f6e0751a3c0
80,280
from typing import Union import base64 def file_to_base64(**kwargs: Union[str, bytes]) -> str: """ 파일을 byte string을 base64 encoding한 string data로 변환. \n file_path | file_data 중 한개 이상 필수 파라미터 필요. :param kwargs: file_path | file_data file_path: str file_data: bytes ...
5b1e55307d7b951961d0b9d43f32968380f3daa7
80,281
from bs4 import BeautifulSoup def get_issue_metadata(issue_soup: BeautifulSoup, name: str) -> str: """ Return the value of the key """ if len(issue_soup.find_all("dd", id=name)) > 0: if (name != "issue_indicia_publisher") & (name != "issue_brand"): return issue_soup.find_all("dd", ...
2643d36f9d79389048bc9ef6a3bd5de9c900d88f
80,282
def document_new_view(): """ New document view. """ return render_template('admin/documents/new.html', path='/admin/documents/new')
dc2dca992d4a4fadf1c7d3f67e91ef759085d8f9
80,283
import uuid def high_low_2_uuid(uuid_high, uuid_low): """Combine high and low bits of a split UUID. :param uuid_high: The high 64 bits of the UUID. :type uuid_high: int :param uuid_low: The low 64 bits of the UUID. :type uuid_low: int :return: The UUID. :rtype: :py:class:`uuid.UUID` ...
b0c7c53bc4b61085574bcda1d5a8c616f0db8c92
80,284
import functools def get_train_op(loss, learning_rate=0.001, lr_decay_steps=10000, lr_decay_rate=0.98, gradient_clip_norm=3.0, use_tpu=True, variables=None): """Get training operation with gradient clipping and lea...
7a898c2ee90851c764958db6d96e226cdf37122a
80,286
from datetime import datetime def is_naive(the_datetime): """Tests if a datetime.datetime object is 'naive', i.e., has no associated timezone information. See also is_aware. Parameters: the_datetime (datetime.datetime) : The datetime to be tested. Returns: bool : False if the_dateti...
8e5f9f457315ccf6648b6c508ad5283f1c336c92
80,287