content
stringlengths
22
815k
id
int64
0
4.91M
def min_window(k): """ Algorithm to find minimum window length between k lists. Uses a heap. """ heap = [] p=[0 for i in range(len(k))] min_r = 99999999 ma=0 for i in range(len(k)): if k[i][0]>ma: ma=k[i][0] heapq.heappush(heap,(k[i][0...
59,200
def test_project_create(connection): """Test the create method of the project object""" project = connection.Project.create(name="test_project") assert project.name == "test_project" assert project.owner == connection.current_user() # If group is not specified, the group should be the # first...
59,201
def gather_target_types(shacl_graph: 'ShapesGraph') -> Sequence[Union['SHACLTargetType', 'SPARQLTargetType']]: """ :param shacl_graph: :type shacl_graph: ShapesGraph :return: :rtype: [SHACLTargetType] """ all_target_types: List[Union['SHACLTargetType', 'SPARQLTargetType']] = [] sub_targ...
59,202
def r_vonmises(n,mu,kappa): """ This function is used for generating random numbers for a von Mises circular distribution Parameters: n: int, Number of observations mu: float/int, location parameter kappa: float/int, scale parameter. Large values of kappa co...
59,203
def mempool_space_mempool_stats(update: Update, context: CallbackContext): """ Mempool statistics from mempool space """ try: r = requests.get(f'{config.MEMPOOL_SPACE_URL}/api/mempool', timeout=5) mempool = r.json() except: context.bot.send_message(chat_id=update.message.cha...
59,204
def video_flip_transform(buildState): """ APPLIES: VIDEO Applies frame rate adjustments first and the flips the masks. Resize is supported (last), but not recommended as part of the operation. :param buildState: :return: updated composite mask @type buildState: BuildState @rtype: Composi...
59,205
def alpha_023(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: eries:index为成分股代码,values为对应因子值或0.00,当不满足条件时为0.00 公式: (((sum(high, 20) / 20) < high) ? (-1\* delta(high, 2)) : 0) """ enddate = to_date_str(enddate) ...
59,206
def upstart_restart(name): """Tries a `restart` command to the given service, if not successful will stop it and start it. If the service is not started, will start it.""" with fabric.api.settings(warn_only=True): status = sudo("service %s status|cat" % name) if status.failed: return sudo("service %s start" % n...
59,207
def test_get_package_folders_epub() -> None: """It gets the package template epub folder""" template_epub_folder = get_package_folders("template_epub") assert template_epub_folder.name == "template_epub"
59,208
def default_main(parser): """ Default entry point implementation """ args = safe_parse_args(parser, sys.argv[1:]) if args.verbose: logging.basicConfig(level=logging.DEBUG) if hasattr(args, 'func'): args.func(args) return args
59,209
def reorder(text): """reorder strings that are in format [title, The] to [The title]""" m = re.match("([\w ]+), The$", text) return "The " + m.group(1) if m else text
59,210
def test_databag_init_ok(): """stale databag values must be updated with per-run settings""" data = api.get_env_databag(root_dir, False, "dev/special") assert data.get("intermediate_databag_file") is not None assert data.get("intermediate_databag_file") != "stale"
59,211
def TNorm(aFuzzyNumber, bFuzzyNumber, normType='logic'): """ T-Norm conjunctive operators. normType is an operator's name: 'logic' - result of fuzzy logic AND (min operator), 'algebraic' - result of algebraic multiplication operation, 'boundary' - result of boundary multiplication op...
59,212
async def test_step_import(hass): """Test that the import step works.""" conf = { CONF_USERNAME: "user@host.com", CONF_PASSWORD: "123abc", } with patch( "homeassistant.components.tile.async_setup_entry", return_value=True ), patch("homeassistant.components.tile.config_flow.a...
59,213
def label_segmentos(rfm): """Función que segmenta los clientes según su Frecuencia y Recencia en 10 grupos. Además se crea un diccionario con los dni's en cada categoría en el intervalo de tiempo analizado. Finalmente genera un barplot con la fracción de clientes en cada categoría. Requiere como argume...
59,214
def register_by_user_type(self, request, current_serializer): """Complementary function for manage register by serializer""" serializer = current_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() data = UserSerializer(user).data return Response(data...
59,215
def table_standardise_units_inplace(table): """Standardise units for all columns in a table in place. """ for column in table.columns.values(): if column.unit: column.unit = standardise_unit(column.unit) return table
59,216
def get_virtual_nodes(glycan, libr = None, reducing_end = ['Glc', 'GlcNAc']): """find unobserved biosynthetic precursors of a glycan\n | Arguments: | :- | glycan (string): glycan in IUPAC-condensed format | libr (list): library of monosaccharides; if you have one use it, otherwise a comprehensive lib will be ...
59,217
def parallel_read(file_patterns, parse_fn, shuffle_filenames=True, num_train_samples_per_task=4, num_val_samples_per_task=4, shuffle_buffer_size=50, filter_fn=None, interleave_cycle_length=None,...
59,218
def rblock(inputs, filters, kernel_size, padding='valid', activation=None, scale=0.1): """Create a scaled Residual block connecting the down-path and the up-path of the u-net architecture Activations are scaled by a constant to prevent the network from dying. Usually is set between 0.1 and 0.3. See: https:...
59,219
def removeLanguageLinks(text: str, site=None, marker: str = '') -> str: """Return text with all inter-language links removed. If a link to an unknown language is encountered, a warning is printed. :param text: The text that needs to be modified. :param site: The site that the text is coming from. ...
59,220
def get_category_articles(start_date: datetime.date, end_date: datetime.date, category: str): """ It iterates daily from the start_date to the end_date downloading the articles This is the method used by the threads. :param start_date: A datetime object with the start date :param end_date: A datetim...
59,221
def unbound_callback(data, status, r): """ Check unbound's response and record the status, score and log (if any) in the callback data. """ data['score'] = data['score_error'] data['log'] = "" if status == 0: log = "" if r.rcode == unbound.RCODE_SERVFAIL: status ...
59,222
def setup_game(save_replay: bool) -> None: """Miscellaneous setup steps.""" const.verify_valid_const_config(const) if save_replay: with open(const.REPLAY_STATE, "w", encoding="utf-8") as replay_file: json.dump({"rng_state": random.getstate()}, replay_file)
59,223
def q_factorial(n, q=None): """ Return the `q`-analogue of the factorial `n!`. If `q` is unspecified, then it defaults to using the generator `q` for a univariate polynomial ring over the integers. EXAMPLES:: sage: from sage.combinat.q_analogues import q_factorial sage: q_factoria...
59,224
def http_upload_files( path: str, token: str, data: dict, files_info: List, domain: str = config.HF_AUTONLP_BACKEND_API, **kwargs ) -> requests.Response: """Uploads files to AutoNLP""" try: response = requests.post( url=domain + path, data=data, files=files_info, ...
59,225
def get_most_purchased_item(user_data: Dict[str, Dict[str, Any]]) -> Tuple[str, Dict[str, int]]: """ Returns the name of the most purchased item. """ return get_most_N_item(user_data, 3)
59,226
def mean(x, axis=None, keepdims=False): """Mean of a tensor, alongside the specified axis. # Arguments x: A tensor or variable. axis: An integer or list of integers in [-rank(x), rank(x)), the axes to compute the mean. If `None` (default), computes the mean over all dime...
59,227
def as_dict_with_keys(obj, keys): """ Convert SQLAlchemy model to list of dictionary with provided keys. """ return [dict((a, b) for (a, b) in zip(keys, item)) for item in obj]
59,228
def get_required_fields(): """ Get required fields for the deployment from UI. Fields required for update only: eventId, rd, deploymentNumber, versionNumber, [lastModifiedTimestamp, deployCruiseInfo, recoverCruiseInfo, ingestInfo] At a minimum, deploymentNumber, versionNumber and (instr...
59,229
def requirements(path=getcwd(), freeze_file=FREEZE_FILE, venv=None): """manage requirements (dependencies) in `requirements.txt` and `upgrade_requirements.txt`""" log(INFO, ICONS["setup"] + "setup environment requirements") code = False if freeze_file and not exists(join(path, freeze_file)): ...
59,230
def filter_df_by_threshold(df: pd.DataFrame, threshold: int, y_col: str='family'): """ Filter rare classes from dataset in a pd.DataFrame Input: df (pd.DataFrame): Must contain at least 1 column with name given by `y_col` threshold (int): Exclude any rows from df that contain a `y_col` ...
59,231
def balloon_tip(title, msg, length): """Pop-up messagebox""" #MessageBox = WindowsBalloonTip() MessageBox.ShowWindow(title, msg, length)
59,232
def canned_elasticsearch(task_vars=None, exec_oc=None): """Create an Elasticsearch check object with stubbed exec_oc method""" check = Elasticsearch(None, task_vars or {}) if exec_oc: check.exec_oc = exec_oc return check
59,233
def get_cupy_tensor_dtype(tensor): """Return the corresponded Cupy dtype given a tensor.""" if isinstance(tensor, cupy.ndarray): return tensor.dtype.type if torch_available(): if isinstance(tensor, torch.Tensor): return TORCH_NUMPY_DTYPE_MAP[tensor.dtype] raise ValueError(f"U...
59,234
def addfunctions(abunch): """add functions to epbunch""" key = abunch.obj[0].upper() # ----------------- # TODO : alternate strategy to avoid listing the objkeys in snames # check if epbunch has field "Zone_Name" or "Building_Surface_Name" # and is in group u'Thermal Zones and Surfaces' # ...
59,235
def maximo_libreria(a: float, b: float) -> float: """Re-escribir utilizando el built-in max. Referencia: https://docs.python.org/3/library/functions.html#max """ return max(a, b)
59,236
def calculate_sensitivity(nex, nbg, alpha): """ Sensitivity calculation using nex/sqrt(nbg) Parameters --------- nex: `float` number of excess events in the signal region nbg: `float` number of events in the background region alpha: `float` inverse of the number of off positions Re...
59,237
def highlight_min(s: pd.Series) -> pd.Series: """Takes a row from pandas series and colors a cell if value in a cell is min value in an entire row""" is_min = s == s.min() return ["background-color: steelblue" if v else "" for v in is_min]
59,238
def sort(li): """ Performs a mini radix sort on the top ten documents by first sorting on document ids, then sorting on document ranking. As sorted() is stable, this ensures that any documents with identical rankings will be sorted on their document ids in increasing order """ ...
59,239
def MULS(product, multiplicand, multiplier): """ args: sum: the register where the addition result is stored. augend: the left operand of the addition. addend: the right operand of the addition. function: Performs basic addition. """ return TacInstruction(instruction...
59,240
def __generic_install(item, force_mode, new_only, check_function, install_function, install_args): """Generic check and caller""" try: # First check if we know about this item if check_function(item.name): log.d(TAG, "Item exists, need to check") ...
59,241
def chord_and_tangent(F, P): """ Use the chord and tangent method to get another point on a cubic. INPUT: - ``F`` -- a homogeneous cubic in three variables with rational coefficients, as a polynomial ring element, defining a smooth plane cubic curve. - ``P`` -- a 3-tuple `(x,y,z)` def...
59,242
def optimize(X, Y, a_prev, parameters, learning_rate = 0.01): """ Execute one step of the optimization to train the model. Arguments: X -- list of integers, where each integer is a number that maps to a character in the vocabulary. Y -- list of integers, exactly the same as X but shifted one in...
59,243
def glob(glob_pattern: str, directoryname: str) -> List[str]: """ Walks through a directory and its subdirectories looking for files matching the glob_pattern and returns a list=[]. :param directoryname: Any accessible folder name on the filesystem. :param glob_pattern: A string like "*.txt", which...
59,244
def _upload_entity_df_into_sqlserver_and_get_entity_schema( engine: sqlalchemy.engine.Engine, config: RepoConfig, entity_df: Union[pandas.DataFrame, str], ) -> EntitySchema: """ Uploads a Pandas entity dataframe into a SQL Server table and constructs the schema from the original entity_df datafr...
59,245
def test_store_decorator(sirang_instance): """Test dstore""" db = 'dstore' collection = 'test' def test_func(arg1, arg2, arg3, arg4): return arg2 # Test inversions no_invert = sirang_instance.dstore( db, collection, keep=['arg1', 'arg2'], inversion=False, doc_id_templat...
59,246
def remove_backups(files, cutoff_time): """Use this tool to remove backups older than given input from a directory. """ def older_than(item): item_time, item = item return item_time < cutoff_time files_to_remove = filter(older_than, files) for item in files_to_remove: date_ti...
59,247
def incsum(prevsum, prevmean, mean, x): """Caclulate incremental sum of square deviations""" newsum = prevsum + abs((x - prevmean) * (x - mean)) return newsum
59,248
def test_transaction_find_active_lookup(session): """Invalid lookup..""" payment_account = factory_payment_account() payment = factory_payment() payment_account.save() payment.save() invoice = factory_invoice(payment.id, payment_account.id) invoice.save() fee_schedule = FeeSchedule.find_...
59,249
def sdate_from_datetime(datetime_object, format='%y-%m-%d'): """ Converts a datetime object to SDATE string. """ return datetime_object.strftime(format)
59,250
def test_async_image_signatures(): """Test async image signatures.""" for method in dir(AsyncImage): if method.startswith('_'): continue method_signature = signature(getattr(AsyncImage, method)).parameters base_signature = signature(getattr(BaseImage, f'_{method}')).parameter...
59,251
def test_not_simplifiable_only_if( assert_errors, parse_ast_tree, comparators, default_options, ): """Statements with only if and empty parent are not simplifiable.""" tree = parse_ast_tree(only_if.format(*comparators)) visitor = IfStatementVisitor(default_options, tree=tree) visitor.ru...
59,252
def test_git_remote(): """Ensure that git remote works. Note that we check both clone URLS since travis uses https to clone rather than ssh.""" repo = GITRepository(REPO_DIR) assert repo.remote() in ("git@github.com:iotile/multipackage.git", "https://github.com/iotile/...
59,253
def zyz(alpha, beta, gamma): """ 3d rotation around z-, y-, z-axis: float, float, float -> (3,3)-array """ return np.dot(z(alpha), np.dot(y(beta), z(gamma)))
59,254
def drcomplete(N,Index,r,p,solver = None, gamma = 1,rho = 1,Z0 = None,tol = None): """ Douglas-Rachford proximal splitting for low-rank completion through the low-rank inducing Frobenius/spectral norm and non-convex Douglas-Rachford for integer-valued r. M,rankM,err,D,Z_fix,iter = D...
59,255
def load_data(database_filepath): """ load data and output features and targets """ # load data from database engine = create_engine('sqlite:///{}'.format(database_filepath)) file_name = database_filepath.split("/")[-1] table_name = file_name.split(".")[0] df = pd.read_sql_table(ta...
59,256
def hpix2radec(nside, hpix): """ Function transforms HEALPix index (ring) to RA, DEC parameters ---------- nside : int hpix : array_like HEALPix indices returns ------- ra : array_like right ascention in deg dec : array_like de...
59,257
def convert_crop_cam_to_orig_img_and_focal(cam, bbox, img_width, img_height, focal=5000., resized_width=224, resized_height=224, new_focal=None): """ Borrow from VIBE """ ''' Convert predicted camera from cropped i...
59,258
def ismember(a, b): """ equivalent of np.isin but returns indices as in the matlab ismember function returns an array containing logical 1 (true) where the data in A is B also returns the location of members in b such as a[lia] == b[locb] :param a: 1d - array :param b: 1d - array :return: is...
59,259
def init_obj_discrete(env_fn_discrete): """ Instantiate a PolicyWithValue class object """ MyNet = PolicyWithValue( policy_net = 'mlp', env = env_fn_discrete, normalize_observations=False ) return MyNet
59,260
def new_norm(graphs_, bl_feat): """Normalize graph function uniformly""" newnorm = dict(zip(bl_feat, [0] * 5)) for attr in bl_feat: for gs in graphs_: for g in gs: tmp = max(nx.get_node_attributes(g, attr).values()) if tmp > newnorm[attr]: ...
59,261
def in6_and(a1, a2): """ Provides a bit to bit AND of provided addresses. They must be passed in network format. Return value is also an IPv6 address in network format. """ return _in6_bitops(a1, a2, 1)
59,262
def get_photon_density_gaussian_cuda( photon_n, elec_Ntot, elec_x, elec_y, elec_z, ct, photon_n_lab_max, inv_laser_waist2, inv_laser_ctau2, laser_initial_z0, gamma_boost, beta_boost ): """ Fill the array `photon_n` with the values of the photon density (in the simulation frame) in the scattering las...
59,263
def send_data(socket_path, data): """Send data to the socket path. The send method takes serialized data and submits it to the given socket path. This method will return information provided by the server in String format. :returns: String """ with UNIXSocketConnect(socket_path) as s...
59,264
def get_manifest(apk_path): """反编译解压apk,获取AndroidManifest.xml文件""" # command = 'apktool d ' + apk_path + ' -o apkshield_tmp' # os.system(command) decompAPK(apk_path) stDisassembleDp = apk_path + "decompile" stAMFp = os.path.join(stDisassembleDp, "AndroidManifest.xml") print("stAMFp:{}...
59,265
def nim(heaps, game_type, output=True): """ Computes next move for Nim, for both game types normal and misere. if there is a winning move: return tuple(heap_index, amount_to_remove) else: return 0, 0 - mid-game scenarios are the same for both game types >>> print(nim([1, 2, 3]...
59,266
def get_positions(p_state, idx_image=-1, idx_chain=-1): """Returns a `numpy.array_view` of `shape(NOS, 3)` with the components of each spins position. Changing the contents of this array_view will have direct effect on the state and should not be done. """ nos = system.get_nos(p_state, idx_image, idx_c...
59,267
def make_get_call(context, use_user_key, uuid): """Make the get call on the user management api.""" context.duration = None start_time = time.time() get_url = urljoin(context.core_v2_api_url, '/user/{}'.format(uuid)) print(get_url) parms = {'user_key': context.three_scale_preview_user_key} ...
59,268
def image_dataset_from_tfrecords(globs, tag, image_shape, batch_size = 0, shuffle = True, repeat = -1): """Loads images from sharded TFRecord files. A...
59,269
def get_writer(_): """ Returns the writer class. """ return LunrWriter
59,270
def test_logo(): """ Plot the GMT logo as a stand-alone plot. """ fig = Figure() fig.logo() return fig
59,271
def decrypt(data, key, iv, guest_padding_size): """Decrypt using AES CBC""" decryptor = AES.new(key, AES.MODE_CBC, IV=iv) # if ValueError AND has correct padding, https://github.com/Legrandin/pycryptodome/issues/10#issuecomment-354960150 if guest_padding_size == 0: # can use as flag bcoz pad with 0 will...
59,272
def SRL32(init=0, has_shiftout=False, has_ce=False): """ Configure a Slice as a 32-bit shift register [I, A[5]] -> O @note: SRL32's can be chained together using SHIFTOUT and SHIFTIN. In that case, an SRL32 does not generate any output. """ if isinstance(init, IntegerTypes): i...
59,273
def compute_peak_valley(rip: DataStream, rip_quality: DataStream, fs: float = 21.33, smoothing_factor: int = 5, time_window: int = 8, expiration_amplitude_threshold_perc: float = 0.10, ...
59,274
def WaveguideConnect(port1: "DevicePort",port2: "DevicePort", rad: float = 3): """ Simple waveguide connector for two ports. Given a start port and an end port, the function attempts to connect the ports using a sequence of straight lines (sequencer command S), 90 degrees bends ...
59,275
def convert_title(original_title): """Remove underscores from string""" new_title = original_title.replace("_", " ").title() new_title = new_title.replace("Api", "API") return new_title
59,276
def our_path(): """ This will get us the program's directory, even if we are frozen using py2exe""" if _are_we_frozen(): return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( ))) return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))
59,277
def type_from_outputs(outputs): """ :param outputs: [ Theano Variable ] :returns: pykit return type """ result_types = [map_type(v.type) for v in outputs] if len(outputs) > 1: result_type = types.Tuple(result_types) else: result_type, = result_types return result_t...
59,278
def analyze_sentiment(text, **kwargs): """ Analyzing Sentiment in a String Args: text_content The text content to analyze """ if not text: return "Syntax: /analyze_sentiment <your text here>" client = language_v1.LanguageServiceClient() # Available types: PLAIN_TEXT, HTML ...
59,279
def abbreviate_for_xray(payload: dict) -> dict: """ If the payload includes a file, the file is translated to just it's name and size instead of including the whole file. """ for k in payload.keys(): v = payload.get(k) if isinstance(v, File): v = {"type": v.type, "siz...
59,280
def trend_plot(df_in, types='day', d_time=None, rotation=True, output_dir=None, display=False, tracking=False): """ Trend plot for the aggregated time series data if the rdd data frame has date features and numerical features. :param df_in: the input rdd data frame :param types: the types for time feat...
59,281
def get_version(release): """ Given x.y.z-something, return x.y On ill-formed return verbatim. """ if '.' in release: sl = release.split(".") return '%s.%s' % (sl[0], sl[1]) else: return release
59,282
def arrays_shape(*arrays): """Returns the shape of the first array that is not None. Parameters ---------- arrays : ndarray Arrays. Returns ------- tuple of int Shape. """ for array in arrays: if array is not None: shape = array.shape ...
59,283
def get_coords_2d(obj, P): """ calculate the image (2d) coordinates of the 3d bounding box of an object. """ bbox3 = get_coords_3d(obj) # Rl = obj.Rl # height = obj.height # width = obj.width # length = obj.length # x = obj.x # y = obj.y # z = obj.z # bbox = np.array(...
59,284
def setPanicProperty(prop, value): """ Method to write global properties It manages compatibility with PANIC <= 6 using PyAlarm properties """ print('setPanicProperty(%s, %s)' % (prop, value)) r = get_tango().get_property('PANIC',[prop])[prop] o = get_tango().get_class_property('PyAlarm',[p...
59,285
def gridSquare(eastings, northings, squaresize): """Returns the appropriate National Grid Reference including 100km letters. eastings: in metres between 0 and 700000 northings: in metres between 0 and 1300000 squaresize: in kilometres, valid values are 100,10,5,1,0.5,0.1,0.01,0.001 """ # check...
59,286
def plot_pr2_bias(data, title='ALANINE', graph_name='pr2_bias.png', \ num_genes='ignored', **kwargs): """Outputs a PR2-Bias plot of: -isotypic transversions (base swapping) with G3/(G3+C3) and A3/(A3+T3) -Transitions (deaminations) with G3/(G3+A3) and C3/(C3+T3) -Allotypic transversions (G- ...
59,287
def _run_cromwell(args): """Run CWL with Cromwell. """ main_file, json_file, project_name = _get_main_and_json(args.directory) work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "cromwell_work")) final_dir = utils.safe_makedir(os.path.join(work_dir, "final")) if args.no_container: _...
59,288
def test_signin_incorrect_password(): """ Incorrect password. """ response = requests.post(URL, headers={'Authorization': 'Basic ' + b64encode(EMAIL + ":testpassword!1")}) print({'Authorization': 'Basic ' + b64encode(EMAIL + ":testpassword!1")}) print(response.status_code) print(response.hea...
59,289
def check_records(server, answer, query, query_type, authority=False, error=None, other_query=None): """ Checks that the A record value & record count matches (if error is None) Otherwise, if error is specified, then it checks to make sure that the error is achieved Optionally, check if the DNS response...
59,290
def findGenSubClasses(superclass): """Find all Generator sub-classes of a certain class, e.g. ODEsystem.""" assert isinstance(superclass, str), \ "findGenSubClasses requires a string as the name of the class to search for subclasses." subclasslist = [] sc = eval(superclass) for x in...
59,291
def delete_cache(package, location): """ Remove selected cached data, please run print_cache() to get path. Parameters ---------- location : str Returns ------- result : boolean """ home, _ = _get_home(package=package) if not isinstance(location, str): raise ValueE...
59,292
def get_artemis_data_path(relative_path ='', make_local_dir = False): """ Get the full local path of a file relative to the Data folder. If the relative path starts with a "/", we consider it to be a local path already. TODO: Make this Windows-friendly :param relative_path: A path relative to the dat...
59,293
def PSQRT(N, C, M, A): """ PSQRT finds the first m + 1 coefficients of the square-root power series $$ (c_0 + c_1 \, z + \cdots + c_n \, z^n) ^{0.5} = a_0 + a_1 \, z + + a_2 \, z^2 + \cdots $$ p. 32 """ A[0] = SQRT(C[0]) TA = 2 * A[0] A[1] = C[1] / TA A[2] = (C[2] - A...
59,294
def check_is_board(riotdir, board): """Verify if board is a RIOT board. :raises ValueError: on invalid board :returns: board name """ if board == 'common': raise ValueError("'%s' is not a board" % board) board_dir = os.path.join(riotdir, 'boards', board) if not os.path.isdir(board_d...
59,295
def overview_command(): """Market data overview [Wall St. Journal]""" # Debug user input if imps.DEBUG: logger.debug("econ-overview") # Retrieve data df = wsj_model.market_overview() # Check for argument if df.empty: raise Exception("No available data found") df["Last ...
59,296
def test_db(test_app): """ Does a database rollback on a function based scope and closes the session after execution is completed. NOTE: when running pytest in parallel (multiple functions at the same time) this way of doing a rolleback it may happend that one test is doing a rolleback while the ot...
59,297
def load_manga(f): """ Load manga object by query manga_id into g.manga """ @wraps(f) def wrapper(manga_id, *args, **kwargs): manga = Manga.query.get(manga_id) if not manga: return jsonify({ 'code': 404, 'message': 'Not Found' }), 4...
59,298
def pln_reflection_basis(pt_coord, pln_pt, pln_normal): """ Symétrie mirroir, en 3D, par rapport à un plan. Le plan est défini par une normale et un point contenu dans ce plan. """ # ? laisser la possibilité d'utiliser directement un np.array ou une liste # ? pour donner les coordonnées pour plu...
59,299