content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _func_and(current, checks): """Implementation of And.""" return all(check(current) for check in checks)
a778d9193c958729f40e09feb3903350b2d3054b
65,600
def add_eo3_parts(doc, tol=None): """Add spatial keys the DB requires to eo3 metadata """ return dict(**doc, **eo3_grid_spatial(doc, tol=tol))
5340d2134568e2836bb368acd6a48228d95ffa45
65,601
from typing import Dict def get_potential_fields(attrs: Dict) -> Dict: """ Gets all the fields in current class namespace that are Fields. :param attrs: current class namespace :type attrs: Dict :return: extracted fields that are ormar Fields :rtype: Dict """ return {k: v for k, v in ...
8594286f7331ef36b9d77d9e0fcfb7e57d1b3331
65,602
def _hilbert_integer_to_transpose(p, h): """Store a hilbert integer (`h`) as its transpose (`x`). Args: p (int): iterations to use in the hilbert curve h (int): integer distance along hilbert curve Returns: x (list): transpose of h (n components with values between...
aa2166cdde6ebf978a1514c370f9c0dcdc2d703a
65,603
from pathlib import Path from typing import Optional import os import json async def safe_load( path: Path, profile: str, user_email: Optional[str], selected_remote: Optional[RemoteGateway], context: Optional[Context] = None, ) -> YouwolEnvironment: """ Possible errors:...
4456dd66dd19213e5f9b2eaecf45343034b0419e
65,604
def plot_sphere(ax=None, radius=1.0, p=np.zeros(3), ax_s=1, wireframe=True, n_steps=20, alpha=1.0, color="k"): """Plot sphere. Parameters ---------- ax : Matplotlib 3d axis, optional (default: None) If the axis is None, a new 3d axis will be created radius : float, optional...
56c75eb6547c51d85a04a85ef50be804f1a28eb0
65,605
def __parse_num_den(num: ndarray, den: ndarray): """ Reduce the two linears objects as a single item The reduction follows the matrix_rn_representation protocol: ======================= INTER-LINEARS REDUCTION ======================= -> checks for possible reductions between numerator...
0cc010b4590dfebc1a4eaf6ce37793a7f498fcb9
65,606
def get_auc_score(result_dataframe, # result dataframe for a certain run key): # the name of the result to get the curve for """ Get the Area Under the Curve for the indicated key in the dataframe. Args: result_dataframe: Result dataframe for a certain run key: The name of t...
f1609fae173a498a2f38214010068d52bd0758a0
65,607
from typing import Optional from typing import Sequence def method_def( name: BaseOperatorName, module: Optional[str], overloads: Sequence[PythonSignatureNativeFunctionPair], *, method: bool ) -> str: """ Generate method def entry. """ pycname = get_pycname(name) if is_noarg(o...
309943490d5268b50e72aca9e330624450747682
65,608
import os def dds_solver(pbn): """Takes a pbn of the form 'AKJ852.AKT3..KT9 T3.Q62.5.AQJ8763 Q764.98754.J872. 9.J.AKQT9643.542' """ os.system('echo \"1\n' + pbn + '\n\" > ' + DDS_SOLVER_DIR + 'myd.txt') out = os.popen('cd ' + DDS_SOLVER_DIR + '; ./CalcAllTablesPBN < myd.txt').read() if not out: ...
86950074b47b12512488ffe2898cbf0202dfc459
65,609
import torch def normalize_quaternion(quaternion, eps=1e-12): """Normalizes a quaternion. The quaternion should be in (w, x, y, z) format. Parameters ---------- quaternion: torch.FloatTensor (B4) Input quaternion to normalize. eps: float, default: 1e-12 Epsilon value to avoid...
8e1de3b25753b982f0a06b0c6aa9fb98d5360e86
65,610
def do_djfrontend_twbs_js(parser, token): """ Returns Twitter Bootstrap (3.0.0) JavaScript file(s). all returns concatenated file; full file for TEMPLATE_DEBUG, minified otherwise. Other choice are: affix, alert, button, carousel, collapse, dropdown, m...
9005a4232d775665a453fc99f40e9cae61f5bb0a
65,611
def get_user_id(email): """Fetches user's id. Args: email: user's email address. Returns: User ID of user with given email address. """ try: user = User.query.filter_by(email=email).one() return user.id except: return None
31204d23e38c6bb55e7d4e70144a10e87e64203a
65,612
def blindspots(center, gridcoords, minelev, maxelev, maxrange): """Blind regions of the radar, marked on a 3-D grid The radar is blind below the radar, above the radar and beyond the range. The function returns three boolean arrays which indicate whether (1) the grid node is below the radar, (2) the gr...
ccd24ccebf09b3f9e47918834a3986047eba58f7
65,613
from meerschaum.utils.misc import choose_subaction from typing import Optional from typing import List from typing import Any def install( action : Optional[List[str]] = None, **kw : Any ) -> SuccessTuple: """ Install Meerschaum plugins or Python packages. """ options = { '...
2d7ece9237843f96b776bb0f1161bec1a40d157a
65,614
def eval_py(distmat, q_pids, g_pids, q_camids, g_camids, max_rank=50): """Evaluation with market1501 metric Key: for each query identity, its gallery images from the same camera view are discarded. """ num_q, num_g = distmat.shape if num_g < max_rank: max_rank = num_g print("...
81f248829b9c357eae72bc26441ca09ae55d8124
65,615
def compare_events(a: EnterEvent, b: EnterEvent) -> int: """Compares 2 Enter events based on the timestamp of the first human event :param a: The first enter event :param b: The second enter event :return: Returns -1 if `a` is before `b`, 1 if `b` is before `a`, and 0 if `a` and `b` occur at the same t...
e5d7a3f2d48b13ee5773ca3d9590453eb603b795
65,616
def _extra_gas_dndfeh(s, feh, p, M): """ Not normalized! """ z = (10**feh)/p return z * (1 + s*(1-1/M)) / (1/(1-s/M) - 2*z*(1-1/M))
485880edfc10be58716a31f25edd4d1c1188867e
65,617
def bash_quote(*args): """Quote the arguments appropriately so that bash will understand each argument as a single word. """ def quote_word(word): for c in word: if not (c.isalpha() or c.isdigit() or c in '@%_-+=:,./'): break else: if not word: ...
cb25adb60ea98cb6887e89a6a4f5097bb8f4843f
65,618
def count_change(amount): """Return the number of ways to make change for amount. >>> count_change(7) 6 >>> count_change(10) 14 >>> count_change(20) 60 >>> count_change(100) 9828 >>> from construct_check import check >>> # ban iteration >>> check(HW_SOURCE_FILE, 'count_c...
8926533e846f67474ebe0ea8983089010af28ed0
65,619
import re import os def find( path, include_dirs = True, include_files = True, name_regex = None, not_name_regex = None, whole_name_regex = None, not_whole_name_regex = None, exclude_root = False, relative = False, limit_depth = None ): """ Creates an iterator of files matching a variety of conditions. ...
20b3add77af97dce4b9dc8ee102ae7bd98010ccf
65,620
from datetime import datetime def datetime_ceil(dateval: datetime) -> datetime: """Round the given datetime object upwards.""" if dateval.microsecond > 0: return dateval + timedelta(seconds=1, microseconds=-dateval.microsecond) return dateval
d77531000d8fbda01d4631193e4e09a5e13611a7
65,621
import numpy def asind(slope: ArrayLike) -> ArrayLike: """Return the arcsine of an angle specified in degrees. Returns ------- float An angle, in degrees. """ return numpy.degrees(numpy.arcsin(slope))
f6d87036f5d1ae3c5879f54f457e34818e6b478b
65,622
def on_status(): """ command /status: show bot status """ return bot.send_message("Listening Motion run") \ if bot.is_listen else bot.send_message("Listen Motion doesn't run")
c22315512c3727430c363b8877480393f0def52e
65,623
def XfmrCode(*args): """Name of an XfrmCode that supplies electircal parameters for this Transformer.""" # Getter if len(args) == 0: return get_string(lib.Transformers_Get_XfmrCode()) # Setter Value, = args if type(Value) is not bytes: Value = Value.encode(codec) lib.Transf...
f11b4d43ec6c1d4a4b5cb36b8fbb466dc8a4cd73
65,624
import sys def shell(command, capture=False): """Portable system call that aborts generation in case of failure.""" try: if capture: stdout = check_output(command, shell=True, stderr=STDOUT, universal_newlines=True) return str(stdout) ...
5bb913caeadd7294812a984f28fe2a331fefdede
65,625
def move(rel_src_path: str, rel_dest_path: str) -> None: """paths are relative to users root folder (ROOT/user_X/). Folders that don't exist are created""" client_logger_sync().info(f"Move file: rel_src_path={rel_src_path}, rel_dest_path={rel_dest_path}") abs_src_path = path_utils.rel_user_path_to_abs(r...
fe44b5223d29520a8d698ba6f47b0cd580a5c016
65,626
def blackholes(data_in, filter_spec_samples=None, filter_spec_variables=None, label_rows_with=None, label_cols_with=None, group_rows_by=None, group_cols_by=None, missing_color='black', backkground_col...
633b39914929dc40525de9411a362a3adc0733dd
65,627
def get_area(root): """Extracts the ash cloud total area Values returned are in this order" 1. Total ash area 2. Total ash area unit""" area = root.alert.total_area.attrib.get('value') area_unit = root.alert.total_area.attrib.get('units') return area, area_unit
ea5a908e4226359aeb962f66c4ed4691d8d93a1b
65,628
from typing import Iterable from typing import Any def replace_na( data: Iterable[Any], data_or_replace: Any = None, replace: Any = None, ) -> Any: """Replace NA with a value This function can be also used not as a verb. As a function called as an argument in a verb, data is passed implicitly...
ffebb0d26b58766e3d4c7c6780e92d31e95f5f98
65,629
def mid_point(p1, p2): """ 计算中点 """ x = (p1[0] + p2[0]) // 2 y = (p1[1] + p2[1]) // 2 return [x, y]
2630e4158ea6414242b05ada987f2cf020442339
65,630
def extract_task(tsk, tsk_lst): """ Searches for a task in the task lst and if found: the corresponding keywords and values will be returned Function only works if task is present in the list one time. :param tsk: task to extract information for :type tsk: str :param tsk_ls...
b8c3e68ca5d00227e51cbd0b869cbe09ddd3123f
65,631
def heliocentric_velocity_corr_kms(ra, dec, mjd) : """ Heliocentric velocity correction routine. See http://docs.astropy.org/en/stable/coordinates/velocities.html for more details. The computed correction can be added to any observed radial velocity to determine the final heliocentric radial velocit...
2828c6aef538407b41f46498318d01ad8fd76935
65,632
def rev_parse(rev: str, *, abbrev: bool = False) -> str: """Compute the hash for a revision. Args: rev: A Git revision in any format known to the Git CLI. abbrev: Return a branch or tag name instead of a git sha Returns: ref: A 40 character hex-encoded SHA-1 hash representing the I...
3bd38dd29235593d93a1f55fd2422504f7367295
65,633
def generate_key(): """Generate a MongoDB ObjectID-compatible string.""" return str(ObjectId())
72524f8552703af2ace52d937f3dec5279c09a49
65,634
from typing import List from typing import Optional def TabWidget( tabs: List[Tab], owner: Optional[QWidget] = None, name: Optional[str] = None, ) -> QTabWidget: """[summary]""" tabWidget = QTabWidget() for tab in tabs: tabWidget.addTab(tab.widget, tab.label) return tabWidget
b9db8694c4dcf5ae25e9ed09a1c2f21db7669fe1
65,635
def isclassof(classinfo): """Creates a partial application of isinstance. Args: classinfo: The classinfo argument for isinstance. Returns: (Callable[[object], bool]): A function `f(obj)` that returns `isinstance(object, classinfo)` """ return partial(flip(is...
b0dec9b1ec6f8dc4368e717232cfd1fa49cc8862
65,636
def generate_population_of_solutions(): """ Generate a number of random solutions and sort them by best first """ solutions = [] for i in range(1, POPULATION_NUMBER): solution = generate_random_solution() res = solution.test_solution() solutions.append((solution, res)) return s...
f24421b88329eff0b2221b3755daa88ec2cc20ff
65,637
def get_client_permissions(client_id: str) -> Permissions: """Return effective client permissions.""" client = Session.get(Client, client_id) if not client: raise x.ODPClientNotFound return { scope.id: '*' if not client.provider else [client.provider_id] for scope in client.scop...
288948ea1b0373957e902648244f1af24eb967cf
65,638
def to_unicode(s): """Convert str s to unicode :param str s: string :return: "unicode" version of s (unicode in py2, str in py3) """ if PY_VERSION == 2: s = unicode(s) return s
38e792f3599b272907d28ed8a9d8b822fc6ea5b1
65,639
import inspect def init_db(): """ Import all modules here that might define models so that they will be registered properly on the metadata, and then create a database """ def func(subcls): """ To check the subclasses of BASE""" try: if issubclass(subcls[1], BASE): ...
98b85022e111373de90df58361b1293b90cf10b3
65,640
def question_data_path(instance, filename): """Returns Questions data path.""" # question data will be uploaded to MEDIA_ROOT/question_<id>/<filename> return 'question_{0}/{1}'.format(instance.title.replace(" ", "_"), filename) # return 'question_{0}/{1}'.format(inst...
dc268bb4e3ff0d00ac3bb8ba8299ce0629951487
65,641
from typing import Counter def get_dice_frequencies(throw): """ Returns a dictionary with the counts of unique dice, pairs, three of a kind etc Examples: '222333' returns {'Three of a kind': ['2', '3']} '123344' returns {'Pair': ['3', '4'], 'Single': ['1', '2']} """ # use the Counter funct...
4f7962d0b35dd37bf2be28bb32d385e5c703b0f7
65,642
def load(modulefile, flags=''): """Load modulefile(s) into the shell environment.""" return module('load {0} {1}'.format(modulefile, flags))
1ba43fa75a24627e06bde3f5f8129b85e5a05420
65,643
def load_hashbits(filename): """Load a hashbits object from the given filename and return it. Keyword argument: filename -- the name of the hashbits file """ hashtable = _Hashbits(1, [1]) hashtable.load(filename) return hashtable
85aac0cb53d6f0d71257da66c720d4418bae651c
65,644
def assert_api_call( client, url, payload, expected, expect_authenticated=False, expect_status=status.HTTP_200_OK, use_defaults=True, ): """Run the API call and perform basic assertions""" assert bool(get_user(client).is_authenticated) is False response = client.post(reverse(url...
2ea1677485f8662f0d6f55b1e3adb45d37ceb02c
65,645
def find_artist(name): """ Given an artist name, return an artist object from search results. returns None if no artist is found. """ q = 'artist:{}'.format(name) s = get_spotify() result = s.search(q, limit=1, type='artist', market=user_country()) items = result['artists']['items'] ...
61511c97de487055671a079560eb71ac2d318829
65,646
import builtins def float(name, default=None, allow_none=False, fallback=None): """Get a string environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `Non...
241a79882f11b97ac725660effce11dc67aa0c64
65,647
import os def create_destdir(): """创建系统目录,这里只是在tmp目录中建立""" tmpdir = mkdtemp() os.makedirs("%s/%s/acl"%(tmpdir, sysconf.namedconf)) os.makedirs("%s/%s/dynamic"%(tmpdir, sysconf.namedconf)) os.chown("%s/%s/dynamic"%(tmpdir, sysconf.namedconf), sysconf.named_uid, 0) os.mkdir("%s/%s/master"%(...
a9777661e093ebe697d09259a971e1c764757dc7
65,648
def wrappable_filter(value, autoescape=None): """ Places zero-width breaking spaces in text to allow it to wrap before a underscore (_) or fullstop (.). The browser will use this as a hint as to where to wrap the text if required. """ # Escape the input text so that it's safe to display ...
5d6b61c55116093bd3a9642b217740e222e01289
65,649
def by_name(name): """Return a platform object that corresponds to the given name or None if there is no match. Args: name (str): name of the platform """ platform_cls = cls_by_name(name) return platform_cls() if platform_cls else None
ab7394df8ee50508d4e8e1a0f86f7d7ac380243c
65,650
def _compscale(data): """ Automatically computes a scaling for the wavefunctions in the plot. Args: data (dict): The data neccesarry for computing the scale factor. Needs to contain 'wfuncs' and 'energies'. Returns: scale (float): The computed scale. """ wfuncs = d...
0c33313c86c38568a1713de28e5f5b44b2b0207c
65,651
def get_nodes(G,**kwargs): """ search nodes having the given attributes :param G: graph where nodes are searched :param kwargs: atom= , in_cycle= :return: a list of nodes :rtype: list """ nodes=[] if G!=None: for n in G.nodes(): match=True for k,v...
058475407fd0ad7104fb9eb90a8118ee130ae98f
65,652
def deviceagents(): """Get all DeviceAgent data from the DB. Args: None Returns: Agent data """ # Get data data = db_deviceagent.get_all_device_agents() # Return return jsonify(data)
1d6313cad1ce5ad22b9dcec0d925ed5a0c4b8481
65,653
from typing import OrderedDict import tarfile import re def import_votes_internal( vote_type, principal, domain, session, date_, dataset_name, expats, vote, municipality ): """ Import test datasets in internal formats. For one vote, ther...
4421f33103a6e71a1e3e78891a852efdfce1bb60
65,654
def filter_job_dict(job_dict: dict, args: dict) -> dict: """Filter out parts of job result dict based on query string arguments.""" logger = get_logger() # Define order of nornir tasks in known types of jobs filter_map = { "syncto": { "config": 1, "diff": 2 } ...
842d35cf620d1db58e124768d6c8c4e49cd65140
65,655
def scipy_sparse_to_sympy(m, **options): """Convert a scipy.sparse matrix to a sympy matrix.""" return Matrix(m.todense())
4c7ad5530f89a31767fa782c6c4f2a69239cd350
65,656
from numpy.lib.stride_tricks import as_strided def cross_correlation(x, y, maxlag): """ Cross correlation with a maximum number of lags. `x` and `y` must be one-dimensional numpy arrays with the same length. This computes the same result as numpy.correlate(x, y, mode='full')[len(a)-maxlag-1:...
ef881c37e13ca39bb80a14c65bd2dd0767172e0c
65,657
def part1(bags): """ >>> part1(read_input()) 254 """ reverse = defaultdict(list) for colour, bags in bags.items(): for (_, bag) in bags: reverse[bag].append(colour) queue = ['shiny gold'] colours = set() while queue: colour = queue.pop(0) for ...
bd8c1e91fbd49203aee1eaca0a4697553d9cf630
65,658
def count(name: str = "") -> "Expr": """ Count the number of values in this column """ return col(name).count()
0573bc477ab5301391496e07a4757c453c077978
65,659
from typing import List def largest_less_than(indexes: List[int], line_num: int, pos: int) -> int: """Replacement func for python str.rfind using indexes """ return indexes[line_num - 1] if indexes and count_occurrences(indexes, pos) else -1
7320eaacaa395778590eb0c3077ae0223b82166f
65,660
from functools import reduce def equal(list_): """ Returns True iff all the elements in a list are equal. >>> equal([1,1,1]) True """ return reduce( lambda a, x: a and (x[0] == x[1]), zip(list_[1:], list_[:-1]), True, )
65b8a9b5652ecd6b3cc9709dd7e56b4e1258caf4
65,661
def encode_query_string_for_alb(params: QueryParams) -> bytes: """Encode the query string parameters for the ALB event. The parameters must be decoded and then encoded again to prevent double encoding. According to the docs: "If the query parameters are URL-encoded, the load balancer does not deco...
2dc0ddafff93d55148c60a1baaf57a25f28daf42
65,662
import inspect def get_code(): """ Return source code of Fibonacci sequence logic's implementation. """ return inspect.getsource(get_sequence)
f164f873d591650df55cb7dd08546f261a5582a7
65,663
import six def swapaxes(a, axis1, axis2): """Swaps the two axes. Args: a (cupy.ndarray): Array to swap the axes. axis1 (int): The first axis to swap. axis2 (int): The second axis to swap. Returns: cupy.ndarray: A view of ``a`` that the two axes are swapped. .. seeals...
25b007ad3a749ff27a37d6b12060c95885aed165
65,664
import os def create_npd_shapefile_dict_preprocess(main_path='./sample_data/'): """ Function designed to grab a variety of shape files from the NPD database. Assumes hard coded files are present Arguments: main_path: string, absolute file path to the shapefiles Returns: dictionary of file...
bfbf61e097a6402c3759b588719dddb3901f7685
65,665
from datetime import datetime import tqdm def scrape(league): """Scrape data :param league: league ID """ # Start timer startTime = datetime.now() # Scrape player IDs and teams from a public league data = set() groups = ["QB", "WR", "RB", "TE", "K", "DEF"] s = create_session() ...
9180c9d007600d8b7ee826f7befd2143f491ad3c
65,666
def fit_potential_to_snap(snap, rho_func, m_range=(1, 20), m_bins=50, q=None, return_p=False, *args, **kwargs): """Fit an ellipsoidal density function of the form rho_func(m,p[0],p[1],....) to the snapshot. Returns pot : the best fitting potential. Must supply initial parameters f...
65025e1763da04791d48d1c27d93e5869779e757
65,667
import copy def process_dataframe_dft(df, data_path = '/data/utils', origin=False, dim=False, AX_sub_only=False): """ Featurize the preprocessed NiCOLit dataset with DFT and physico-chemical descriptors already computed and stored as csv files and return additionnal data as yields, DOIs, coupling partner class an...
044f9ba411cb73d52194bdcf696301cdf1b1c915
65,668
import requests def commit_transaction(rivine_explorer_address, rivine_explorer_api_password, transaction): """ Commits a singed transaction to the chain @param transaction: Transaction object to be committed """ data = transaction.json url = '{}/transactionpool/transactions'.format(rivine_ex...
235779ac09a4f8350847c17de2a1f86fda15671b
65,669
def test_expand_dims_grad(): """ test_expand_dims_grad """ input_tensor = Tensor(np.array([[2, 2], [2, 2]])) expand_dims = P.ExpandDims() def fn(x): output = expand_dims(x, 0) return output out = fn(input_tensor) gfn = grad_all_with_sens(fn) sens = Tensor(np.ones_like(out.a...
7ba132785f3299b4b2f03a298ef04e8cee184a4a
65,670
import trace def plot_eigenvalues(mc: tmc, dpi: int = 100) -> oplot: """ The function plots the eigenvalues of the Markov chain on the complex plane. :param mc: the target Markov chain. :param dpi: the resolution of the plot expressed in dots per inch (by default, 100). :return: None if Matplotl...
4b9ca996d7cbb6cf243d02da55cd9a410fa4c15c
65,671
from typing import List def _effective_dir_path_exists(mb: MACIDBase, start: str, finish: str, effective_set: List[str]) -> bool: """ checks whether an effective directed path exists """ start_finish_paths = find_all_dir_paths(mb, start, finish) for path in start_finish_paths: if _path_is...
e81ff58c400748e54058f26de1db9151944ca1ae
65,672
def dequeue(queue_id, output_type, output_shape, queue_name=""): """ Dequeue. """ result = gen_npu_cpu_ops.dequeue( queue_id=queue_id, output_type=output_type, output_shape=output_shape, queue_name=queue_name) return result
02c7b0bd1d94873d90bcccbcc12886c1629dcaa8
65,673
def yields_from_leung_nomoto_2020(feh): """ Supernova data source: Leung & Nomoto, 2020, ApJ, Vol 888, Issue 2, Id 80 The seven datasets are provided for Z/Zsun values of 0, 0.1, 0.5, 1, 2, 3 and 5. Using Zsun = 0.0169 the corresponding FeH values are -1, -0.301, 0.0, 0.301, 0.4771 and 0.69897. We u...
21ad4bf1eab2193a97f98594c60a5e3db18e4a74
65,674
from pathlib import Path def add_path_to_local_dataset_list(paths_list: list) -> Path: """Take a list with folders and/or file names and add it to the local dataset path Args: paths_list: A list with folders and/or file needed to be added to the path Returns: The full pat...
5c0144370a62082c9e14e96b72d2b69c1838c6b3
65,675
def stocking_event_dict(db): """return a dictionary representing a complete, valid upload event. This dictionary is used directly to represent a stocking event, or is modified to verify that invalid data is handled appropriately. """ event_dict = { "stock_id": None, "lake": "HU", ...
bed85f03438700754d52a0d858d7a41ee5079406
65,676
def highest_hpx_level_from_largest_hpx(max_hpx): """ given the largest hpx value it returns the corresponding hpx level """ for i in range(12): if (max_hpx < number_of_healpixels(i)): break return(i)
ca1df1b87582e43c4d9b71399c3d54c2d1e5bd51
65,677
import socket def get_device_description(): """ This info is later shown in the "Open sessions" overview in the client. Should be something so the user knows where this session is coming from. :return: :rtype: """ return 'Console Client ' + socket.gethostname()
2881b58e5854156adc57fb834284d55fc961cc55
65,678
import torch def preemphasis(signal, coeff=0.95): """perform preemphasis on the input signal. :param signal: The signal to filter. :param coeff: The preemphasis coefficient. 0 is no filter, default is 0.95. :returns: the filtered signal. """ signalroll = torch.roll(signal, 1) signalroll[0]...
2bb30b13b737554471b45ad4dfcdb3a5890865fe
65,679
import time import os import logging import signal def terminate(end, proc, kill): """Terminate or kill the process after end.""" if not end or time.time() <= end: return False if kill: # Process will not die, kill everything pgid = os.getpgid(proc.pid) logging.info( '...
7cf36dc08597d19a1d6bb7cd55b5cbb8a71fa4c1
65,680
def estLr(meta, cpu=1, plot=False, fout=None): """ Estimation the linear relationship between genomic distance and interaction frequency. """ ds = Parallel(n_jobs=cpu, backend="multiprocessing")( delayed(preObs)(meta["data"]["cis"][key]["ixy"], cut=0, binSize=10000) for key in meta["data...
6faabec52f157b0ba9afab47859f12010b072721
65,681
def login( request: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(configuration.get_db), ): """ Login user Args: request (OAuth2PasswordRequestForm, optional): OAuth2PasswordRequestForm. db (Session, optional): Session. Defaults to Depends(configuration.get_db). ...
7bb60b2b840e367d93fc072e0a085f7490091605
65,682
def f_3b(beta, x): """ implicit definition of the circle """ return (x[0]-beta[0])**2 + (x[1]-beta[1])**2 - beta[2]**2
960417c0c462f41e0345ae3331c86b820faaa73e
65,683
def dict_to_str(dct): """Convert a dict to a string.""" def convert(dct): for k, v in dct.items(): if isinstance(v, ftrack_api.entity.base.Entity): v = str(v) else: v = repr(v) yield '{}={}'.format(k, v) return ', '.join(convert(dct...
6a8690645ce9d46f2536f508254fc14203327d59
65,684
import torch def diverse_deepdraw(net, base_img, octaves, random_crop=True, original_size=None, bias=None, scale=None, device='cuda', div_metric='correlation', div_linkage='minimum', div_weight=0, div_mask=1, **step_params): """ Similar to deepdraw() but including a diver...
afe1e4342d299d8422812c6ce8b8e145d14c7730
65,685
def db_keys(): """ Endpoint Function to interact with PupDB's keys() method. """ return {'keys': list(DB.keys())}, 200
c8f282a10a068e92746f97a1a9ddff5789e63b9a
65,686
import os def make_dir_safe(path): """ Make a directory without any race conditions @return - true if newly created, false if already exists """ try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise else: return False ...
afcffc88039bcef0e83d90bf4ae96fd7ee261e38
65,687
import random def random(states_size, alphabet_size, acceptance=0.5): """Constructs a random DFA with "states_size" states and "alphabet_size" inputs. Each transition destination is chosen uniformly at random, so the resultant DFA may have unreachable states. The optional "acceptance" parameter indicates ...
21b61f986231e470df33a8c48dd21163feab04f0
65,688
from typing import Union from typing import Iterable def predict_from_binary_tree( X: Union[list, np.ndarray], children_left: Union[list, np.ndarray], children_right: Union[list, np.ndarray], feature: Union[list, np.ndarray], threshold: Union[list, np.ndarray], value: Union[list, np.ndarray], ...
39e447137891705a5b8e1800a0421c1d284edc28
65,689
def vol_volunteer_controller(): """ Volunteers Controller """ s3 = current.response.s3 s3db = current.s3db settings = current.deployment_settings T = current.T # Volunteers only s3.filter = FS("type") == 2 vol_experience = settings.get_hrm_vol_experience() def prep(r): re...
337278dc92b34949210b41e8c2415dfcc314060b
65,690
def unique_hosts(hosts: str) -> str: """ Verify all hosts are unique. If more than one host is passed to the hosts parameter, ensure no two hosts are identical as Bobber can't be run concurrently on the same host. Parameters ---------- hosts : str A ``string`` of the comma-separate...
824b1aa6fc590995f77a901a3b3ddcd93160f69d
65,691
import os def LoadInfoDict(input_file, repacking=False): """Loads the key/value pairs from the given input target_files. It reads `META/misc_info.txt` file in the target_files input, does sanity checks and returns the parsed key/value pairs for to the given build. It's usually called early when working on inp...
e4ae00155d4aa13fef49981707c6bc5b8ac998af
65,692
def get_zaehlsprengel_gdf(year=2020): """ Get geopandas.GeoDataFrame of Zählsprengel districts from Statistik Austria """ file = f'data/OGDEXT_ZSP_1_STATISTIK_AUSTRIA_{year}0101.zip' url = f'http://data.statistik.gv.at/data/OGDEXT_ZSP_1_STATISTIK_AUSTRIA_{year}0101.zip' if not exists(file): ...
28d9e6c36b060a440cf77ec6ab4cb9741d4342d1
65,693
import os def mount_procfs(newroot, target='/proc'): """Mounts procfs on directory. """ while target.startswith('/'): target = target[1:] mnt_flags = MS_NODEV | MS_NOEXEC | MS_NOSUID |MS_RELATIME return mount( source='proc', target=os.path.join(newroot, target), f...
c66fc4f39192f7805ff33fc1f657aa304886f229
65,694
import argparse def parse_arguments(args=None) -> list: """ Returns the parsed arguments. Parameters ---------- args: List of strings to be parsed by argparse. The default None results in argparse using the values passed into sys.args. """ parser = argparse.\ Argu...
1ce5d885ffa038c21bc821bfbd7ce0c0cfd34ab7
65,695
def get_price_current(list_all_tickers: list, symbolTicker: str) -> float: """This function returns the current price of an asset Args: list_all_tickers (list): List with all assets symbolTicker (str): Tick ​​base Returns: float: returns the current price """ result = ...
04a7d00797b12075b64462b9a8ea585c526c8609
65,696
def convert_dir_regex_to_dir_prefix_regex(dir_regex): """ The patterns used to match directory names (and file names) are allowed to match a prefix of the name. This 'feature' was unintentional, but is being retained for compatibility. This means that a regex that matches a directory name can't be...
bb9843984d9a724380eab2509095fccc03e280e1
65,697
import subprocess import os def getVersionString(): """ Function return string with version information. It is performed by use one of three procedures: git describe, file in .git dir and file __VERSION__. """ version_string = None try: version_string = subprocess.check_output(['gi...
3ba922ffa404b354c787d8d5528190b448be785d
65,698
async def consume_aiter(iterable): """consume an async iterable to a list""" result = [] async for item in iterable: result.append(item) return result
897c8e9380f9c631f2dd8721884ec1ccbe462d48
65,699