content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _insert_text_func(s, readline): """Creates a function to insert text via readline.""" def inserter(): readline.insert_text(s) readline.redisplay() return inserter
06532be051cb69b92fa79ef339edb733b8f31c15
3,647,300
def dumps(ndb_model, **kwargs): """Custom json dumps using the custom encoder above.""" return NdbEncoder(**kwargs).encode(ndb_model)
0f0a74cdaedd81a95874f745ad1bc24881d1fb73
3,647,301
def classifier_on_rbm_scores(models, dataset_train, dataset_test, clfs=None): """ TODO: store progress on heirarchical clustering; that is the slowest step clfs: list of classifiers """ if clfs is None: clfs = [CLASSIFIER] features_order = list(models.keys()) feature_dim = len(featu...
acea7cdb174dfc61e2ab5f04d295024d6b58d2f4
3,647,302
import inspect def _evolve_no_collapse_psi_out(config): """ Calculates state vectors at times tlist if no collapse AND no expectation values are given. """ global _cy_rhs_func global _cy_col_spmv_func, _cy_col_expect_func global _cy_col_spmv_call_func, _cy_col_expect_call_func num_ti...
a87fe7c21b0bc31599d94845d41384714c0084da
3,647,303
import os def get_version_from_package() -> str: """Read the package version from the source without importing it.""" path = os.path.join(os.path.dirname(__file__), "arcpy2foss/__init__.py") path = os.path.normpath(os.path.abspath(path)) with open(path) as f: for line in f: if lin...
67b0374794ede6c13560265ab3e6ebf3c5b2aef3
3,647,304
def create_critic_train_op(hparams, critic_loss, global_step): """Create Discriminator train op.""" with tf.name_scope('train_critic'): critic_optimizer = tf.train.AdamOptimizer(hparams.critic_learning_rate) output_vars = [ v for v in tf.trainable_variables() if v.op.name.startswith(...
4c33ba79dacebff375971c123e5bbafd34f5ab91
3,647,305
def interpolate(data, tstep): """Interpolate limit order data. Uses left-hand interpolation, and assumes that the data is indexed by timestamp. """ T, N = data.shape timestamps = data.index t0 = timestamps[0] - (timestamps[0] % tstep) # 34200 tN = timestamps[-1] - (timestamps[-1] % tstep)...
ae1fde01529a4d11ea864b0f5757c9cde096a142
3,647,306
def doColorTransfer(org_content, output, raw_data, with_color_match = False): """ org_content path or 0-1 np array output path or 0-1 np array raw_data boolean | toggles input """ if not raw_data: org_content = imageio.imread(org_content, pilmode="RGB").astype(float)/256 output = imageio.imrea...
8af9d8dc199fb4b111da619e4dbc935b2514c5b7
3,647,307
def tb_filename(tb): """Helper to get filename from traceback""" return tb.tb_frame.f_code.co_filename
75ac527b928d605f1dfc2b5034da6ab7e193fb82
3,647,308
async def fetch_symbol(symbol: str): """ get symbol info """ db = SessionLocal() s = db.query(SymbolSchema).filter(SymbolSchema.symbol == symbol).first() res = {"symbol": s.symbol, "name": s.name} return res
6e6a1e4e92ba7796f1893d3144cbdcc75bee6bbe
3,647,309
from typing import List def all_live_response_sessions(cb: CbResponseAPI) -> List: """List all LR sessions still in server memory.""" return [sesh for sesh in cb.get_object(f"{CBLR_BASE}/session")]
e4ea25c8d38e90e8048f6a5c220e5f413ce59da6
3,647,310
def unserialize_model_params(bin: bin): """Unserializes model or checkpoint or diff stored in db to list of tensors""" state = StatePB() state.ParseFromString(bin) worker = sy.VirtualWorker(hook=None) state = protobuf.serde._unbufferize(worker, state) model_params = state.tensors() return mo...
a1cad2172029b7e622486d50de73a7c87aaca9c0
3,647,311
def config(clazz): """Decorator allowing to transform a python object into a configuration file, and vice versa :param clazz: class to decorate :return: the decorated class """ return deserialize(serialize(dataclass(clazz)))
a5386d53c596b77355ee8e5067a0e1c8b4efb89e
3,647,312
import functools def wrap_method_once(func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: """manage Runnable state for given method""" # we don't re-wrap methods that had the state management wrapper if hasattr(func, 'handler_wrapped'): return func @functools.wraps(func) def wrapped_...
cf26f642f09fe5d4b54073eeda4ab7beb03ed538
3,647,313
from re import T async def all(iterable: ty.AsyncIterator[T]) -> bool: """Return ``True`` if **all** elements of the iterable are true (or if the iterable is empty). :param iterable: The asynchronous iterable to be checked. :type iterable: ~typing.AsyncIterator :returns: Whether all elements o...
92c8c20d75318a0b0353ede9641c59d9337c60f6
3,647,314
def _safe_isnan(x): """Wrapper for isnan() so it won't fail on non-numeric values.""" try: return isnan(x) except TypeError: return False
7f4cb2e2f4c3e4ee9d66e6d8dbb73dcac5f343f0
3,647,315
def get_system( context, system_id = None ): """ Finds a system matching the given identifier and returns its resource Args: context: The Redfish client object with an open session system_id: The system to locate; if None, perform on the only system Returns: The system resource...
7127a5cf0df89ba5832b7328746d29ef34c12c3e
3,647,316
import math def cartesian_to_polar(x, y, xorigin=0.0, yorigin=0.0): """ Helper function to convert Cartesian coordinates to polar coordinates (centred at a defined origin). In the polar coordinates, theta is an angle measured clockwise from the Y axis. :Parameters: x: float X co...
3fcbb0fc18b9c8d07bc1394995600fd354ee3c75
3,647,317
def keypoint_dict_to_struct(keypoint_dict): """ parse a keypoint dictionary form into a keypoint info structure """ keypoint_info_struct = KeypointInfo() if 'keypoints' in keypoint_dict: for k in keypoint_dict['keypoints']: keypoint = keypoint_info_struct.keypoints.add() key...
d805e6fbac9df7a3a8d7d7f73a03f63a2a4149d1
3,647,318
def softmax_regression(img): """ 定义softmax分类器: 只通过一层简单的以softmax为激活函数的全连接层,可以得到分类的结果 Args: img -- 输入的原始图像数据 Return: predict -- 分类的结果 """ predict = paddle.layer.fc( input=img, size=10, act=paddle.activation.Softmax()) return predict
0c522589a2130bbba512d557695f432eea50ef48
3,647,319
from typing import Optional from typing import Union from typing import Tuple def incremental_quality( wavelength: ndarray, flux: ndarray, *, mask: Optional[Union[Quantity, ndarray]] = None, percent: Union[int, float] = 10, **kwargs, ) -> Tuple[ndarray, ndarray]: """Determine spectral qual...
69f7966af1bec5cde40d62e42346a28475c120f6
3,647,320
import platform def get_platform(): """Gets the users operating system. Returns: An `int` representing the users operating system. 0: Windows x86 (32 bit) 1: Windows x64 (64 bit) 2: Mac OS 3: Linux If the operating system is unknown, -1 will be ...
2d77b76e7a7010dc1f104e83a7a042b7b7542954
3,647,321
def count_number_of_digits_with_unique_segment_numbers(displays: str) -> int: """Counts the number of 1, 4, 7 or 8s in the displays.""" displays = [Display.from_string(d) for d in displays.splitlines()] num_digits = 0 for display in displays: num_digits += sum(len(c) in (2, 3, 4, 7) for c in dis...
df9731371066cc89445fd5eeb94f40624cf24a2f
3,647,322
def svo_filter_url(telescope, photofilter, zeropoint='AB'): """ Returns the URL where the filter transmission curve is hiding. Requires arguments: telescope: SVO-like name of Telescope/Source of photometric system. photofilter: SVO-like name of photometric filter. Optional: ...
e3cbe6a3192fcc890fb15df8fc3c02620a7c69fb
3,647,323
def calculate_sampling_rate(timestamps): """ Parameters ---------- x : array_like of timestamps, float (unit second) Returns ------- float : sampling rate """ if isinstance(timestamps[0], float): timestamps_second = timestamps else: try: v_parse_date...
0554866b55eb9310c64399819d8d3978108d5e1a
3,647,324
def compute_ss0(y, folds): """ Compute the sum of squares based on null models (i.e., always predict the average `y` of the training data). Parameters ---------- y : ndarray folds : list of ndarray Each element is an ndarray of integers, which are the indices of members of the fold. ...
e546404eaa2637cc8073ddc0654f42987a07d972
3,647,325
import glob def read_logging_data(folder_path): """ Description:\n This function reads all csv files in the folder_path folder into one dataframe. The files should be in csv format and the name of each file should start with 'yrt' and contain '_food_data' in the middle. For example, yrt1999_food_data1...
964ad379eb70083b6a696655b22c77a2c61d101f
3,647,326
def get_user_strlist_options(*args): """ get_user_strlist_options(out) """ return _ida_kernwin.get_user_strlist_options(*args)
71c637c1d663d685ffd7e5fd5bba8cba04b18535
3,647,327
import torch def coord_sampler(img, coords): """ Sample img batch at integer (x,y) coords img: [B,C,H,W], coords: [B,2,N] returns: [B,C,N] points """ B,C,H,W = img.shape N = coords.shape[2] batch_ref = torch.meshgrid(torch.arange(B), torch.arange(N))[0] out = img[batch_ref...
d4a1ac6125d11381933d59190074f33bd9a7e774
3,647,328
import os def directory(name, *args): """ Returns the directory with the specified name, as an absolute path. :param name: The name of the directory. One of "textures" or "models". :args Elements that will be appended to the named directory. :return: The full path of the named directory. """ ...
61a8b4014f11fa449d455b941f032b415c393186
3,647,329
def adapt_ListOfX(adapt_X): """This will create a multi-column adapter for a particular type. Note that the type must itself need to be in array form. Therefore this function serves to seaprate out individual lists into multiple big lists. E.g. if the X adapter produces array (a,b,c) then this ...
15a6ada60c3b78110097c29222c245225a2669b9
3,647,330
def add_sighting(pokemon_name): """Add new sighting to a user's Pokédex.""" user_id = session.get('user_id') user = User.query.get_or_404(user_id) pokemon = Pokemon.query.filter_by(name=pokemon_name).first_or_404() # 16% chance logging a sighting of a Pokémon with ditto_chance = True will ...
cbc078b71d31bb40f582731341aefd89e23f26dc
3,647,331
def edit_colors_names_group(colors, names): """ idx map to colors and its names. names index is 1 increment up based on new indexes (only 0 - 7) """ # wall colors[0] = np.array([120, 120, 120], dtype = np.uint8) names[1] = 'wall' # floor colors[1] = np.array([80, 50, 50], dtype = np....
45e6977b2ff4339417900d31d8bd22e9c5d934d8
3,647,332
def semidoc_mass_dataset(params, file_names, num_hosts, num_core_per_host, seq_len, num_predict, is_training, use_bfloat16=False, ...
9c5809268931c1235bdd32c40f89781b05f387ae
3,647,333
def ListChrootSnapshots(buildroot): """Wrapper around cros_sdk --snapshot-list.""" cmd = ['cros_sdk', '--snapshot-list'] cmd_snapshots = RunBuildScript( buildroot, cmd, chromite_cmd=True, stdout=True) return cmd_snapshots.output.splitlines()
5ae25b11dd0dba39834411a05c095fd38ea70494
3,647,334
import httpx import asyncio async def post_github_webhook( request: Request, logger: BoundLogger = Depends(logger_dependency), http_client: httpx.AsyncClient = Depends(http_client_dependency), arq_queue: ArqQueue = Depends(arq_dependency), ) -> Response: """Process GitHub webhook events.""" if...
56326d3084f1b525776a923bc76a1a1f1959b6f6
3,647,335
import os import stat import json def _load_cache(b_cache_path): """ Loads the cache file requested if possible. The file must not be world writable. """ cache_version = 1 if not os.path.isfile(b_cache_path): display.vvvv("Creating Galaxy API response cache file at '%s'" % to_text(b_cache_path)) ...
17496359e4958e3059ef7a4b4fcaeaf474037fdc
3,647,336
def nmad_filter( dh_array: np.ndarray, inlier_mask: np.ndarray, nmad_factor: float = 5, max_iter: int = 20, verbose: bool = False ) -> np.ndarray: """ Iteratively remove pixels where the elevation difference (dh_array) in stable terrain (inlier_mask) is larger \ than nmad_factor * NMAD. Iterations w...
74275be5223531bc7cfc3f788cb562104514996c
3,647,337
def setup_output_vcf(outname, t_vcf): """ Create an output vcf.Writer given the input vcf file as a templte writes the full header and Adds info fields: sizeCat MEF Returns a file handler and a dict with {individual_id: column in vcf} """ out = open(outname, 'w') line = t...
82870c9c8d46dbe3161c434a87fac9108ed644b2
3,647,338
import os import json def load_json_file(): """loads the json file""" dirname = os.path.dirname(os.path.abspath(__file__)) json_filepath = os.path.join(dirname, "rps101_data.json") with open(json_filepath) as f: json_load = json.load(f) return json_load
9bd4b77167af6fc84d05b1766470a165d3ee6bd1
3,647,339
def validate_processing_hooks(): """Validate the enabled processing hooks. :raises: MissingHookError on missing or failed to load hooks :raises: RuntimeError on validation failure :returns: the list of hooks passed validation """ hooks = [ext for ext in processing_hooks_manager()] enabled =...
2d76fb003a3e960c86e342f057ee5a9ea0a77def
3,647,340
def rnn_stability_loss(rnn_output, beta): """ REGULARIZING RNNS BY STABILIZING ACTIVATIONS https://arxiv.org/pdf/1511.08400.pdf :param rnn_output: [time, batch, features] :return: loss value """ if beta == 0.0: return 0.0 # [time, batch, features] -> [time, batch] l2 = tf.sqr...
55dcc6461c7dcc683ae5a3b2d642ed9172616c8b
3,647,341
import os import pprint import google def import_csv_to_calendar_api(): """The main route of the Project.\ If requested with a GET: renders the page of the import operation. If requested with POST: Starts importing events in the file to be uploaded present in the POST data. """ if request....
3205b303ec0c17b303fd6da5993880e3515564bb
3,647,342
def xproto_fields(m, table): """ Generate the full list of models for the xproto message `m` including fields from the classes it inherits. Inserts the special field "id" at the very beginning. Each time we descend a new level of inheritance, increment the offset field numbers by 100. The base ...
fffcbb99cf7ff851dde77fee3f16046e0e71582d
3,647,343
def create_decomp_expand_fn(custom_decomps, dev, decomp_depth=10): """Creates a custom expansion function for a device that applies a set of specified custom decompositions. Args: custom_decomps (Dict[Union(str, qml.operation.Operation), Callable]): Custom decompositions to be applied b...
f7a4682bae3b520dcce87e715834439311e7d8b6
3,647,344
from typing import Dict from typing import List def get_lats_map(floor: float, ceil: float) -> Dict[int, List[float]]: """ Get map of lats in full minutes with quarter minutes as keys. Series considers lat range is [-70;69] and how objects are stored in s3. """ full = full_minutes([floor, cei...
e2bc82e509372d0ed20483a7ac97c5bbfbc9e2d5
3,647,345
from typing import Dict from typing import Any def format_dict(body: Dict[Any, Any]) -> str: """ Formats a dictionary into a multi-line bulleted string of key-value pairs. """ return "\n".join( [f" - {k} = {getattr(v, 'value', v)}" for k, v in body.items()] )
b3f66d086284772e6783b8281f4d46c3dd6c237d
3,647,346
def block3(x, filters, kernel_size=3, stride=1, groups=32, conv_shortcut=True, name=None): """A residual block. # Arguments x: input tensor. filters: integer, filters of the bottleneck layer. kernel_size: default 3, kernel size of the bottleneck layer. stride: default...
e04c2bd5662991203f5b3d86652d2469e06bd346
3,647,347
import time def random_sleep(n): """io""" time.sleep(2) return n
f626a2e64a266084f33a78dd9be4e4528ff88934
3,647,348
from typing import Concatenate def yolo2_mobilenet_body(inputs, num_anchors, num_classes, alpha=1.0): """Create YOLO_V2 MobileNet model CNN body in Keras.""" mobilenet = MobileNet(input_tensor=inputs, weights='imagenet', include_top=False, alpha=alpha) # input: 416 x 416 x 3 # mobilenet.output ...
8938a226857ada5fe621c7206d99b32fcd36ee0f
3,647,349
def LeastSquare_nonlinearFit_general( X, Y, func, func_derv, guess, weights=None, maxRelativeError=1.0e-5, maxIteratitions=100, ): """Computes a non-linear fit using the least square method following: http://ned.ipac.caltech.edu/level5/Stetson/Stetson2_2_1.html It takes the follo...
255c5d11607aa13d1ab7d7ea28fbcd95396669e0
3,647,350
def _get_extracted_csv_table(relevant_subnets, tablename, input_path, sep=";"): """ Returns extracted csv data of the requested SimBench grid. """ csv_table = read_csv_data(input_path, sep=sep, tablename=tablename) if tablename == "Switch": node_table = read_csv_data(input_path, sep=sep, tablename="...
81368b79bb737c24d4f614ebd8aff76ff9efcac0
3,647,351
def has_prefix(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid. :return: (bool) If there is any words with prefix stored in sub_s. """ for word in vocabulary_list: if word.strip().startswith(sub_s): return True # Check all vocabularies in dictionary...
4a99a3437a954173a7f4fe87ccd8970a59632aa8
3,647,352
def work_out_entity(context,entity): """ One of Arkestra's core functions """ # first, try to get the entity from the context entity = context.get('entity', None) if not entity: # otherwise, see if we can get it from a cms page request = context['request'] if request.curr...
8cc1039d8611aa03d8e2d1f708339d87845d0381
3,647,353
def rectify(link:str, parent:str, path:str): """A function to check a link and verify that it should be captured or not. For e.g. any external URL would be blocked. It would also take care that all the urls are properly formatted. Args: **link (str)**: the link to rectify. **parent (str)**: the complete url of ...
6ca5771fcbbb35fe6d99bab65082d447299bb93a
3,647,354
def nested_pids_and_relations(app, db): """Fixture for a nested PIDs and the expected serialized relations.""" # Create some PIDs and connect them into different nested PID relations pids = {} for idx in range(1, 12): pid_value = str(idx) p = PersistentIdentifier.create('recid', pid_valu...
b8039318ffa96f5f42cc7398398b761febf06349
3,647,355
def indentsize(line): """Return the indent size, in spaces, at the start of a line of text.""" expline = line.expandtabs() return len(expline) - len(expline.lstrip())
c1f307adfeb2c1ec51c5e926a0b87dd3841e1aff
3,647,356
import os def reprocess_subtitle_file(path, max_chars=30, max_stretch_time=3, max_oldest_start=10): """Combine subtitles across a time period""" file_name, ext = os.path.splitext(path) compressed_subtitle_file = file_name + '.ass' subs = pysubs2.load(path) compressed_subs = compress(subs, max_char...
241454ffc83564a402635d2d47c18c8c8df07561
3,647,357
import os def load(dataFormat,path,ignoreEntities=[],ignoreComplexRelations=True): """ Load a corpus from a variety of formats. If path is a directory, it will try to load all files of the corresponding data type. For standoff format, it will use any associated annotations files (with suffixes .ann, .a1 or .a2) ...
dc60c4c91e34a6693877aa086824dd5c44d0b957
3,647,358
import os import codecs def read(*parts): """ Build an absolute path from *parts* and return the contents of the resulting file. Assumes UTF-8 encoding. """ here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, *parts), "rb", "utf-8") as f: return f.rea...
d19885ee8e1c9889ac6c3c0daff50dac8ce00aa6
3,647,359
import warnings def read_idl_catalog(filename_sav, expand_extended=True): """ Read in an FHD-readable IDL .sav file catalog. Deprecated. Use `SkyModel.read_fhd_catalog` instead. Parameters ---------- filename_sav: str Path to IDL .sav file. expand_extended: bool If True,...
77680e111c9f67b628cd1da5eac26afcb036374b
3,647,360
import struct def guid2bytes(s): """Converts a GUID to the serialized bytes representation""" assert isinstance(s, str) assert len(s) == 36 p = struct.pack return b"".join([ p("<IHH", int(s[:8], 16), int(s[9:13], 16), int(s[14:18], 16)), p(">H", int(s[19:23], 16)), p(">Q"...
f298497173f9011392b671267cb47f081d25a9da
3,647,361
import functools def config(config_class=None, name="config", group=None): """ Class decorator that registers a custom configuration class with `Hydra's ConfigStore API <https://hydra.cc/docs/tutorials/structured_config/config_store>`_. If defining your own custom configuration class, your class must...
6e3828c51835f8a9a9ed3afc4b5d9606d8ba9e50
3,647,362
def truncate_words(text, max_chars, break_words=False, padding=0): """ Truncate a string to max_chars, optionally truncating words """ if break_words: return text[:-abs(max_chars - len(text)) - padding] words = [] for word in text.split(): length = sum(map(len, words)) + len(wo...
b239822fd1cef6c2e3f7425a0ad5cbc32b8b1325
3,647,363
def interpolate_mean_tpr(FPRs=None, TPRs=None, df_list=None): """ mean_fpr, mean_tpr = interpolate_mean_tpr(FPRs=None, TPRs=None, df_list=None) FPRs: False positive rates (list of n arrays) TPRs: True positive rates (list of n arrays) df_list: DataFrames with TPR, FPR columns (list of n D...
47f53c0f5010620bf54119a0f35eff13143fa960
3,647,364
def _generate_copy_from_codegen_rule(plugin, target_name, thrift_src, file): """Generates a rule that copies a generated file from the plugin codegen output directory out into its own target. Returns the name of the generated rule. """ invoke_codegen_rule_name = _invoke_codegen_rule_name( plugin...
652fad4701299d031fd6258ce4d2d8b097af3406
3,647,365
def mir_right(data): """ Append Mirror to right """ return np.append(data[...,::-1],data,axis=-1)
7daa6b4c70e80fcbeda894b7ff358b44149edf22
3,647,366
def mask_nms(masks, bbox_scores, instances_confidence_threshold=0.5, overlap_threshold=0.7): """ NMS-like procedure used in Panoptic Segmentation Remove the overlap areas of different instances in Instance Segmentation """ panoptic_seg = np.zeros(masks.shape[:2], dtype=np.uint8) sorted_inds = li...
92465752e741fffb04ea1a243dd465799daf6598
3,647,367
def table_to_lookup(table): """Converts the contents of a dynamodb table to a dictionary for reference. Uses dump_table to download the contents of a specified table, then creates a route lookup dictionary where each key is (route id, express code) and contains elements for avg_speed, and historic_spee...
97a95a2e06e81907d2d1091e2ebf41a26808653a
3,647,368
def _initialize_weights(variable_scope, n_head, n_input, n_hidden): """ initialize the weight of Encoder with multiple heads, and Decoder """ with tf.variable_scope(variable_scope, reuse=tf.AUTO_REUSE): all_weights = dict() ## forward, Each head has the same dimension ad n_hidden ...
d7950218d9b76c12fd3dbad54bf30286ec2d3b94
3,647,369
import time def sh(cmd, stdin="", sleep=False): """ run a command, send stdin and capture stdout and exit status""" if sleep: time.sleep(0.5) # process = Popen(cmd.split(), stdin=PIPE, stdout=PIPE) process = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE) process.stdin.write(bytes(stdin, "...
22db066b2e4b429b1756bf00d4592359c79939cd
3,647,370
def array_to_slide(arr: np.ndarray) -> openslide.OpenSlide: """converts a numpy array to a openslide.OpenSlide object Args: arr (np.ndarray): input image array Returns: openslide.OpenSlide: a slide object from openslide """ assert isinstance(arr, np.ndarray) slide = op...
83a5d2def7a0626a24396b933bd984a6de7ae634
3,647,371
from typing import Sequence import copy def baseline_replacement_by_blur(arr: np.array, patch_slice: Sequence, blur_kernel_size: int = 15, **kwargs) -> np.array: """ Replace a single patch in an array by a blurred version. Blur is performed via a 2D convolution. blur_k...
5e5f25eeff3caebbdd8c9612fb26d23a11e3f80e
3,647,372
def admit_dir(file): """ create the admit directory name from a filename This filename can be a FITS file (usually with a .fits extension or a directory, which would be assumed to be a CASA image or a MIRIAD image. It can be an absolute or relative address """ loc = file.rfind('.') ext = '...
16d4b32b3994a3a260556b984e86e6507cad581b
3,647,373
def grad(values: list[int], /) -> list[int]: """Compute the gradient of a sequence of values.""" return [v2 - v1 for v1, v2 in zip(values, values[1:])]
a1df1dffb27028dc408b00ec8ac26b6f68d9c923
3,647,374
from typing import Union def subtract( num1: Union[int, float], num2: Union[int, float], *args ) -> Union[int, float]: """Subtracts given numbers""" sub: Union[int, float] = num1 - num2 for num in args: sub -= num return sub
55db772fdcdc9aa24fd61069a3adcd6bc7abe468
3,647,375
import pkgutil import importlib def get_submodules(module): """ Attempts to find all submodules of a given module object """ _skip = [ "numpy.f2py", "numpy.f2py.__main__", "numpy.testing.print_coercion_tables", ] try: path = module.__path__ except Exception:...
214b2aa0551e59a11bd853791ec64e9a238fd155
3,647,376
import inspect import hashlib def ucr_context_cache(vary_on=()): """ Decorator which caches calculations performed during a UCR EvaluationContext The decorated function or method must have a parameter called 'context' which will be used by this decorator to store the cache. """ def decorator(f...
85c6b511761eddb74c8a856f9d2c2f1029cba8b2
3,647,377
def extract_value(item, key): """Get the value for the given key or return an empty string if no value is found.""" value = item.find(key).text if value is None: value = "" else: value = sanitize_value(value) return value
228115b77b0298bb808dcbb0dbd89a0938f0feef
3,647,378
def create_train_test_split(data: pd.DataFrame, split_size: float = .8, seed: int = 42) -> list: """ takes the final data set and splits it into random train and test subsets. Returns a list containing train-test split of inputs Args: ...
49a5a07e5f232106d502eaf2f9d9021644f37e27
3,647,379
def get_vec(text, model, stopwords): """ Transform text pandas series in array with the vector representation of the sentence using fasttext model """ array_fasttext = np.array([sent2vec(x, model, stopwords) for x in text]) return array_fasttext
9c28cf8cd2c6acea3f81a5290d6f6c9fd027a6ca
3,647,380
from typing import Tuple import math def rytz_axis_construction(d1: Vector, d2: Vector) -> Tuple[Vector, Vector, float]: """ The Rytz’s axis construction is a basic method of descriptive Geometry to find the axes, the semi-major axis and semi-minor axis, starting from two conjugated half-diameters. S...
14fec51fa1591e74553e6918187dfb850ae4b6f0
3,647,381
def _join_ljust(words, width=9): """join list of str to fixed width, left just""" return ' '.join(map(lambda s: s.ljust(width), words)).strip()
6096f5be960fb0ae2fe942c9b55924802094db16
3,647,382
def construct_dictionaries(color,marker,size, scatter_ecolor='k', alpha=1.0, fill_scatter=False, elinewidth=1,capsize=0): """ Example usage: halo_kws = construct_dictionaries('k','o', 20, alpha=.3) ...
6741dd1ffacc3a10953f86ccdaf53d1d3504a77c
3,647,383
from datetime import datetime import os def to_file(exp_dir, chain): """Write results to file :param exp_dir: directory to export :param chain: Chain object :raise RoutineErr: on file I/O error :return True: on success """ now = datetime.datetime.today().strftime('%Y%m%d-%H%M%S-%f') ...
782c452d1a17e6b63a443e7f388923602fbef12b
3,647,384
def arrows(m) -> str: """One or more arrows separate by a space""" return m.arrow_list
3fb43d9d753f667148bb9bb18eb026f7385d6264
3,647,385
def hex2int(hex_str): """ Convert 2 hex characters (e.g. "23") to int (35) :param hex_str: hex character string :return: int integer """ return int(hex_str, 16)
0640cffd6f7558f4dfd1bc74e20510e7d2051ca3
3,647,386
def lat_2_R(lat): """Takes a geodetic latitude and puts out the distance from the center of an ellipsoid Earth to the surface Arguments: lat (float): Geodetic Latitude angle [degrees]. Returns: (float): Geocentric distance [km] """ R_polar = 6356.752314245 R_eq = 6378.137 ...
aa4f24ccb8a82bad1e6d9fc49f7e2984874ee78b
3,647,387
def compare_records(old_list, new_list): """Compare two lists of SeqRecord objects.""" assert isinstance(old_list, list) assert isinstance(new_list, list) assert len(old_list) == len(new_list) for old_r, new_r in zip(old_list, new_list): if not compare_record(old_r, new_r): retur...
6b70115f9db52898849fa065eff6ed827eab1e16
3,647,388
def embed_owners_wallet(address, asset_name) -> Embed: """Return discord embed of wallet owner""" title = f"{asset_name} is owned by" description = f"`{address}`" color = Colour.blurple() embed = Embed(title=title, description=description, color=color) name = "This address belongs to wallet......
016039acbdf264e5389d3e4f94153345226d2549
3,647,389
def Qdist_H_lm_jk_FGH(a, b, c , d, N_x, N_y, h, par, model): """ Parameters ---------- a : TYPE left end point of the interval in x coordinate chosen for solving the time independent schrodinger equation. b : TYPE right end point of the interval in x coordinate chosen for solvi...
f67c369f5eadd273afa3a2af7cf9d9b274d7a994
3,647,390
from django.core.exceptions import ObjectDoesNotExist from physical.models import Host from backup.models import LogConfiguration def get_log_configuration_retention_backup_log_days(host_id): """Return LOG_CONFIGURATION_RETENTION_BACKUP_LOG_DAYS""" try: host = Host.objects.get(id=host_id) dat...
02ed8a863fd383c15eb25c37553a7b521a2b27fe
3,647,391
def createLabelsAndWeightsFromRois(image, roiimage): """Create class labels and instance labels. Args: image: input image roiimage: input mask image Returns: classlabelsdata, instancelabelsdata, total_instances """ logger.info("Creating class and instance labels ...") ...
747a99c9a1e27666dfc5f6aa73394d86ee4e7a19
3,647,392
def dup_inner_refine_complex_root(f, x, y, dx, dy, F, K): """One bisection step of complex root refinement algorithm. """ hx, hy = dx/2, dy/2 cx, cy = x + hx, y + hy F1, F2, F3, F4 = F Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy = _dup_inner_sturm(f, K.zero, K.one, cx, cy, K) ...
c45e1deba1ad68fb9a85a2e46ca4e3c7eddb072d
3,647,393
def print_dataset_info(superclasses, subclass_splits, label_map, label_map_sub): """ Obtain a dataframe with information about the superclasses/subclasses included in the dataset. Args: superclasses (list): WordNet IDs of super...
6885eecfaa38f609957b6ccfa594701f77ea1b30
3,647,394
def mock_sync_cavatica_account(mocker): """ Mocks out sync Cavatica account functions """ sync_cavatica_account = mocker.patch( "creator.projects.cavatica.sync_cavatica_account" ) sync_cavatica_account.return_value = [], [], [] return sync_cavatica_account
27a0a8abee2c025fe17ba4fa4a939bcf04fc9c63
3,647,395
def check_illegal(s): """ :param s: (String) user input :return: (Bool) check user input is illegal or not """ check = 0 for ch in s: if len(ch) > 1: check = 1 if check == 0: return True else: print("Illegal input") return False
6c028f03ae6f317e7fea020e2da1f35b93d3bcd7
3,647,396
def phasefold(time, rv, err, period): """Phasefold an rv timeseries with a given period. Parameters ---------- time : array_like An array containing the times of measurements. rv : array_like An array containing the radial-velocities. err : array_like An array containing ...
c0076fd49fa9c97fa90419f6f2d42d78c09f0f2e
3,647,397
def get_att_mats(translate_model): """ Get's the tensors representing the attentions from a build model. The attentions are stored in a dict on the Transformer object while building the graph. :param translate_model: Transformer object to fetch the attention weights from. :return: """ ...
d6c7f0d214c444250210c926b2407405e8e34807
3,647,398
def get_resource_string(package, resource): """Return a string containing the contents of the specified resource. If the pathname is absolute it is retrieved starting at the path of the importer for 'fullname'. Otherwise, it is retrieved relative to the module within the loader. """ provider, ...
e0e76f912e02d30645b646e076c10cbd5016a600
3,647,399