content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import requests def username(UID: str) -> str: """ Get a users username from their user ID. >>> username("zx7gd1yx") '1' >>> username("7j477kvj") 'AnInternetTroll' >>> username("Sesame Street") Traceback (most recent call last): ... utils.UserError: User with uid 'Sesame Street' not found. """ R: dic...
c2d66af182a970783ef6e2236c1db3e5a3f80b50
11,076
import logging def handle_exceptions(func): """Exception handler helper function.""" logging.basicConfig(level = logging.INFO) def wrapper_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logging.error(f'{func.__name__} raised an error...
2d5c428e65cfb823d1afbf2d2c77f98b8722d685
11,077
def apply_hamming_window(image): """Cross correlate after applying hamming window to compensate side effects""" window_h = np.hamming(image.shape[0]) window_v = np.hamming(image.shape[1]) image = np.multiply(image.T, window_h).T return np.multiply(image, window_v)
f319506e9a51350664683ede7411e677bbf96ab3
11,078
from typing import Tuple from functools import reduce def calc_ewald_sum(dielectric_tensor: np.ndarray, real_lattice_set: np.ndarray, reciprocal_lattice_set: np.ndarray, mod_ewald_param: float, root_det_epsilon: float, volu...
5be08f833c8e44a4afeab48af0f5160278fbf88a
11,079
import time def proximal_descent( x0, grad, prox, step_size, momentum='fista', restarting=None, max_iter=100, early_stopping=True, eps=np.finfo(np.float64).eps, obj=None, benchmark=False): """ Proximal descent algorithm. Parameters ---------- x0 : array, shape (n_l...
e6a05c2ef4295b67e3bc3ac2b1608b16d43bc09e
11,080
from stable_baselines_custom.common.atari_wrappers import wrap_deepmind def wrap_atari_dqn(env): """ wrap the environment in atari wrappers for DQN :param env: (Gym Environment) the environment :return: (Gym Environment) the wrapped environment """ return wrap_deepmind(env, frame_stack=True, ...
6c47492fe412b5620f22db17a45aa42968ed9a62
11,082
def get_Theta_CR_i_d_t(pv_setup, Theta_A_d_t, I_s_i_d_t): """加重平均太陽電池モジュール温度 (6) Args: pv_setup(str): 太陽電池アレイ設置方式 Theta_A_d_t(ndarray): 日付dの時刻tにおける外気温度(℃) I_s_i_d_t(ndarray): 日付dの時刻tにおける太陽電池アレイiの設置面の単位面積当たりの日射量(W/m2) Returns: ndarray: 日付dの時刻tにおける太陽電池アレイiの加重平均太陽電池モジュール温度 """ ...
6c96d9c4692de19909feccf647fd39126358b29c
11,083
from typing import Set def or_equality(input_1: Variable, input_2: Variable, output: Variable) -> Set[Clause]: """ Encode an OR-Gate into a CNF. :param input_1: variable representing the first input of the OR-Gate :param input_2: variable representing the second input of the OR-Gate :param output...
f101b1d7ae3d70e7849133562cd274275f8419a8
11,084
import math def keyPosition_to_keyIndex(key_position: int, key: int) -> int: """ キーポジションからどのキーのノーツなのかを変換します 引数 ---- key_position : int -> キーポジション key : int -> 全体のキー数、4Kなら4と入力 戻り値 ------ int -> キーインデックス、指定したキーの0~キー-1の間の数 """ return math.floor(key_position * key / 512)
e6edcc1711a283336da046e1f8f174cc7ff87760
11,085
from masonite.routes import Patch def patch(url, controller): """Shortcut for Patch HTTP class. Arguments: url {string} -- The url you want to use for the route controller {string|object} -- This can be a string controller or a normal object controller Returns: masonite.routes.Pa...
c267ca8c2e2c55369584a94cd07aaf26b0b7ae4b
11,087
def get_user(message: discord.Message, username: str): """ Get member by discord username or osu username. """ member = utils.find_member(guild=message.guild, name=username) if not member: for key, value in osu_tracking.items(): if value["new"]["username"].lower() == username.lower(): ...
323ac71e24e4da516263df3a4683ed5fd87138ce
11,088
import colorsys def resaturate_color(color, amount=0.5): """ Saturates the given color by setting saturation to the given amount. Input can be matplotlib color string, hex string, or RGB tuple. """ if not isinstance(color, np.ndarray) and color in matplotlib.colors.cnames: color = matplot...
2bd1b9b4d9e1d11390efc79f56a89bf7555cbe71
11,089
def create_reach_segment(upstream_point, downstream_point, polyline, identifier="HA", junctionID=0, isEnd=False): """Returns a polyline based on two bounding vertices found on the line. """ part = polyline.getPart (0) total_length = polyline.length lineArray = arcpy.Array () ...
c378fb05c1eda5cde35d5caf60a9d732578ae6d8
11,090
def sample_recipe(user, **params): """ Helper function for creating recipes """ """ for not writing every single time this fields """ defaults = { 'title': 'Sample recipe', 'time_minutes': 10, 'price': 5.00 } """ Override any field of the defaults dictionary. Updati...
11fe56c88cc0c641b1c04b279b2346615b2257c9
11,091
def _unary_geo(op, left, *args, **kwargs): # type: (str, np.array[geoms]) -> np.array[geoms] """Unary operation that returns new geometries""" # ensure 1D output, see note above data = np.empty(len(left), dtype=object) data[:] = [getattr(geom, op, None) for geom in left] return data
d302bdb41c74f7b127df4ccd24dd6bc56c694a56
11,092
def map_func(h, configs, args): """Polygons command line in parallel. """ if args.verbose: cmd = "python {} -i {}/threshold{}.tif -o {}/threshold{}.shp -v".format( configs["path"]["polygons"], configs["path"]["output"], h, configs["path"]["output"], h ) print cmd else: cmd = "python {} -i {}/...
4ff4e961b2d0eb9a19b277a0b8e2ef165aa43819
11,093
def check_health(request: HttpRequest) -> bool: """Check app health.""" return True
20d572edd68e1518e51cbdbe331c17798bc850fe
11,095
def return_galo_tarsilo(message): """Middle function for returning "gaucho" vídeo. Parameters ---------- message : telebot.types.Message The message object. Returns ------- msg : str User/Chat alert list addition/removal. """ return 'https://www.youtube.com/watch?v...
58307b763d139dc38220b9a93af15644ccd32959
11,096
def preimage_func(f, x): """Pre-image a funcation at a set of input points. Parameters ---------- f : typing.Callable The function we would like to pre-image. The output type must be hashable. x : typing.Iterable Input points we would like to evaluate `f`. `x` must be of a type acce...
6ca0496aff52cff1ce07e327f845df4735e3266a
11,097
import warnings def load_tree(tree,fmt=None): """ Load a tree into an ete3 tree data structure. tree: some sort of tree. can be an ete3.Tree (returns self), a dendropy Tree (converts to newick and drops root), a newick file or a newick string. fmt: format for reading tree from new...
efc727fee6f12b4a8bc0e8c2b2319be2a820df13
11,100
from typing import Dict def load_extract(context, extract: Dict) -> str: """ Upload extract to Google Cloud Storage. Return GCS file path of uploaded file. """ return context.resources.data_lake.upload_df( folder_name="nwea_map", file_name=extract["filename"], df=extract["v...
c9d5fedf6f2adcb871abf4d9cead057b0627267a
11,101
def _make_default_colormap(): """Return the default colormap, with custom first colors.""" colormap = np.array(cc.glasbey_bw_minc_20_minl_30) # Reorder first colors. colormap[[0, 1, 2, 3, 4, 5]] = colormap[[3, 0, 4, 5, 2, 1]] # Replace first two colors. colormap[0] = [0.03137, 0.5725, 0.9882] ...
ca6275fc60efe198be5a89662d791f6c47e45b24
11,102
def poly_to_box(poly): """Convert a polygon into an array of tight bounding box.""" box = np.zeros(4, dtype=np.float32) box[0] = min(poly[:, 0]) box[2] = max(poly[:, 0]) box[1] = min(poly[:, 1]) box[3] = max(poly[:, 1]) return box
4fb8cea86494c34832f43dbf7f942a214dc2e010
11,103
import torch def default_collate(batch): """Puts each data field into a tensor with outer dimension batch size""" error_msg = "batch must contain tensors, numbers, dicts or lists; found {}" elem_type = type(batch[0]) if isinstance(batch[0], torch.Tensor): return torch.stack(batch, 0) elif...
576366ac5e57a84a015ffa3e5e80e8d4b62ac329
11,104
def updatestatus(requestdata, authinfo, acldata, supportchan, session): """Update the /Status page of a user.""" if requestdata[2] in acldata['wikis']: wikiurl = str('https://' + acldata['wikis'][requestdata[2]]['url'] + '/w/api.php') sulgroup = acldata['wikis'][requestdata[2]]['sulgroup'] e...
f305f1c4ceb6b4cfd949a1005a961b710e81740f
11,105
def sortByTimeStamps(paths): """Sorts the given list of file paths by their time-stamp :paths: The file paths to sort by time-stamp :returns: A sorted list of file paths """ sortedPaths = [] timeStamps = [] # Extract the YYYYMMDD & HHMMSS timestamps from the file paths for p in paths:...
01d60e0f3d793ca17f04462911406d03a6c3ddf0
11,106
def get_xml_nk_bands(xml_tree): """ Function to specifically get kpoint (cartesian) coordinates and corresponding eigenvalues (in Hartree) """ k_points_car = [] k_eigenvalues = [] k_occupations = [] for ks_energies in xml_tree.iter(tag='ks_energies'): k_points_car.append( get_x...
e510995ee468552d395c179aa8713f159b1ad0e1
11,107
def enumerate(server, directory_list, filenames): """ Enumerate directories and files on the web server. """ print('\n[*] Enumerating resources.') to_search = [server] directories = [] resources = [] print('[*] Recursively searching for directories.') while len(to_search) != 0: ...
e9b2eb94b71b48dcc032448369a413cc4c1790ba
11,108
def deep_equals(x, y): """Test two objects for equality in value. Correct if x/y are one of the following valid types: types compatible with != comparison pd.Series, pd.DataFrame, np.ndarray lists, tuples, or dicts of a valid type (recursive) Important note: this function w...
27f5dc79e5c3b9e8a08a4bbd0db847995f0fa9ef
11,109
import re def _is_valid_img_uri(uri: str) -> bool: """ Returns true if a string is a valid uri that can be saved in the database. """ regex = "data:image/jpeg;base64*." return not uri or re.match(regex, uri)
0836bfa447b42fb7ed24fc897de8fb40c6e593b2
11,113
def update_config(a, b, mode="default"): """Update the configuration a with b.""" if not b: return a from_version = get_config_version(a) to_version = get_config_version(b) if from_version == 1 and to_version == 2: # When updating the configuration to a newer version, we clear all u...
464adc3a4daeedb246d911caab5477ff4d55841e
11,114
def create_app(config_name='DevelopmentConfig'): """Create the Flask application from a given config object type. Args: config_name (string): Config instance name. Returns: Flask Application with config instance scope. """ app = Flask(__name__) {{cookiecutter.package_name | up...
6022c976ffa2bf6afa692bb96c5c53bfed4a7d32
11,116
def label_accuracy_score(hist): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc """ with np.errstate(divide='ignore', invalid='ignore'): iu = np.diag(hist) / ( hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist) ...
5e129604d476f17e0cfd7a30f785775266763432
11,117
def get_page_title(title: str): """ Возвращает заголовок, отображаемый на вкладках """ return f'{title} | NeuraHS'
3df2de16325cf0c4c849e7d09111ea87e36c309a
11,118
def make_pointer_union_printer(val): """Factory for an llvm::PointerUnion printer.""" pointer, value = get_pointer_int_pair(val['Val']) if not pointer or not value: return None pointer_type = val.type.template_argument(int(value)) string = 'llvm::PointerUnion containing %s' % pointer_type return make_pr...
40d12a45a05fb49dd32b1a450b7dff23ab0ece7c
11,119
def get_paramvals_percentile(table, percentile, chi2_arr): """ Isolates 68th percentile lowest chi^2 values and takes random 1000 sample Parameters ---------- table: pandas dataframe Mcmc chain dataframe pctl: int Percentile to use chi2_arr: array Array of chi^2 va...
1d83c54b61446aecf0a7fcbf4d8ae49e96a25b3f
11,120
def get_text_from_span(s, (start, end)): """ Return the text from a given indices of text (list of words) """ return " ".join(s[start: end])
df58cf8056039b183dc421c94baa22176fe23e84
11,121
import time import struct def __timestamp(): """Generate timestamp data for pyc header.""" today = time.time() ret = struct.pack(b'=L', int(today)) return ret
477c8473026c706785b4091bbbf647b86eaa560f
11,122
def reverse_index(alist, value): """Finding the index of last occurence of an element""" return len(alist) - alist[-1::-1].index(value) -1
21fc4e17a91000085123ea4be42c72cb27a3482c
11,123
def generate_twist(loops, non_interacting=False): """Generate initial configuration to start braid moves where the active end has crossed outside the loops and they have an initial twist. Format: ' │ │ │┃' '┏━━━━━┛' '┃│ │ │ ' '┗━┓│ │ ' ' │┃│ │ ' '┏│┛│...
fdeb58b49d2e559c4d0ccfc24e439057683f7e96
11,124
def IsShuttingDown(_shutting_down=_shutting_down): """ Whether the interpreter is currently shutting down. For use in finalizers, __del__ methods, and similar; it is advised to early bind this function rather than look it up when calling it, since at shutdown module globals may be cleared. """ ...
6cbc5d3388ee8eb0cabbb740fc5e0b8f2ac4714a
11,126
def ellipse_center(a): """ Parameters ---------- a : fitted_ellipse_obj """ b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0] num = b*b-a*c x0=(c*d-b*f)/num y0=(a*f-b*d)/num return np.array([x0,y0])
66487a641c35d2c1c1c8a8c7c0bb129eda55f4c4
11,127
def _to_average_temp(name, temperature_map): """ Converts the list of temperatures associated to a label to a list of average temperatures. If the sensor does not exist, it will return _default_temperature. If the high or critical temperature thresholds are invalid, it will use the values from _default_...
88c3b5d0bdd64f782a26a7dc11d44dc39e6efc82
11,128
def segments_decode(aseg): """ Decode segments. Parameters ---------- aseg : numpy.ndarra of uint32 Returns ------- segments : list of list of int """ max = 2 ** 32 - 1 segments = [] l = [] for x in list(aseg): if x == max: segments.append(l) ...
d5edf85ae489b62c8820c3616a75a9ca305f06ec
11,129
def cvGetReal3D(*args): """cvGetReal3D(CvArr arr, int idx0, int idx1, int idx2) -> double""" return _cv.cvGetReal3D(*args)
4130a4f9571bdea1c9e54b5fcf7d1d0f5c3ce083
11,130
def get_wf_double_FF_opt( molecule, pcm_dielectric, linked=False, qchem_input_params=None, name="douple_FF_opt", db_file=">>db_file<<", **kwargs, ): """ Firework 1 : write QChem input for an FF optimization, run FF_opt QCJob, parse directory and inse...
d21b04035d41beb3a24e9cbba45c420bd8d9b727
11,131
def get_element_action_names(element): """Get a list of all the actions the specified accessibility object can perform. Args: element: The AXUIElementRef representing the accessibility object Returns: an array of actions the accessibility object can perform (empty if the accessibility objec...
f906f9565eb72b060d9e4c69ab052dc6001f192a
11,133
import re def ParseFile(fname): """Parse a micrcode.dat file and return the component parts Args: fname: Filename to parse Returns: 3-Tuple: date: String containing date from the file's header license_text: List of text lines for the license file ...
2774157dd256f11268a7ea4ee3d941e7aea1ca4f
11,134
import numpy def cal_q_vel(guidance_v): """ 暂时使用默认参考速度进行优化,等调试成熟再使用粗糙速度来优化 :return: """ q_vel = numpy.zeros((1, n_t + 1)) if flag_obs == 0: q_vel[0][0] = -ref_v q_vel[0][n_t] = ref_v if flag_obs == 1: for i in range(n_t + 1): if i < 1: q_vel[0][i] = -guidance_v[0][i] elif i >= n_t: q_vel...
b7551e7b911c5e0fd27a1e90f00c1e1a3a60f53f
11,135
def tf_decode( ref_pts, ref_theta, bin_x, res_x_norm, bin_z, res_z_norm, bin_theta, res_theta_norm, res_y, res_size_norm, mean_sizes, Ss, DELTAs, R, DELTA_THETA, ): """Turns bin-based box3d format into an box_3d Input: ref_pts: (B,p,3) [x,y,z]...
720252aaad2b8d380d30d871e97d47b2c9309a68
11,136
def _histogram_discretize(target, num_bins=gin.REQUIRED): """Discretization based on histograms.""" discretized = np.zeros_like(target) for i in range(target.shape[0]): discretized[i, :] = np.digitize(target[i, :], np.histogram( target[i, :], num_bins)[1][:-1]) return discretized
14108b9208dca586f7fd39dac3a5a17f1e5a2928
11,137
def apply_acl(instance, content): """Apply ACLs.""" any_acl_applied = False if not isinstance(instance, roleable.Roleable): return any_acl_applied instance_acl_dict = {(l.ac_role_id, p.id): l for p, l in instance.access_control_list} person_ids = set() for role_id, data in content...
134f4ae98018626712c2f918ce5b501129169a30
11,138
import json def serialize(results): """Serialize a ``QueryDict`` into json.""" serialized = {} for result in results: serialized.update(result.to_dict()) return json.dumps(serialized, indent=4)
1ce996e1172344ba72ccbb9487b51b0efc30fa5c
11,139
def allowed_once (cave, visited): """Only allows small caves to be visited once. Returns False if `cave` is small and already in `visited`. """ return big(cave) or (small(cave) and cave not in visited)
f3619c1d230de50fab539103084457413f30a74e
11,140
from datetime import datetime import json def _serialize_examstruct(exam): """ Serialize the exam structure for, eg. cache. The dates, especially, need work before JSON """ assert isinstance(exam, dict) date_fmt = '%Y-%m-%d %H:%M:%S' assert isinstance(exam['start'], datetime.datetime) ...
3c553986bfd6b565bbdc34218ca01d984d3aab69
11,141
def _analysis_test_impl(ctx): """Implementation function for analysis_test. """ _ignore = [ctx] return [AnalysisTestResultInfo( success = True, message = "All targets succeeded analysis", )]
5f006c817581b771bf3d1f5b3cc7861cd98e8958
11,142
import warnings def CD_Joint(CD_J_AS = None, Ypred = None, beta = None, zeta = None, active_set = None, lam = None, P = None, P_interaction = None, Y = None, B = None, B_interaction = None...
780bbd6a44dcfacf55a22390a6f7ee8c98e2d2f0
11,144
from typing import Tuple def testAllCallbacksSmokeTest( args_count: int, type_checker: TypeCheckerFixture ) -> None: """ Parametrized test to do basic checking over all Callbacks (except Callback0). We generate functions with too much arguments, too few, and correct number, and check that the err...
8459b040f2c7dc145a6a41ddebd4edb24873d704
11,145
def transform_unnamed_cols_range(df: pd.DataFrame, columns_range: range, new_column_name_prefix: str, inplace=False) -> object: """ This function transforms a range of columns based assuming the presence of following schema in dataframe: |base_column_name|Unnamed_n|Unnamed_...
c54394531cec3aeef6e1717d3db0be17852ade9b
11,146
def shingles(tokens, n): """ Return n-sized shingles from a list of tokens. >>> assert list(shingles([1, 2, 3, 4], 2)) == [(1, 2), (2, 3), (3, 4)] """ return zip(*[tokens[i:-n + i + 1 or None] for i in range(n)])
93e8f3828bf4b49397e09cb46565199dcd7a68be
11,147
import json def load_json(filename): """Load JSON file as dict.""" with open(join(dirname(__file__), filename), "rb") as fp: return json.load(fp)
3ce3a92b4a11a005709ea3fab003d73133627183
11,148
def getLayerList(layer_list, criterionFn): """Returns a list of all of the layers in the stack that match the given criterion function, including substacks.""" matching_layer = [] for layer in layer_list: if criterionFn(layer): matching_layer.append(layer) if hasattr(layer, 'laye...
5e09065b350f1305a2fcd45379751fac6552031e
11,149
def getBiLinearMap(edge0, edge1, edge2, edge3): """Get the UV coordinates on a square defined from spacing on the edges""" if len(edge0) != len(edge1): raise ValueError("getBiLinearMap: The len of edge0 and edge1 are not the same") if len(edge2) != len(edge3): raise ValueError("getBiLinearM...
a75626a846c18418db8dbb98afdb25ab0c903969
11,150
def _parse_orientation(response: HtmlResponse): """Parse Orientation. Returns None if not available or is unknown. """ value = response.css('th:contains("Ausrichtung") + td ::text').get() if value: if value == "unbekannt" or value == "verschieden": return None fk_value =...
338fb6dbc8e3f1c0e116f766f86a01b110c922f2
11,152
def binaryread(file, vartype, shape=(1,), charlen=16): """ Uses numpy to read from binary file. This was found to be faster than the struct approach and is used as the default. """ # read a string variable of length charlen if vartype == str: result = file.read(charlen * 1) el...
221e0a71271eea4a31423a94244c12784af7fef2
11,153
def subsample_data(neuron_data, sample_size = 10000): """ Acquires a subsample of the Neuron dataset. This function samples a set of neurons without replacement. Params ----------- Returns ----------- rand_ix (array-like): Array containing the chosen indices sample_neu...
801d0d618576e14b67b33bf9071c135409362bfe
11,154
def connect_db(): """Connects to the specific database.""" mongo = MongoClient(DATABASE_URL,replicaset=MONGO_REPLICASET) #if COLLECTION_NAME in mongo[DATABASE_NAME].collection_names(): collection = mongo[DATABASE_NAME][COLLECTION_NAME] #else: # mongo[DATABASE_NAME].create_collection(COLLECTIO...
0e037a2bfb8687d4ff2b477a59c3f5ba99335c44
11,156
def transient(func): """ decorator to make a function execution transient. meaning that before starting the execution of the function, a new session with a new transaction will be started, and after the completion of that function, the new transaction will be rolled back without the consideration o...
454c808d15bbdddd800db70ec56d228f432921f8
11,157
def make_mapping(environ, start_response): """ Establishing a mapping, storing the provided URI as a field on a tiddler in the PRIVATEER bag. Accepted data is either a json dictory with a uri key or a POST CGI form with a uri query paramter. Respond with a location header containing the uri ...
e90a72bce2132d703504230d41f3e807ea77d7a2
11,158
def create_space_magnitude_region(region, magnitudes): """Simple wrapper to create space-magnitude region """ if not (isinstance(region, CartesianGrid2D) or isinstance(region, QuadtreeGrid2D)) : raise TypeError("region must be CartesianGrid2D") # bind to region class if magnitudes is None: ...
64f4606c74ad38bd34ade7673074124e3d3faa48
11,159
def get_productivity(coin_endowments): """Returns the total coin inside the simulated economy. Args: coin_endowments (ndarray): The array of coin endowments for each of the agents in the simulated economy. Returns: Total coin endowment (float). """ return np.sum(coin_en...
e6dfe2485bce54599bc919d9a2b2235b90166702
11,161
def prefix_attrs(source, keys, prefix): """Rename some of the keys of a dictionary by adding a prefix. Parameters ---------- source : dict Source dictionary, for example data attributes. keys : sequence Names of keys to prefix. prefix : str Prefix to prepend to keys. Retu...
e1c8102fddf51cd7af620f9158419bff4b3f0c57
11,162
def add(coefficient_1, value_1, coefficient_2, value_2): """Provides an addition algebra for various types, including scalars and histogram objects. Incoming values are not modified. Args: coefficient_1: The first coefficient, a scalar value_1: The first value, a histogram or scalar ...
70bccba3d504325a66090104ffc4d464649f2b32
11,164
import time def kotlin_object_type_summary(lldb_val, internal_dict = {}): """Hook that is run by lldb to display a Kotlin object.""" start = time.monotonic() log(lambda: f"kotlin_object_type_summary({lldb_val.unsigned:#x}: {lldb_val.GetTypeName()})") fallback = lldb_val.GetValue() if lldb_val.GetT...
79883644017bfc35c77a17a3e5da4b5913864ef2
11,165
def _grep_first_pair_of_parentheses(s): """ Return the first matching pair of parentheses in a code string. INPUT: A string OUTPUT: A substring of the input, namely the part between the first (outmost) matching pair of parentheses (including the parentheses). Parentheses between...
7441c1b8734c211b9b320e195155719452cf7407
11,167
import requests def login(): """ """ url = "http://127.0.0.1:5001/rest/login" data = {"username": "kivanc", "password": "1234"} r = requests.post(url, json=data) output = r.json() return output["access_token"]
a2b4bd68110fd053c48988f7cc490c88f148bc1f
11,168
import tqdm import torch def evaluation_per_relation(triples: dict, model: EvaluationModel, batch_size: int = 4): """ :param triples: It should be a dict in form (Relation id):[(s_1,p_1,o_1)...(s_n,p_n,o_n)] """ # Evaluate per relation and store scores/evaluation measures score_per_rel = dict() ...
73262587c181fa285b97479110f49ea4dd178946
11,170
from datetime import datetime def check_upload(): """ 判断今天的代码是否上传 :return: """ ctime = datetime.date.today() # 当前日期 data = db_helper.fetchone('select id from record where ctime = %s and user_id = %s', (ctime, session['user_info']['id'])) return data
2dfceb7cc91668b3a41920b931e946188332c6e4
11,171
def get_package_object(): """Gets a sample package for the submission in Dev Center.""" package = { # The file name is relative to the root of the uploaded ZIP file. "fileName" : "bin/super_dev_ctr_api_sim.appxupload", # If you haven't begun to upload the file yet, set this value to "Pen...
d65329372f356325c08ecb814f48ad856b9509bc
11,172
def load_config(config_file="config.yaml"): """Load config file to initialize fragment factories. A config file is a Python file, loaded as a module. Example config file: # config.yaml name: My LDF server maintainer: chuck Norris <me@gmail.com> datasets: - name: DBpedia-2016-04...
b5ee03a3b30f4374da05469cd3a289566eb26540
11,176
def find_start_end(grid): """ Finds the source and destination block indexes from the list. Args grid: <list> the world grid blocks represented as a list of blocks (see Tutorial.pdf) Returns start: <int> source block index in the list end: <int> destination block index...
d617af3d6ebf9a2c9f42250214e3fe52d2017170
11,178
from typing import Optional import inspect def find_method_signature(klass, method: str) -> Optional[inspect.Signature]: """Look through a class' ancestors and fill out the methods signature. A class method has a signature. But it might now always be complete. When a parameter is not annotated, we might ...
17d3e7d554720766ca62cb4ad7a66c42f947fc1c
11,179
def format_long_calc_line(line: LongCalcLine) -> LongCalcLine: """ Return line with .latex attribute formatted with line breaks suitable for positioning within the "\aligned" latex environment. """ latex_code = line.latex long_latex = latex_code.replace("=", "\\\\&=") # Change all... long_l...
a6f19b7f3a1876f3b6b0c88baddfd02b16901b41
11,180
from riddle import emr, feature_importance from riddle.models import MLP import time import pickle def run(data_fn, prop_missing=0., max_num_feature=-1, feature_selection='random', k=10, data_dir='_data', out_dir='_out'): """Run RIDDLE classification interpretation pipeline. Arguments: data_f...
ac28216cbea67b0bdc6d2b3f617c24c975623415
11,181
def h_lgn(t, mu, sigma, normalize=False): """ Log-normal density Args: t: input argument (array) mu: mean parameter (-infty,infty) sigma: std parameter > 0 normalize: trapz integral normalization over t Returns: function values """ y = np.ze...
63bd6ea48f5ea28c5631b3ce259066d3624d038b
11,182
from .background import set_background_alignment import copy def align_background(data, align='auto'): """ Determine the Qz value associated with the background measurement. The *align* flag determines which background points are matched to the sample points. It can be 'sample' if background is ...
a8b33aa5440cf6c212d964d58720bef771fe2083
11,183
def get_bounds_from_config(b, state, base_units): """ Method to take a 3- or 4-tuple state definition config argument and return tuples for the bounds and default value of the Var object. Expects the form (lower, default, upper, units) where units is optional Args: b - StateBlock on which ...
c9e757a2032178e656f7bbc27519bd1650eb9a79
11,184
def read_train_data(): """ train_data.shape = (73257, 32, 32, 3) train_label.shape = (73257,) extra_data.shape = (531131, 32, 32, 3) extra_label.shape = (531131,) data.shape = (604388, 32, 32, 3) labels.shape = (604388,) """ train_data, train_label = read_images(full_data_dir+'train...
d6e5c06ceb3a95e20e8ae301d83e1f480fc48591
11,185
def laguerreFunction(n, alpha, t, normalized=True): """Evaluate Laguerre function using scipy.special""" if normalized: Z = np.exp( .5*sps.gammaln(n+1) - .5*sps.gammaln(n+alpha+1) ) else: Z = 1 return Z * np.sqrt(mu(alpha,t)) * sps.eval_genlaguerre(n, alpha, t)
6c48f3ddaed9db7d748ad8fc972a132795ad3916
11,186
def end(s): """Select the mobile or weight hanging at the end of a side.""" assert is_side(s), "must call end on a side" return branches(s)[0]
2bcbc61e989287d714e9401660e58bd2f54c6fe6
11,187
def get_ca_pos_from_atoms(df, atoms): """Look up alpha carbon positions of provided atoms.""" ca = df[df['atom_name'] == 'CA'].reset_index() nb = ca.reindex(atoms) nb = nb.reset_index().set_index('index') return nb
c069db751d94f6626be5d56e7b286ef3c873c04e
11,188
def LoadComponent(self,filename): # real signature unknown; restored from __doc__ """ LoadComponent(self: object,filename: str) -> object LoadComponent(self: object,stream: Stream) -> object LoadComponent(self: object,xmlReader: XmlReader) -> object LoadComponent(self: object,filename: TextReader) -> object L...
17b893a6e91f4ef62b8ba18646d9dc2005c52ccd
11,190
def split_bits(word : int, amounts : list): """ takes in a word and a list of bit amounts and returns the bits in the word split up. See the doctests for concrete examples >>> [bin(x) for x in split_bits(0b1001111010000001, [16])] ['0b1001111010000001'] >>> [bin(x) for x in split_bits(...
556a389bb673af12a8b11d8381914bf56f7e0599
11,191
def global_tracer(ot_tracer): """A function similar to one OpenTracing users would write to initialize their OpenTracing tracer. """ set_global_tracer(ot_tracer) return ot_tracer
87207d92179a0b23f20806e3e93ec7e78b1b31f1
11,192
import requests def getListProjectsInGroup(config, grp): """ Get list of issue in group """ print("Retrieve project of group: %s " % grp.name) data = None __prjLst = gitlabProjectList(grp) if (DUMMY_DATA): testFile = getFullFilePath(ISSUES_GRP_TEST_FILE) with open (testFile...
1c926e8b855cba502229ab1c31c9706c20882a1c
11,193
def group_naptan_datatypes(gdf, naptan_column='LocalityName'): """[summary] groups together naptan datasets into subsets that are grouped by the given naptan column. Args: gdf ([type]): [description] naptan_column (str, optional): [description]. Defaults to 'LocalityName'. Returns: ...
d4cca1180f1b3d6622c7c2fd5df1cdd1b369c5b3
11,194
def get_facts_by_name_and_value(api_url=None, fact_name=None, fact_value=None, verify=False, cert=list()): """ Returns facts by name and value :param api_url: Base PuppetDB API url :param fact_name: Name of fact :param fact_value: Value of fact """ return utils._make_api_request(api_url, '...
bdce7473bff944609ffdb191948b008ca4a1422a
11,195
def produce_phase(pipeline_run): """Produce result with Produce phase data.""" scores = pipeline_run['run']['results']['scores'] if len(scores) > 1: raise ValueError('This run has more than one score!') scores = scores[0] return { 'metric': scores['metric']['metric'], 'con...
7ed003281eac240a407dac1d03a5e3f5a6e5b2cd
11,196
import json from unittest.mock import patch async def init_integration(hass: HomeAssistant, use_nickname=True) -> MockConfigEntry: """Set up the Mazda Connected Services integration in Home Assistant.""" get_vehicles_fixture = json.loads(load_fixture("mazda/get_vehicles.json")) if not use_nickname: ...
96756b011f66786c0c8a8704446546c0751de13f
11,197
def get_app_domain(): """ Returns the full URL to the domain. The output from this function gets generally appended with a path string. """ url = settings.INCOMEPROPERTYEVALUATOR_APP_HTTP_PROTOCOL url += settings.INCOMEPROPERTYEVALUATOR_APP_HTTP_DOMAIN return url
0a9c58a179c281072104fb5b7859b2d0ef8426ae
11,198