content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def open_sciobj_file_by_path(abs_path, write=False): """Open a SciObj file for read or write. If opened for write, create any missing directories. For a SciObj stored in the default SciObj store, the path includes the PID hash based directory levels. This is the only method in GMN that opens SciObj fil...
8c5852de544be21c61636df03ddb681a6c084310
27,853
def mps_to_kmh(speed_in_mps): """Convert from kilometers per hour to meters per second Aguments: speed_in_mps: a speed to convert Returns: speed_in_kmh: a speed in m/s """ return speed_in_mps / 1000.0 * 3600.0
5a37cbca17f8262043b7e1cb2b193b4c9d146766
27,854
import logging def tokenize_and_remove_stopwords(txt,additional_stopwords): """ Runs tokenization and removes stop words on the specified text Parameters ----------- txt: text to process additional_stopwords: path to file containing possible additional stopwords on each line Returns ...
a118747bbd030e37ee0ed5f421f56390e1bd5b38
27,855
async def async_setup_entry(hass, config_entry, async_add_entities): """Add the Wiser System Switch entities.""" data = hass.data[DOMAIN][config_entry.entry_id][DATA] # Get Handler # Add Defined Switches wiser_switches = [] for switch in WISER_SWITCHES: if switch["type"] == "room": ...
5a83f0888fadab08c573378dce4167f2d01478c1
27,856
def get_keep_dice_check(input_prompt): """ Enables returning a yes or no response to an input prompt. :param input_prompt: String yes no question. """ return pyip.inputYesNo(prompt=input_prompt)
c7b8a1392c3e17a1acba615079848245a1b6e167
27,857
import sh def get_pending_jobs(sort=True): """Obtains the list of currently pending (queued) jobs for the user.""" username = getusername() # see squeue man page for status code (%t specifier) listjob = sh.pipe_out(("squeue", "-u", username, "--noheader", "--format=%i %t"), split=True) rslt = [] # treat o...
5b03917885f8a09463c65a456c251cf753abdae2
27,858
def getOverlapRange(rangeA, rangeB): """ Calculate the overlapping range between rangeA and rangeB. Args: rangeA (list, tuple): List or tuple containing start and end value in float. rangeB (list, tuple): List or tuple containing start and end value in float. Retu...
5f3bd22f5ec317d2bde87c92b027f658a80431fb
27,859
def multiply_values(dictionary: dict, num: int) -> dict: """Multiplies each value in `dictionary` by `num` Args: dictionary (dict): subject dictionary num (int): multiplier Returns: dict: mapping of keys to values multiplied by multiplier """ return ( {key: value * ...
16eb87d60da64d648113858ba5cb4308137e0a14
27,860
def send_alarm(address, email_type, template_data={}): """ Send an email message to the given email address immediately, bypassing any queues or database system. :param address: The email address to send this message to. :param email_type: str defining this email template e.g EMAIL_WELCOME. Defined in e...
2564a3d5c27f092e3e940d907b2cc2bc986257c2
27,861
def serialize_curve_point(p: Point) -> bytes: """ Serialize an elliptic curve point ``p`` in compressed form as described in SEC1v2 (https://secg.org/sec1-v2.pdf) section 2.3.3. Corresponds directly to the "ser_P(P)" function in BIP32 (https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#...
9e002df4b18245cb4ce54f1aede5687279aae5bb
27,862
def gcom_so_config(revision=None): """ Create a shared object for linking. """ config = BuildConfig( project_label=f'gcom shared library {revision}', source_root=gcom_grab_config(revision=revision).source_root, steps=[ *common_build_steps(fpic=True), Link...
ddcd625cd1393b38e1871f46a2f1b8738a904f1f
27,863
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"): """ Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$") "...
4c058afdb03b9d85a32e654f83beec95b72785ee
27,864
def get_basic_details(args, item): """ :param args: { "item_code": "", "warehouse": None, "doctype": "", "name": "", "project": "", warehouse: "", update_stock: "", project: "", qty: "", stock_qty: "" } :param item: `item_code` of Item object :return: frappe._dict """ if not item:...
6ddd7f3249d55a073d57c466e8994c1ccf8b1aa7
27,865
def validate_standard_json(json_to_test: dict) -> bool: """ validate fixed json against schema """ valid_json_flag = False schema_to_use = get_standard_json_schema() valid_json_flag = validate_json(json_to_test, schema_to_use, True) return valid_json_flag
97004d7f5e4758dedeaa4ecaf0ee4a67955336c9
27,866
from typing import Any def desg_to_prefix(desg: str) -> Any: """Convert small body designation to file prefix.""" return (desg.replace('/', '').replace(' ', '') .replace('(', '_').replace(')', '_'))
badde1e3ec9c3f669c7cce8aa55646b15cc5f4c8
27,868
def get_logger(name=None, log=False, level=INFO, path=None): """ Returns the appropriate logger depending on the passed-in arguments. This is particularly useful in conjunction with command-line arguments when you won't know for sure what kind of logger the program will need. :param name: ...
be321f4704e98db7a8f4d6033004194104bbee64
27,869
def stop_job(job_name: Text, execution_id: Text) -> JobInfo: """ Stop a job defined in the ai flow workflow. :param job_name: The job name which task defined in workflow. :param execution_id: The ai flow workflow execution identify. :return: The result of the action. """ return ...
0e67a061cbb730ffb6ebe57b11d32a3c110566dc
27,871
def find_user(): """ Determines current user using the username value of the current session user and returns the current user as a dict. """ current_user = mongo.db.users.find_one({"username": session["user"]}) return current_user
249836f8f1a23ff34bc55f112db2f4670672a7a1
27,872
def field2nullable(field, **kwargs): """Return the dictionary of swagger field attributes for a nullable field. :param Field field: A marshmallow field. :rtype: dict """ attributes = {} if field.allow_none: omv = kwargs['openapi_major_version'] attributes['x-nullable' if omv < 3...
dd5d4cd63aeede4ef9356baa9fe9a48bd5f87841
27,873
def zero_expand3d(inputs, stride=1): """Expand the inputs by zeros explain the expand operation: given stride = 1 [[[1, 2] --> [[[1, 0, 2] [3, 4]] [0, 0, 0] [3, 0, 4]] [[5, 6] [7, 8]]] [[0, 0, 0] [0, 0, 0] ...
4944b3f5f42811955b76fa46082dc5617fb648b7
27,874
import json def _load_setup_cfg(): """Load the setup configuration from the 'setup.json' file.""" try: with open(ROOT / 'setup.json') as setup_json_file: return json.load(setup_json_file) except json.decoder.JSONDecodeError as error: # pylint: disable=no-member raise Dependenc...
b3e26e25f18098a51210221299f3a1066c92e5db
27,875
import json def toJSON(obj, opt_pretty=False, for_cloud_api=True): """Serialize an object to a JSON string appropriate for API calls. Args: obj: The object to serialize. opt_pretty: True to pretty-print the object. for_cloud_api: Whether the encoding should be done for the Cloud API or the lega...
3f3d79d0b3b200ed3a05b55ea671eccae99543ce
27,876
import urllib def load_config_file_koe(filename): """ Loads in a config file for KOE to run Args: filename: Filename (can be absolute or relative path, or a URL) to read config file from. Returns: dict: Configuration file as a dict object. """ config_values = {} # First try t...
e04b162a396f5e3e4747855f7c69b9cad017bb39
27,877
def select_by_type(transcripts, log): """Filter transcripts depending on different type""" # Difference types: UTR5_number and UTR5_boundary candidates, dtype, dcrit = analyse_difference_type_utr5_number_or_boundary(transcripts, log) if candidates is not None: return candidates, dtype, dcrit ...
2b1b7311459e7a305a2cbc64d295114f5bca3fc3
27,878
def lorentzian_distance(x, y): """Calculates the Lorentzian Distance. Args: x (np.array): N-dimensional array. y (np.array): N-dimensional array. Returns: The Lorentzian Distance between x and y. """ dist = np.log(1 + np.fabs(x - y)) return np.sum(dist)
d11cc411aa22aab14b1b3ee2dd606d5a8efb6fe7
27,879
def check_database_status(database_name, env): """This function looks for a DatabaseCreate task and returns a http response or the Database itself depeding on the context. If the DatabaseCreate task is still running of failed, a http response is returned, otherwise this functions tries to retrieve the D...
17d9f616d20638c4624e5b35a042d9265ccf625f
27,880
def get_flat_schema(schema_name=None): """Flatten the specified data model schema, defaulting to the core schema, useful for retrieving FITS keywords or valid value lists. """ return _schema_to_flat(_load_schema(schema_name))
6f43a095015c25bdace05cf473f252ac699b33f9
27,881
def repeat3(img): """ Repeat an array 3 times along its last axis :param img: A numpy.ndarray :return: A numpy.ndarray with a shape of: img.shape + (3,) """ return np.repeat(img[..., np.newaxis], 3, axis=-1)
eddd3469d8d02457b87ef00c13ef7213d3a5568b
27,882
import time import tqdm def encode_strategies(strategies, batch_size=stg.JOBLIB_BATCH_SIZE, parallel=True): """ Encode strategies Parameters ---------- strategies : Strategies array Array of strategies to be encoded. Returns ------- numpy array ...
c77fcd28c69b447e43fc9eef359b32426771d6bd
27,883
def generate_authenticator(data, authenticator_key): """ This function will generate an authenticator for the data (provides authentication and integrity). :param data: The data over which to generate the authenticator. :type data: :class:`str` :param authenticator_key: The secret key to be used b...
8203c9f487d2acf6a8a0bbd907bc1f8cc9dc026c
27,884
def multi_recall(pred_y, true_y, labels): """ Calculate the recall of multi classification :param pred_y: predict result :param true_y: true result :param labels: label list :return: """ if isinstance(pred_y[0], list): pred_y = [item[0] for item in pred_y] recalls = [binary_...
a11984b6c509b9b95d65ad148ca712099ff91a66
27,886
def is_safe_range(expression): """ Return true if an expression is safe range. This function receives an expression in safe range normal form and returns true if all its free variables are range restricted. """ try: return extract_logic_free_variables( expression ...
e6a23b250f936cc78918ad15eb1122a419a8b872
27,887
def star_marker_level(prev, curr): """Allow markers to be on the same level as a preceding star""" return (prev.is_stars() and not curr.is_stars() and prev.depth == curr.depth)
3311c452c8f138cd8fa75b67109e75a9bf30902c
27,888
from typing import Optional from typing import Sequence def get_mail_addresses(ids: Optional[Sequence[str]] = None, key_word: Optional[str] = None, output_file: Optional[str] = None, sendtype: Optional[str] = None, status: Opt...
52590cc1c12788e47aa81adc1e9f51bbd9092f31
27,889
import torch def load_checkpoint( file, model: torch.nn.Module, optimizer: torch.optim.Optimizer = None, lr_scheduler: torch.optim.lr_scheduler._LRScheduler = None, strict: bool = True, ): """Loads training states from a checkpoint file. Args: file: a file-like object (has to imp...
f4eb59a303a5bf13ff1bdb9f37ca577a4d9e0419
27,890
def num_or_str(x): """The argument is a string; convert to a number if possible, or strip it. Ex: num_or_str('42') ==> 42; num_or_str(' 42x ') ==> '42x' """ try: return int(x) except ValueError: try: return float(x) except ValueError: return str(x).strip()
6709cfc772ecc79993563f43c2d8ea4526f222c6
27,891
def mac_timezone(): """Determine system timezone""" output = cmdmod['cmd.run']("/usr/sbin/systemsetup -gettimezone") return {'mac_timezone': output[11:]}
e5e8e45fdbd54d1741dd80a76a47f26f43640293
27,892
def lookup_loc_carriers(model_run): """ loc_carriers, used in system_wide balance, are linked to loc_tech_carriers e.g. `X1::power` will be linked to `X1::chp::power` and `X1::battery::power` in a comma delimited string, e.g. `X1::chp::power,X1::battery::power` """ # get the technologies associa...
85c20bd789e0250405dded9e0e4a56777047ef5a
27,895
def filldown(table, *fields, **kwargs): """ Replace missing values with non-missing values from the row above. E.g.:: >>> from petl import filldown, look >>> look(table1) +-------+-------+-------+ | 'foo' | 'bar' | 'baz' | +=======+=======+=======+ | 1 ...
1f14d9e3aba6791ab9d512c647053ad41fcfab59
27,896
def realworld_bring_peg(fully_observable=True, time_limit=_TIME_LIMIT, random=None, log_output=None, environment_kwargs=None, safety_spec=None, delay_spec=None, ...
496c7e31fee93d87d10cbee7bb6369c417956b23
27,897
def schedule_gemm(cfg, s, A, B, C, batched=False, schedule_transforms=True): """Schedule GEMM, single and batched Parameters ---------- cfg : Config Schedule configuration s : tvm.te.schedule.Schedule Operator schedule A : tvm.te.Tensor 2D/3D Tensor, shape [n, k]/[b, n...
2a99a20f4e9634bdaa06d114a9eafb7406736bc3
27,898
import math def distance(x1: float, y1: float, x2: float, y2: float) -> float: """Возвращает расстояние между двумя точками на плоскости""" return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
2113cb5926492ba89820ebb7f42de6993e46e3cb
27,899
import logging def GitPush(git_repo, refspec, push_to, force=False, dry_run=False, capture_output=True, skip=False, **kwargs): """Wrapper for pushing to a branch. Args: git_repo: Git repository to act on. refspec: The local ref to push to the remote. push_to: A RemoteRef object representi...
3af43d0a819c297735995a9d8c7e39b49937b7a3
27,900
def boxes_to_array(bound_boxes): """ # Args boxes : list of BoundBox instances # Returns centroid_boxes : (N, 4) probs : (N, nb_classes) """ temp_list = [] for box in bound_boxes: temp_list.append([np.argmax(box.classes), np.asarray([box.x, box.y, box.w, box....
e01b908e675b84928d1134d8eec4627f36b8af4a
27,901
from typing import Tuple def _scope_prepare(scope: str) -> Tuple[object, str]: """ Parse a scope string a return a tuple consisting of context manager for the assignation of the tf's scope and a string representing the summary name. The scope is of the form "<ident1>.<ident2>. ... .<ident3>", the righ...
01bcd08d87e23621f3476055379d9c7403fd4b75
27,903
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): aftv = hass.data[DOMAIN][entry.entry_id][ANDROID_DEV] await aftv.adb_close() hass.data[DOMAIN].p...
77376bcdf98c9b4c2ac6020e44d704fbe59d9143
27,904
from typing import Tuple def render_wrapped_text(text: str, font: pygame.freetype.Font, color: Color, centered: bool, offset_y: int, max_width: int) -> Tuple[pygame.Surface, pygame.Rect]: """Return a surface & rectangle with text rendered over several lines. Pa...
73be30318fd3afe5bf5138b8c21c46caf05022bc
27,905
def comp4(a1,a2,b1,b2): """两个区间交集,a1<a2; b1<b2""" if a2<b1 or b2<a1:#'空集' gtii = [] else: lst1 = sorted([a1,a2,b1,b2]) gtii = [lst1[1], lst1[2]] return gtii
ba4357b16ee09f78b6c09f422d27a42cd91e298e
27,906
from typing import Callable from typing import Optional from typing import Union from typing import Tuple from typing import List def fixed_step_solver_template( take_step: Callable, rhs_func: Callable, t_span: Array, y0: Array, max_dt: float, t_eval: Optional[Union[Tuple, List, Array]] = None...
6e989b1f6d92ddeb4d5f18e9eb110667f28b6a33
27,907
def set_reference_ene(rxn_lst, spc_dct, pes_model_dct_i, spc_model_dct_i, run_prefix, save_prefix, ref_idx=0): """ Sets the reference species for the PES for which all energies are scaled relative to. """ # Set the index for the reference species, right n...
52c915060a869f41ee5262190dd7ffac79b1684b
27,908
import torch def get_laf_center(LAF: torch.Tensor) -> torch.Tensor: """Returns a center (keypoint) of the LAFs. Args: LAF: tensor [BxNx2x3]. Returns: tensor BxNx2. Shape: - Input: :math: `(B, N, 2, 3)` - Output: :math: `(B, N, 2)` Example: >>> input = t...
c172defe938c35e7f41616b48d9d6d3da21eb9d1
27,909
def get_all_vlan_bindings_by_logical_switch(context, record_dict): """Get Vlan bindings that match the supplied logical switch.""" query = context.session.query(models.VlanBindings) return query.filter_by( logical_switch_uuid=record_dict['logical_switch_id'], ovsdb_identifier=record_dict['ov...
df88a52325e1bee59fae3b489a29ce8ee343d1fb
27,910
def conv_input_length(output_length, filter_size, padding, stride): """Determines input length of a convolution given output length. Args: output_length: integer. filter_size: integer. padding: one of "same", "valid", "full". stride: integer. Returns: The input length (integer). ...
88c80a77d3aee4050625aa080db5d9b246f9e920
27,911
def convert_data_to_int(x, y): """ Convert the provided data to integers, given a set of data with fully populated values. """ # Create the new version of X x_classes = [] for i in xrange(x.shape[1]): x_classes.append({item:j for j, item in enumerate(set(x[:,i]))}) new_x = np.zeros(x.shape, dtype='i') for ...
c8b3f017a34b68edf4f1740f8a3dd2130664ddae
27,912
def send_report(report_text, svc_info, now_str): """ Publish report to AWS SNS endpoint Note: publish takes a max of 256KB. """ overage = len(report_text) - MAX_SNS_MESSAGE if overage > 0: report_text = report_text[:-overage - 20] + '\n<message truncated/>' resp = SNS_C.publish(Topic...
9c48c3d7ba12e11cf3df944942803f36f6c23f52
27,913
def credential(): """Return credential.""" return Credential('test@example.com', 'test_password')
1da4e56abb87c9c5a0d0996d3a2911a23349321b
27,914
def get_ez_from_contacts(xlsx_file, contacts_file, label_volume_file): """Return list of indices of EZ regions given by the EZ contacts in the patient spreadsheet""" CONTACTS_IND = 6 EZ_IND = 7 df = pd.read_excel(xlsx_file, sheet_name="EZ hypothesis and EI", header=1) ez_contacts = [] contact...
b3e4bfda0d0e9830b34012b7995082e90c9932a8
27,915
def mapfmt_str(fmt: str, size: int) -> str: """Same as mapfmt, but works on strings instead of bytes.""" if size == 4: return fmt return fmt.replace('i', 'q').replace('f', 'd')
af51b6ac65c80eef1721b64dcd8ee6a8bb5cbc97
27,916
def RandomImageDetection(rows=None, cols=None): """Return a uniform random color `vipy.image.ImageDetection` of size (rows, cols) with a random bounding box""" rows = np.random.randint(128, 1024) if rows is None else rows cols = np.random.randint(128, 1024) if cols is None else cols return ImageDetectio...
e7f06b32b771f3eb3c10d09e39bc4be4577d4233
27,918
def upsample(x, stride, target_len, separate_cls=True, truncate_seq=False): """ Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension. """ if stride == 1: return x if separate_cls: cls = x[:, :1] x = x[:, 1:] outp...
716c94cb365144e65a6182e58c39284375c8f700
27,919
import numpy def torsional_scan_linspaces(zma, tors_names, increment=0.5, frm_bnd_key=None, brk_bnd_key=None): """ scan grids for torsional dihedrals """ sym_nums = torsional_symmetry_numbers( zma, tors_names, frm_bnd_key=frm_bnd_key, brk_bnd_key=brk_bnd_key) inter...
a2dcd4ec57ae598a42c25102db89af331e6f8a40
27,920
import ctypes def get_output_to_console(p_state): """Returns a bool indicating whether the Log is output to the console.""" return bool(_Get_Output_To_Console(ctypes.c_void_p(p_state)))
71599b5a2e4b2708d6e8d5fa003acc89cd0d030c
27,921
def check_valid_column(observation): """ Validates that our observation only has valid columns Returns: - assertion value: True if all provided columns are valid, False otherwise - error message: empty if all provided columns are valid, False otherwise """ valid...
104fc6646a5e4d978b2a0cec4322c6f275b82f42
27,922
def w_getopt(args, options): """A getopt for Windows. Options may start with either '-' or '/', the option names may have more than one letter (/tlb or -RegServer), and option names are case insensitive. Returns two elements, just as getopt.getopt. The first is a list of (option, value) pairs...
34095675fa95cbc1c8474a7253b4d49a2e947dc0
27,924
def get_alt_for_density(density: float, density_units: str='slug/ft^3', alt_units: str='ft', nmax: int=20, tol: float=5.) -> float: """ Gets the altitude associated with a given air density. Parameters ---------- density : float the air density in slug/ft^3 densi...
68243ec75bbe8989e7a9fd63fe6a1635da222cae
27,925
from datetime import datetime def parse_date_string(date: str) -> datetime: """Converts date as string (e.g. "2004-05-25T02:19:28Z") to UNIX timestamp (uses UTC, always) """ # https://docs.python.org/3.6/library/datetime.html#strftime-strptime-behavior # http://strftime.org/ parsed = datetime.strp...
624e92ceab996d7cfded7c7989e716fbba7abd5e
27,926
def levenshtein_distance(s, t, ratio_calc = False): """ levenshtein_distance: Calculates levenshtein distance between two strings. If ratio_calc = True, the function computes the levenshtein distance ratio of similarity between two strings For all i and j, distance[i,j] will contain ...
670196344e33bd4c474c0b24b306c9fe3d7e093b
27,927
def no_warnings(func): """ Decorator to run R functions without warning. """ def run_withoutwarnings(*args, **kwargs): warn_i = _options().do_slot('names').index('warn') oldwarn = _options()[warn_i][0] _options(warn=-1) try: res = func(*args, **kwargs) except ...
52831940551c324b6e9624af0df28cc2442bac2b
27,928
def ParseKindsAndSizes(kinds): """Parses kind|size list and returns template parameters. Args: kinds: list of kinds to process. Returns: sizes_known: whether or not all kind objects have known sizes. size_total: total size of objects with known sizes. len(kinds) - 2: for template rendering of gr...
7f94fd099ea2f28070fe499288f62d1c0b57cce9
27,929
def load_3D(path, n_sampling=10000, voxelize=True, voxel_mode="binary", target_size=(30, 30, 30)): """Load 3D data into numpy array, optionally voxelizing it. Parameters ---------- path : srt Path to 3D file. n_sampling : int Number o...
eec6614b2675faa61d9a09b8ff3a491580302a91
27,930
import array def create_vector2d(vec): """Returns a vector as a numpy array.""" return array([vec[0],vec[1]])
0b3cdc81f3744c54dea8aab0ee28743134ff1d42
27,931
def get_chrom_start_end_from_string(s): """Get chrom name, int(start), int(end) from a string '{chrom}__substr__{start}_{end}' ...doctest: >>> get_chrom_start_end_from_string('chr01__substr__11838_13838') ('chr01', 11838, 13838) """ try: chrom, s_e = s.split('__substr__') start, ...
5dbce8eb33188c7f06665cf92de455e1c705f38b
27,932
def Remove_Invalid_Tokens(tokenized_sentence, invalidating_symbols): """ Returns a tokenized sentence without tokens that include invalidating_symbols """ valid_tokens_sentence = [] + tokenized_sentence # forcing a copy, avoid pass by reference for token in tokenized_sentence: for invalid_symbol in invalidat...
931858685c6c405de5e0b4755ec0a26a672be3b0
27,933
def _get_protocol(url): """ Get the port of a url. Default port is 80. A specified port will come after the first ':' and before the next '/' """ if url.find('http://') == 0: return 'http' elif url.find('https://') == 0: return 'https' else: return 'h...
42b2750148829154f17e34a2cebccf4387f07f25
27,934
def row_to_str(row): """Convert a df row to a string for insert into SQL database.""" return str(list(row)).replace("[", "(").replace("]", ")")
fb2b0d598604a124b948f884a6839a40af1203fc
27,936
def interpolate_affines(affines): """ """ # get block grid block_grid = affines.shape[:3] # construct an all identities matrix for comparison all_identities = np.empty_like(affines) for i in range(np.prod(block_grid)): idx = np.unravel_index(i, block_grid) all_identities[id...
880ea993634a6c4725d02365d75e79705175c2e5
27,937
import tqdm def getLineMeasures(file_list, orders, names, err_cut=0): """ Find line center (in pixels) to match order/mode lines """ # Load in x values to match order/mode lines x_values = np.empty((len(file_list),len(orders))) x_values[:] = np.nan # want default empty to be nan x_errors =...
b13fe9f46457f7d289d09ffba3b769fe4e1c700e
27,938
def signature_exempt(view_func): """Mark a view function as being exempt from signature and apikey check.""" def wrapped_view(*args, **kwargs): return view_func(*args, **kwargs) wrapped_view.signature_exempt = True return wraps(view_func)(wrapped_view)
f564ad0ce20e6e2b7ae760c5f50a297f587006d4
27,940
def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg() add_tridentnet_config(cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) # if args.eval_only: # cfg.MODEL.WEIGHTS = "/root/detectron2/projects/TridentNet/log_80_20/model_0...
13d30557537c7e7d18811e016c0eaf43602f1ef2
27,941
def get_intersections(line, potential_lines, nodes, precision): """ Get the intersection points between the lines defined by two planes and the lines defined by the cost area (x=0, y=0, y=-x+1) and the lines defined by the possible combinations of predictors """ slope, intercept = line # In...
3e9811bee159f6c550dea5784754e08bc65624d7
27,942
def subtract_loss_from_gain(gain_load, loss_load): """Create a single DataCollection from gains and losses.""" total_loads = [] for gain, loss in zip(gain_load, loss_load): total_load = gain - loss total_load.header.metadata['type'] = \ total_load.header.metadata['type'].replace(...
b53044b802a8ea13befdde850a478c435b0370ef
27,943
def zero_out_noisy_epochs(psg, sample_rate, period_length_sec, max_times_global_iqr=20): """ Sets all values in a epoch of 'period_length_sec' seconds of signal to zero (channel-wise) if any (absolute) value within that period exceeds 'max_times_global_iqr' times the IQR of all...
427e2652a2e595bd0b25c3a30d35e088a9b0562b
27,944
from typing import Tuple from typing import List def start_training(channel: Channel) -> Tuple[List[ndarray], int, int]: """Start a training initiation exchange with a coordinator. The decoded contents of the response from the coordinator are returned. Args: channel (~grpc.Channel): A gRPC chann...
70ac5b32b58df84cd386cc820f18a8fe2667d620
27,946
import re def has_forbidden(mylist) -> bool: """ Does the string contain one of the forbidden substrings "ab" "cd" "pq" "xy"? """ return bool(re.search(FORBIDDEN, mylist))
848fb1270ba99f40ef1ff0e23296f76895a5484d
27,947
from main import PAGLuxembourg def classFactory(iface): # pylint: disable=invalid-name """Load PagLuxembourg class from file PagLuxembourg. :param iface: A QGIS interface instance. :type iface: QgsInterface """ # return PAGLuxembourg(iface)
9ff71fbc9f915435da660861ee9023026dfb2e48
27,948
def is_official_target(target_name, version): """ Returns True, None if a target is part of the official release for the given version. Return False, 'reason' if a target is not part of the official release for the given version. target_name: Name if the target (ex. 'K64F') version: The release ver...
4cd8a2e3735aa91cd66204568c70e645e6f2f8ed
27,949
from typing import Dict from typing import Union from typing import Any def _convert_to_dict_or_str(elements_map: Dict[str, Element]) -> Dict[str, Union[str, Dict[Any, Any]]]: """Combines a dictionary of xml elements into a dictionary of dicts or str""" return { key: XmlDictElement(value) if value or ...
a68d1043abb995a632209528a52416a8a4661b58
27,950
def vsi_tecaji(): """ Funkcija vrne vse tečaje PGD Hrušica. """ poizvedba = """ SELECT id, naziv FROM tecaji """ tecaji = conn.execute(poizvedba).fetchall() return tecaji
c4e9e9a9422920b38d4dce51a27d4db142c50f90
27,951
def cosine(u, v, dim=-1): """cosine similarity""" return (u * v).sum(dim=dim) / (u.norm(dim=dim, p=2) * v.norm(dim=dim, p=2))
2d2a5a02ce20f6ae37dbefa3c8f9399aef2da8ad
27,952
from datetime import datetime def retrive_cache_data(format: str, query: str) -> dict[int, Book]: """ Retrive the cached data for the query. """ date_now = datetime.now() # save the search results in the cache if not already there or if the cache is expired if format not in book_cache: ...
885532f94f1e4b28350d3854ada867f42d386d5f
27,953
def get_orders_loadings_palette_number(client_orders, value): """ Searches OrdersLoadingPlaces objects linked with client orders and that contain value :param client_orders: orders of profile :param value: value of palettes number for which OrdersLoadingPlaces objects are searching :return: List wit...
c145997418722e84da5d7420fbba6a8167737f96
27,954
import math def rotmat(x=0,y=0,z=0): """Rotation Matrix function This function creates and returns a rotation matrix. Parameters ---------- x,y,z : float, optional Angle, which will be converted to radians, in each respective axis to describe the rotations. The defau...
f1b31916abb78f3f47c324c3341d06338f6e4787
27,955
def add_model_components(m, d, scenario_directory, subproblem, stage): """ :param m: :param d: :return: """ m.Horizon_Energy_Target_Shortage_MWh = Var( m.ENERGY_TARGET_ZONE_BLN_TYPE_HRZS_WITH_ENERGY_TARGET, within=NonNegativeReals ) def violation_expression_rule(mod, z...
e6fe56e72fb7cd5906f0f30da2e7166a09eeb3f1
27,956
def grow_rate(n, k, nu_c, nu_d, sigma, g, dp, rho_c, rho_d, K): """ Compute the instability growth rate on a gas bubble Write instability growth rate equation in Grace et al. as a root problem for n = f(k) Returns ------- res : float The residual of the growth-rate equation...
79e277ca7941b80fd52667b4157ffbfd97f9a87e
27,957
def cg_semirelaxed_fused_gromov_wasserstein(C1:th.Tensor, A1:th.Tensor, p:th.Tensor, C2:th.Tensor, A2:th.Tensor, ...
5a21edf35423b46826a9b88af62ddd27678538c2
27,958
def Vinv_terminal_time_series(m_t,Vdc_t): """Function to generate time series inverter terminal voltage.""" try: assert len(m_t) == len(Vdc_t) != None return m_t*(Vdc_t/2) except: LogUtil.exception_handler()
cbbcc7475c30694f3960e1b78b4be64bde283a2b
27,959
def render(ob, ns): """Calls the object, possibly a document template, or just returns it if not callable. (From DT_Util.py) """ if hasattr(ob, '__render_with_namespace__'): ob = ZRPythonExpr.call_with_ns(ob.__render_with_namespace__, ns) else: # items might be acquisition wrapped ...
fba552131df5fe760c124e90e58f845f06fbbf44
27,960
def GetFlakeInformation(flake, max_occurrence_count, with_occurrences=True): """Gets information for a detected flakes. Gets occurrences of the flake and the attached monorail issue. Args: flake(Flake): Flake object for a flaky test. max_occurrence_count(int): Maximum number of occurrences to fetch. ...
596573749599e7a1b49e8047b68d67a09e4e00e9
27,961
def get_prop_cycle(): """Get the prop cycle.""" prop_cycler = rcParams['axes.prop_cycle'] if prop_cycler is None and 'axes.color_cycle' in rcParams: clist = rcParams['axes.color_cycle'] prop_cycler = cycler('color', clist) return prop_cycler
9b571b16cddf187e9bbfdacd598f280910de130a
27,962
def binary_crossentropy(target, output, from_logits=False): """Binary crossentropy between an output tensor and a target tensor. Arguments: target: A tensor with the same shape as `output`. output: A tensor. from_logits: Whether `output` is expected to be a logits tensor. By default, we...
eb388c3bb3454eec6e26797313534cf089d06a6d
27,963