content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def gen_rsa(): """ Generate an RSA Key Pair for digital signature this is designed to be called once per user TODO maybe this belongs in server-specific code since server will need to know public and private keys """ pkey = PKey() pkey.generate_key(TYPE_RSA, RSA_BITS) pkey.check() ...
ea6566c6486eaf524f026092f41adb414161ed69
3,649,100
import sys def get_token_type_str(token): """根据传入的token对象的类型返回该token的类型的字符串表达 参数 ---- token : Token 返回 ---- str : str """ token_type = token.type if token_type == TOKEN_TYPE_IF: return '(keyword)if' elif token_type == TOKEN_TYPE_ELIF: return '(keyword)elif'...
66d3c811eaf32ca891e0d130bdb7eaed35d9c5c4
3,649,101
import os def _( sklearn_model: ensemble.GradientBoostingRegressor, path: os.PathLike, ) -> tf.keras.Model: """Converts a gradient boosting regression model into a TFDF model.""" if isinstance(sklearn_model.init_, dummy.DummyRegressor): # If the initial estimator is a DummyRegressor, then it predicts ...
d40ae1ff430cf0a5096611b97ff4f7fee40fe8bf
3,649,102
import queue def task_checkqueue(storage): """ Task that watches a queue for messages and acts on them when received. """ # Get the queue object from the storage dictionary thequeue = storage.get("queue") try: # Use a timeout so it blocks for at-most 0.5 seconds while waiting for a mes...
3c7e8cfda53abb0551916894719e66b3d27886e9
3,649,103
import torch def to_sparse(x): """ converts dense tensor x to sparse format """ x_typename = torch.typename(x).split('.')[-1] sparse_tensortype = getattr(torch.sparse, x_typename) indices = torch.nonzero(x) if len(indices.shape) == 0: # if all elements are zeros return sparse_tensortype(...
b9af99c3c6e41e4f6a73ad213f58338110329dbc
3,649,104
def get_top_article_categories(): """ 获取顶级文章分类列表 自定义模版标签 """ return Category.objects.filter(level=1)
88ed0aefe81b3190590974a38c9363f862b8db6c
3,649,105
def filter_variants_top_k(log, k, parameters=None): """ Keeps the top-k variants of the log Parameters ------------- log Event log k Number of variants that should be kept parameters Parameters Returns ------------- filtered_log Filtered log ...
20e273f5d3ac88e3bc9d0795566b2536c10b5703
3,649,106
def get_weighted_average(embedding, x, w): """ Compute the weighted average vectors :param embedding: embedding[i,:] is the vector for word i :param x: x[i, :] are the indices of the words in sentence i :param w: w[i, :] are the weights for the words in sentence i :return: emb[i, :] are the weig...
e5cd9984e49075530f981c8600c7e6d86de3c113
3,649,107
from glyphsLib import glyphdata # Expensive import def _build_gdef(ufo): """Build a table GDEF statement for ligature carets.""" bases, ligatures, marks, carets = set(), set(), set(), {} category_key = GLYPHLIB_PREFIX + 'category' subCategory_key = GLYPHLIB_PREFIX + 'subCategory' for glyph in uf...
2163971557a8908cce5f142f2e9dfc7fe360f190
3,649,108
def winningRate2(r, s, X, Y): """ revised version, now we want to investigate how value of X and Y will affect. r: int = remaining round of game s: int = current score X: int = points winning for X-head Y: int = points wining for Y-head (assuming X and Y are both fair, and we always assume Y...
d33b05aa429044cb76b33842e33b99c1d1d6de7f
3,649,109
import json import os def handler(event, context): """Deletes all user content based on username provided in body, only accessible from authenticated users with the custom:group=admin""" logger.info(f"Received event: {json.dumps(event)}") try: if event["requestContext"]["authorizer"]["claims"...
392fdd6a2a67b94909d095e15bfe7870ba349f42
3,649,110
def DayOfWeek(year,month,day): """DayOfWeek returns the day of week 1-7, 1 being Monday for the given year, month and day""" num=year*365 num=num+year//4+1 num=num-(year//100+1) num=num+year//400+1 if month<3 and LeapYear(year): num=num-1 return (num+MONTH_OFFSETS[month-1]+day+4)%7+1
41c974e1342e65d553702d0610e8dc9c671538a6
3,649,111
import os def get_stand_exe() -> str: """Get the path to standexe Returns: Path to standexe Raises: ValueError: If STAND_EXE is not found in environment variables. """ if os.environ['STAND_EXE']: return os.environ['STAND_EXE'] else: raise ValueError('STAND_EXE...
da44d23239060874965617c24ab0bd678c9535b9
3,649,112
def chef_execute_cli_commands(configuration): """ API to generate sonic cli commands with the provided configuration :param configuration: :return: """ if not configuration: return False commands = "" action_run = "action:run" for module in configuration: if module ...
439b7310015a9707ea6796ea3d24577a5dec069f
3,649,113
def _normalize(vector): """Returns a normalized version of a numpy vector.""" return vector/np.sqrt(np.dot(vector, vector));
42942ea19af176f6c9fa0ad39b7e060dd518c086
3,649,114
def load_ext(ext_name, name, func=None, endpoint=None): """ Load an external module. Example: ``load_ext("distkv_ext","owfs","model")`` loads …/distkv_ext/owfs/model.py and returns its global dict. When "ep" is given it returns the entry point. Any additional keywords are added to the module d...
1c47abb64af732f1820e80eb4da714b338ec3e50
3,649,115
def get_chol_factor(lower_tri_vals): """ Args: lower_tri_vals: numpy array, shaped as the number of lower triangular elements, number of observations. The values ordered according to np.tril_indices(p) where p is the dimension of t...
fa27afefb49a87bdeac8bceee9f95b34e6c01d3f
3,649,116
def get_angles_gram_mask(gram, mask): """ Input: (gram) square numpy array, (mask) square numpy array where 1 = select, 0 = do not select Output: (angles) numpy array or angles in mask in degrees """ angles = gram * mask angles = angles[angles != 0] angles = np.degrees(np.arccos(angles...
3303e318f42b2a7c3a15b4d267f07b7618026b25
3,649,117
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None): """ Compute the expectation: expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n) - Ka_{.,.}, Kb_{.,.} :: Linear kernels Ka and Kb as well as Z1 and Z2 can differ from each other, but this is supported only if the Gaussian p is Diago...
105a6445f1a37e2208c65c8bcbcfe76227516991
3,649,118
def rotX(angle): """ ----------------------------------------------------------------------- Purpose: Calculate the matrix that represents a 3d rotation around the X axis. Input: Rotation angle in degrees Returns: A 3x3 matrix representing the rotation about angle around X axis. ...
b1dd62497cf9db137edbd90f1ff4f6fdb36d54d5
3,649,119
import requests import logging def extract_url(url): """ extract the real url from yahoo rss feed item """ _url = None if '*' in url: # old style yahoo redirect link _url = "http" + url.split("*http")[-1] elif url.startswith("http://finance.yaho...
0707aaaf5677fe33542f14a4b0335fef98711cf2
3,649,120
import re def LF_positive_MeshTerm(report): """ Looking for positive mesh terms """ for idx in range(1,len(categories)): reg_pos = re.compile(categories[idx],re.IGNORECASE) reg_neg = re.compile('(No|without|resolution)\\s([a-zA-Z0-9\-,_]*\\s){0,10}'+categories[idx],re.IGNORECASE) ...
391d5775cf109c9f4b0d254162b93937882605ee
3,649,121
def user_ratio_shuffle_split_with_targets(X, train_ratio=0.8, n_valid_users=1000, n_test_users=1000, minimum_interaction=3, ...
0f6bc42e94caff49c0be29215b9a6ec4f2203ff7
3,649,122
import torch def slice_core(core_tensor, inputs): """ Get matrix slices by indexing or contracting inputs, depending on input dtype """ assert isinstance(core_tensor, torch.Tensor) assert isinstance(inputs, torch.Tensor) if is_int_type(inputs): return core_tensor[:, inputs, :] else...
01a70a678286977b3a36ca24a2f67dce4dbc01fe
3,649,123
import argparse def start_with_strategy(args, strategy, ants): """Reads command-line arguments and starts a game with those options.""" parser = argparse.ArgumentParser(description="Play Ants vs. SomeBees") parser.add_argument('-d', type=str, metavar='DIFFICULTY', help='sets diffic...
bbcd0e01dd86b19110cf3ab83e5d4d2ad6f17710
3,649,124
import math def geo2xy(ff_lat_pto, ff_lng_pto, ff_lat_ref=cdf.M_REF_LAT, ff_lng_ref=cdf.M_REF_LNG): """ transforma coordenadas geográficas em coordenadas cartesianas :param ff_lat_pto: latitude em graus :param ff_lng_pto: longitude em graus :param ff_lat_ref: latitude do ponto de referência :...
93dbe8a41aecb3029d5ac6fa3e68c740c625a486
3,649,125
def size(e): """ :rtype: Column """ return col(Size(parse(e)))
06b904583dc25a9e40b97ca6655bb0e5dcb28304
3,649,126
def b64pad(b64data): """Pad base64 string with '=' to achieve a length that is a multiple of 4 """ return b64data + '=' * (4 - (len(b64data) % 4))
bdc14821bfbdbf220ff371fbe5e486d3e682337b
3,649,127
def get_peak_electric_demand(points_on_line): """ Initialize Power Demand :param points_on_line: information about every node in study case :type points_on_line: GeoDataFrame :returns: - **dict_peak_el**: Value is the ELECTRIC peak demand depending on thermally connected or disconnected. ...
015fe10835f49f060e24681335d77a79586e31ea
3,649,128
def _GetDatabaseLookupFunction(filename, flaps, omega_hat, thrust_coeff): """Produces a lookup function from an aero database file.""" db = load_database.AeroDatabase(filename) def _Lookup(alpha, beta, dflaps=None, domega=None): if dflaps is None: dflaps = np.zeros((system_types.kNumFlaps,)) if dome...
5b1e7a4636aa824466e791b54dd7a67a4208962e
3,649,129
def parse_copy_core_dump(raw_result): """ Parse the 'parse_copy_core_dump' command raw output. :param str raw_result: copy core-dump raw result string. :rtype: dict :return: The parsed result of the copy core-dump to server: :: { 0:{ 'status': 'success' ...
4ce168c9bc8c462ecc36beba889adb36cc64135d
3,649,130
def _handle_requirements(hass, component, name): """Install the requirements for a component.""" if hass.config.skip_pip or not hasattr(component, 'REQUIREMENTS'): return True for req in component.REQUIREMENTS: if not pkg_util.install_package(req, target=hass.config.path('lib')): ...
efa0c371150a9aee9f26136a17ad1e33b9760340
3,649,131
def ticket_id_url(workspace, number): """ The url for a specific ticket in a specific workspace :param workspace: The workspace :param number: The number of the ticket :return: The url to fetch that specific ticket """ return basic_url + ' spaces/' + workspace + '/tickets/' + number + '.json...
a0ffeb53062c635f74feb011af793a2c00c361c4
3,649,132
import os def get_cifar10(data_path): """Returns cifar10 dataset. Args: data_path: dataset location. Returns: tuple (training instances, training labels, testing instances, testing labels) Instances of dimension # of instances X dimension. """ x_train = np.zeros((50000, 3072)) y_...
93f29763ebd2a2cd3a5631ac1c3072ef8451fc25
3,649,133
def compute_lifting_parameter(lamb, lambda_plane_idxs, lambda_offset_idxs, cutoff): """One way to compute a per-particle "4D" offset in terms of an adjustable lamb and constant per-particle parameters. Notes ----- (ytz): this initializes the 4th dimension to a fixed plane adjust by an offset fo...
a9455ed67fcb21bcf1382fe66a77e0563f467421
3,649,134
import re import json def create_controller(): """ 1. Check the token 2. Call the worker method """ minimum_buffer_min = 3 if views.ds_token_ok(minimum_buffer_min): # 2. Call the worker method # More data validation would be a good idea here # Strip anything other than ...
1aa777b66f110d575ea16531ca4bd72e0117e0b0
3,649,135
def reproduce_load_profile(neural_model, simulation_model: CHPP_HWT, input_data, logger): """ Tries to follow a real load profile """ # make sure the random seeds are different in each process #np.random.seed(int.from_bytes(os.urandom(4), byteorder='little')) temperature, powers, heat_demand = ...
078fa837c0c82ea17c42ca949ba9bb33cdaeaaa0
3,649,136
def session_pca(imgs, mask_img, parameters, n_components=20, confounds=None, memory_level=0, memory=Memory(cachedir=None), verbose=0, copy=True): """Filter, mask and compute PCA on Niimg-like objects This is an help...
f175ac8d9c39e133c34a4db215b5e87288bdafd4
3,649,137
def numpy_napoleon(prnt_doc, child_doc): """Behaves identically to the 'numpy' style, but abides by the docstring sections specified by the "Napoleon" standard. For more info regarding the Napoleon standard, see: http://sphinxcontrib-napoleon.readthedocs.io/en/latest/index.html#docstring-sections ...
1795ddd1cfeeb8aee07cb17a369c6043b5fda52f
3,649,138
def search_unique_identities_slice(db, term, offset, limit): """Look for unique identities using slicing. This function returns those unique identities which match with the given `term`. The term will be compared with name, email, username and source values of each identity. When an empty term is given...
1cfed05995eb90427a0f4a9475cfd8f7737d7e59
3,649,139
def get_change_description(req_sheet, row_num): """ Accessor for Change Description Args: req_sheet: A variable holding an Excel Workbook sheet in memory. row_num: A variable holding the row # of the data being accessed. Returns: A string value of the Change Description """ ...
7d3f286fb2586bf7bed64de8bb0cbf156e1ff954
3,649,140
def reduce_pca(data_df, n_components=None): """ Uses PCA to reduce dimension. Parameters: data_df (DataFrame): The input data in DataFrame format n_components (float): The number of components or to reduce to. If the number if between 0 and 1, n_components is the % of th...
b4b8db256b5996ddf3101a7737cb1396bc5abd06
3,649,141
def create_disjoint_intervals(draw, dtype, n_intervals=10, dt=1, time_range=(0, 100), channel_range=(2000, 2119), length_range=(1, 1), ): ...
67ed49bd8d94067cb6647164fa44beb4f8d91314
3,649,142
def get_deleted_resources(): """Get a list of resources that failed to be deleted in OVN. Get a list of resources that have been deleted from neutron but not in OVN. Once a resource is deleted in Neutron the ``standard_attr_id`` foreign key in the ovn_revision_numbers table will be set to NULL. Up...
6a37fd84933ceee3a2a537aee8a01315f5869200
3,649,143
def load_base_schema(base_schema=None, verbose=False): """Load base schema, schema contains base classes for sub-classing in user schemas. """ _base = base_schema or BASE_SCHEMA or [] _base_schema = [] if "schema.org" in _base: _base_schema.append( load_schemaorg(verbose=v...
18fe2b7045aa6d8e7382c37093be053b619ec216
3,649,144
def ShowX86UserStack(thread, user_lib_info = None): """ Display user space stack frame and pc addresses. params: thread: obj referencing thread value returns: Nothing """ iss = Cast(thread.machine.iss, 'x86_saved_state_t *') abi = int(iss.flavor) user_ip = 0 ...
254c8797a16e560b23d92cde15d4a572f3f1660a
3,649,145
def endgame_score_connectfour(board, is_current_player_maximizer) : """Given an endgame board, returns 1000 if the maximizer has won, -1000 if the minimizer has won, or 0 in case of a tie.""" chains_1 = board.get_all_chains(current_player=is_current_player_maximizer) chains_2 = board.get_all_chains(curr...
bcb37381a9633377cb3405fbae45123e2a391df9
3,649,146
import os import glob def identify(path_or_file): """ Accepts a single file or list of files, Returns a list of Image file names :param path_or_file: :return: list of Image file names """ files = [] # Included capitalized formats supported_formats = set( IMAGE_FORMATS[0] + tu...
9d14cd52d2e0aba09b54dc00a7823832bf742f08
3,649,147
def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs): """Add a vertical color bar to an image plot. Taken from https://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph """ divider = axes_grid1.make_axes_locatable(im.axes) width = axes_grid1.axes_size.AxesY(im.ax...
acb0b21139d10393c2605bc94671fc774ada3800
3,649,148
import time def wait_procs(procs, timeout, callback=None): """Convenience function which waits for a list of processes to terminate. Return a (gone, alive) tuple indicating which processes are gone and which ones are still alive. The gone ones will have a new 'retcode' attribute indicating p...
624a6a1286a662a6f9e2d0680898e89b71585a7a
3,649,149
def select(sel, truecase, falsecase): """ Multiplexer returning falsecase for select==0, otherwise truecase. :param WireVector sel: used as the select input to the multiplexer :param WireVector falsecase: the WireVector selected if select==0 :param WireVector truecase: the WireVector selected if select...
134e62fa84a16560e16f72294c9d01b3118c80e4
3,649,150
def fish_collision(sprite1, sprite2): """Algorithm for determining if there is a collision between the sprites.""" if sprite1 == sprite2: return False else: return collide_circle(sprite1, sprite2)
846024639f971c755b9ae88f8db43695d1e7c5e2
3,649,151
def normalizePeriodList(periods): """ Normalize the list of periods by merging overlapping or consecutive ranges and sorting the list by each periods start. @param list: a list of tuples of L{Period}. The list is changed in place. """ # First sort the list def sortPeriods(p1, p2): "...
d178123e8ef65b88e46130db24f96aa86b444b11
3,649,152
from typing import Callable from typing import Optional from typing import Any import inspect from typing import Dict def assemble(the_type: Callable[..., TypeT], profile: Optional[str] = None, **kwargs: Any) -> TypeT: """Create an instance of a certain type, using constructor inject...
e8a39d61ddcb8834daf45089f597754a2860a334
3,649,153
def coord_ijk_to_xyz(affine, coords): """ Converts voxel `coords` in cartesian space to `affine` space Parameters ---------- affine : (4, 4) array-like Affine matrix coords : (N,) list of list Image coordinate values, where each entry is a length three list of int denoti...
c7099a588df3bd85a3a5a85451e15812564aae2f
3,649,154
def _get_create_statement(server, temp_datadir, frm_file, version, options, quiet=False): """Get the CREATE statement for the .frm file This method attempts to read the CREATE statement by copying the .frm file, altering the storage engine in the .frm fil...
953b97df9f7f01540d5f61ef8099282d4aab26d6
3,649,155
def delete_driver_vehicle(driver): """delete driver""" try: driver.vehicle = None driver.save() return driver, "success" except Exception as err: logger.error("deleteVehicleForDriverRecord@error") logger.error(err) return None, str(err)
e6de3c9d1ae0ce0ac2022fe8ce38c2eccbe3b8df
3,649,156
def passivity(s: npy.ndarray) -> npy.ndarray: """ Passivity metric for a multi-port network. A metric which is proportional to the amount of power lost in a multiport network, depending on the excitation port. Specifically, this returns a matrix who's diagonals are equal to the total power rece...
9b3629aae603d8de97982113333b87bb021972e4
3,649,157
def sample_distance(sampleA, sampleB, sigma): """ I know this isn't the best distance measure, alright. """ # RBF! gamma = 1 / (2 * sigma**2) similarity = np.exp(-gamma*(np.linalg.norm(sampleA - sampleB)**2)) distance = 1 - similarity return distance
1f1bb56d8e1876c9c9ab6b1d1db26ff549d86b81
3,649,158
def read_sequence_item(fp, is_implicit_VR, is_little_endian, encoding, offset=0): """Read and return a single sequence item, i.e. a Dataset""" seq_item_tell = fp.tell() + offset if is_little_endian: tag_length_format = "<HHL" else: tag_length_format = ">HHL" tr...
fb0eeca700fa1d66e1289c2cfd106934ba54ca1a
3,649,159
from typing import Dict from typing import Set def get_filters(query_metadata: QueryMetadataTable) -> Dict[VertexPath, Set[FilterInfo]]: """Get the filters at each VertexPath.""" filters: Dict[VertexPath, Set[FilterInfo]] = {} for location, _ in query_metadata.registered_locations: filter_infos = ...
79ef7accd1c8e1d100f48eb7086c842429a4a513
3,649,160
import numpy def auxiliary_equations(*, F, T_degC, I_sc_A_0, I_rs_1_A_0, n_1_0, I_rs_2_0_A, n_2_0, R_s_Ohm_0, G_p_S_0, E_g_eV_0, N_s, T_degC_0=T_degC_stc): """ Computes the auxiliary equations at F and T_degC for the 8-parameter DDM-G. Inputs (any broadcast-compatible combination ...
5bbb988a7e4415f59a56985c2c867ec1a0dc5df2
3,649,161
import time import os def detector(name_file: str, chk_video_det, xy_coord: list, frame_zoom: int, size_detect: int, lab_o_proc, window, frame_shift, play_speed, but_start, but_pause) -> str: """Данная функция производит поиск движения в заданной области, в текущем файле. name_file - Имя файла, к...
d0dafa738421fdf41479327cd7aa76774235e0c3
3,649,162
from typing import List from typing import Dict def get_highest_confidence_transcript_for_each_session( transcripts: List[db_models.Transcript], ) -> List[db_models.Transcript]: """ Filter down a list transcript documents to just a single transcript per session taking the highest confidence transcript...
fccf657c5c670d8b3e275641d411ede34af91e41
3,649,163
def get_groups_data(): """ Get all groups, get all users for each group and sort groups by users :return: """ groups = [group["name"] for group in jira.get_groups(limit=200)["groups"]] groups_and_users = [get_all_users(group) for group in groups] groups_and_users = [sort_users_in_group(group...
9ec0d3772b438f10edde4a4bad591f249709de98
3,649,164
import builtins import os def get_sep(): """Returns the appropriate filepath separator char depending on OS and xonsh options set """ if ON_WINDOWS and builtins.__xonsh__.env.get("FORCE_POSIX_PATHS"): return os.altsep else: return os.sep
7b9431a05ac61ae49680e26939dd91d85df99de5
3,649,165
def hindu_lunar_holiday(l_month, l_day, g_year): """Return the list of fixed dates of occurrences of Hindu lunar month, month, day, day, in Gregorian year, g_year.""" l_year = hindu_lunar_year( hindu_lunar_from_fixed(gregorian_new_year(g_year))) date1 = hindu_date_occur(l_month, l_day, l_year) ...
fa9bafead696b177a137c12b7544c8e71c4f2f43
3,649,166
import copy def identify_all_failure_paths(network_df_in,edge_failure_set,flow_dataframe,path_criteria): """Identify all paths that contain an edge Parameters --------- network_df_in - Pandas DataFrame of network edge_failure_set - List of string edge ID's flow_dataframe - Pandas DataFrame of...
db2da6ad20a4ae547c309ac63b6e68a17c3874e7
3,649,167
def wikipedia_wtap_setup(): """ A commander has 5 tanks, 2 aircraft and 1 sea vessel and is told to engage 3 targets with values 5,10,20 ... """ tanks = ["tank-{}".format(i) for i in range(5)] aircrafts = ["aircraft-{}".format(i) for i in range(2)] ships = ["ship-{}".format(i) for i in range...
828746bef74b88bde1a9c72a79338ec05591721a
3,649,168
def allowed_file(filename: str) -> bool: """Determines whether filename is allowable Parameters ---------- filename : str a filename Returns ------- bool True if allowed """ return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
fd05abc21025c9eb49f7e3426b4e183b178361c4
3,649,169
def share_is_mounted(details): """Check if dev/share/etc is mounted, returns bool.""" mounted = False if PLATFORM == 'Darwin': # Weak and naive text search proc = run_program(['mount'], check=False) for line in proc.stdout.splitlines(): if f'{details["Address"]}/{details["Share"]}' in line: ...
43ca415779d133d7a90c2a8f26521e0a5cca2fcb
3,649,170
def update_bitweights(realization, asgn, tileids, tg_ids, tg_ids2idx, bitweights): """ Update bit weights for assigned science targets """ for tileid in tileids: try: # Find which targets were assigned adata = asgn.tile_location_target(tileid) for loc, tgid in adata.items...
f1b7e085d43e36b025aa1c61ab1b7156ba1d3ed7
3,649,171
def load_from_input_flags(params, params_source, input_flags): """Update params dictionary with input flags. Args: params: Python dictionary of hyperparameters. params_source: Python dictionary to record source of hyperparameters. input_flags: All the flags with non-null value of overridden hyper...
7ec8662f03469f1ed03f29c9f7e9663c49aa7056
3,649,172
import hal def hal(_module_patch): """Simulated hal module""" return hal
3ab217e0cbce54d6dab01217c829905dc61bf06c
3,649,173
def elements(all_isotopes=True): """ Loads a DataFrame of all elements and isotopes. Scraped from https://www.webelements.com/ Returns ------- pandas DataFrame with columns (element, atomic_number, isotope, atomic_weight, percent) """ el = pd.read_pickle(pkgrs.resource_filename('latool...
d706ee5ffaa8c756c9e85f3e143876070f8f81e4
3,649,174
def datas(draw): """TODO expand to include all optional parameters.""" metric = draw(ascii()) filter = draw(filters()) return flow.Data(metric, filter=filter)
8c85202f36a25f871e7235360353f972a56ba06e
3,649,175
import typing def create_steps_sequence(num_steps: Numeric, axis: str) -> typing.List[typing.Tuple[float, str]]: """ Returns a list of num_steps tuples: [float, str], with given string parameter, and the floating-point parameter increasing lineairly from 0 to 1. Example: >>> create_steps_sequenc...
3f7e2010a3360c90bec81a02228b1a7590686175
3,649,176
def disable_doze_light(ad): """Force the device not in doze light mode. Args: ad: android device object. Returns: True if device is not in doze light mode. False otherwise. """ ad.adb.shell("dumpsys battery reset") ad.adb.shell("cmd deviceidle disable light") adb_sh...
d2054ae8f84a45b360ded839badfbd19fea83b11
3,649,177
def jobs(): """ List all jobs """ return jsonify(job.get_jobs())
c7141011c59851586d327185892ea61d7a11ef58
3,649,178
def get_pipelines(): """Get pipelines.""" return PIPELINES
2d770a9fa189dd534528d26794f8887c638723f4
3,649,179
import re def tokenize(s): """ Tokenize on parenthesis, punctuation, spaces and American units followed by a slash. We sometimes give American units and metric units for baking recipes. For example: * 2 tablespoons/30 mililiters milk or cream * 2 1/2 cups/300 grams all-purpose flour ...
04575ff78cb73515fafcda541177d53d330bd510
3,649,180
def makeColorMatrix(n, bg_color, bg_alpha, ix=None, fg_color=[228/255.0, 26/255.0, 28/255.0], fg_alpha=1.0): """ Construct the RGBA color parameter for a matplotlib plot. This function is intended to allow for a set of "foreground" points to be colored according to integer labels (e.g. according to clustering ou...
7ef7a7cfb6cd4a6bcb97086382e6b95e5340ce78
3,649,181
import itertools def closest_pair(points): """ 最近点対 O(N log N) Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A&lang=ja :param list of Point points: :rtype: (float, (Point, Point)) :return: (距離, 点対) """ assert len(points) >= 2 def _rec(xsorted): """...
fbb189269b6d1fcbf214d8030d49bb0605b375c2
3,649,182
def less_equals(l,r): """ | Forms constraint :math:`l \leq r`. :param l: number, :ref:`scalar object<scalar_ref>` or :ref:`multidimensional object<multi_ref>`. :param r: number, :ref:`scalar object<scalar_ref>` or :ref:`multidimensional object<m...
ba37a090cbbf1d7db99411d67e9eda572c1f0153
3,649,183
def ensureImageMode(tex : Image, mode="RGBA") -> Image: """Ensure the passed image is in a given mode. If it is not, convert it. https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes :param Image tex: The image whose mode to check :param str mode: The mode to ensure and convert t...
9b77763fbfea0f66b4b4d7151cdf595f2e2b8aa6
3,649,184
import os import glob def generate_dada_filelist(filename): """ Generate a list of DADA files from start filename Args: filename (str): Path to file. e.g. /data/dprice/2020-07-23-02:33:07.587_0000000000000000.000000.dada Returns: flist (list): A list of all a...
55cde1a818e78886ace3aa89ff9535f099033a79
3,649,185
import os import shutil import subprocess def buildWheels(buildDir, requirements): """build wheels :param buildDir: directory to put wheels in (under 'wheelhouse') :type buildDir: string :param requirements: name of file holding names of Python packages :type requirements: string """ whee...
81bb1879ee1ce0e711dc36fe55cf0b47ad48f3c7
3,649,186
def code2name(code: int) -> str: """ Convert prefecture code to name """ return __code2name[code]
d2ca1a3977915359afd8254337e14c6fd13db8b3
3,649,187
def newton(backward_differences, max_num_iters, newton_coefficient, ode_fn_vec, order, step_size, time, tol, unitary, upper): """Runs Newton's method to solve the BDF equation.""" initial_guess = tf.reduce_sum( tf1.where( tf.range(MAX_ORDER + 1) <= order, backward_differences[:M...
9a5e6e45357d2d769153bf6854818e22df7639f3
3,649,188
from unittest.mock import Mock import os def mock_handler( handler: RequestHandler, uri: str = 'https://hub.example.com', method: str = 'GET', **settings: dict ) -> RequestHandler: """Instantiate a Handler in a mock application""" application = Application( hub=Mock(base_url='/hub/', server=Mock(b...
8615a77bd401b1e6cd9b078ae0b8d9896aecc0d7
3,649,189
import random def input(channel): """ To read the value of a GPIO pin: :param channel: :return: """ return LOW if random.random() < 0.5 else HIGH
838df044dc18c443e2f35f7f67a8e07b8276e1a3
3,649,190
def kml_start(params): """Define basic kml header string""" kmlstart = ''' <Document> <name>%s</name> <open>1</open> <description>%s</description> ''' return kmlstart % (params[0], params[1])
c2fa4c1eeff086dfc3baa41ecd067634920b25b1
3,649,191
def add_item_to_do_list(): """ Asks users to keep entering items to add to a new To Do list until they enter the word 'stop' :return: to do list with new items """ ### TO COMPLETE ### return to_do_list
4c133ea3c05024a51dda2fb9f01dcc30926f84f4
3,649,192
def parse(tokens): """Currently parse just supports fn, variable and constant definitions.""" context = Context() context.tokens = tokens while tokens: parse_token(context) if context.stack: raise CompileError("after parsing, there are still words on the stack!!:\n{0}".format( ...
89dce5a630dd0bd657963185ac533738bee7d6a5
3,649,193
import sys import numpy def _create_rpc_callback(label, result_counter): """Creates RPC callback function. Args: label: The correct label for the predicted example. result_counter: Counter for the prediction result. Returns: The callback function. """ def _callback(result_futur...
6b3276e9db5d551cb5abdd3f3f9b1f5ce041b02e
3,649,194
def get_file_iterator(options): """ returns a sequence of files raises IOError if problemmatic raises ValueError if problemmatic """ # -------- BUILD FILE ITERATOR/GENERATOR -------- if options.f is not None: files = options.f elif options.l is not None: try: ...
53b16f49d14dc346e404a63415772dd2a1d10f50
3,649,195
def entropy_from_CT(SA, CT): """ Calculates specific entropy of seawater. Parameters ---------- SA : array_like Absolute salinity [g kg :sup:`-1`] CT : array_like Conservative Temperature [:math:`^\circ` C (ITS-90)] Returns ------- entropy : array_like ...
dfaaeef93ed924bc5e49fb02c30b6cc43ef824e0
3,649,196
def checking_log(input_pdb_path: str, output_log_path: str, properties: dict = None, **kwargs) -> int: """Create :class:`CheckingLog <model.checking_log.CheckingLog>` class and execute the :meth:`launch() <model.checking_log.CheckingLog.launch>` method.""" return CheckingLog(input_pdb_path=input_pdb_path, ...
c6cb77585920609e12b90f5f783ceb73b58afb8b
3,649,197
from typing import Optional import os import logging import json def _repoint_files_json_dir(filename: str, source_folder: str, target_folder: str, working_folder: str) -> Optional[str]: """ Repoints the DIR entry in the JSON file to the target folder Arguments: filename: the file to load and process ...
974220fb8526cc667fcd1dcaf7c3cdecda06e6b3
3,649,198
def get_registry_by_name(cli_ctx, registry_name, resource_group_name=None): """Returns a tuple of Registry object and resource group name. :param str registry_name: The name of container registry :param str resource_group_name: The name of resource group """ resource_group_name = get_resource_group_...
ca4bcee260f035a7921e772dffaace379e0ab115
3,649,199