content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def createSMAbasis(delta, pistonMode, pistonProj): """ Input args: <delta> is the geometric covariance matrix of actuators, it is computed elsewhere. It is a square, symmetric matrix 60x60 <pistonMode> : piston mode (will be used in sparta) This will create a basis orthogonal to pi...
216e0cd5e36ab9ea437f47b349ccffc670d3a898
24,900
def s3_put_bucket_website(s3_obj, bucketname, website_config): """ Boto3 client based Put bucket website function Args: s3_obj (obj): MCG or OBC object bucketname (str): Name of the bucket website_config (dict): Website configuration info Returns: dict : PutBucketWebsit...
a60d95ef43e5a3643edeb6dacb2b149fef1892d9
24,901
from pma_api.manage.db_mgmt import list_cloud_datasets, download_dataset, \ from pma_api.models import ApiMetadata, Task from pma_api.task_utils import upload_dataset def admin_route(): """Route to admin portal for uploading and managing datasets. .. :quickref: admin; Route to admin portal for uploading and ...
dc59d0819829553ac5224e9ed7b380201719ae79
24,902
from typing import List from typing import Tuple def check_assignment(tokenlist : List[str], current_line : int) -> Tuple[bool, List[Token.Token]]: """Checks if the given construction is of the type 'assignment'. If it is, the first value will return True and the second value will return a list of tokens. If...
2faa56afe89c7d89ff4ec6f4443d8542073bcdaa
24,903
def load_nifc_fires(): """load nifc data for 2020/2021 fire season NB this is a bit of an undocumented NIFC feature -- the data supposedly only cover 2021 but there are definitely 2020 fires included at the endpoint. This might not be true in the future. https://data-nifc.opendata.arcgis.com/datas...
97767eb2bf850e7753cab5fc945efa7b4e235b85
24,904
from datetime import datetime from unittest.mock import call from unittest.mock import patch def test_api_query_paginated_trades_pagination(mock_bitstamp): """Test pagination logic for trades works as expected. First request: 2 results, 1 valid trade (id 2) Second request: 2 results, no trades Third ...
f1bb9cd15c0b595bb9fc1bbfb7e6ce87042ff087
24,905
def eigenvalue_nonunitary_entanglement_infidelity(a, b, mx_basis): """ Returns (d^2 - 1)/d^2 * (1 - sqrt(U)), where U is the eigenvalue-unitarity of a*b^{-1} Parameters ---------- a : numpy.ndarray The first process (transfer) matrix. b : numpy.ndarray The second process (trans...
754717a951868bdc498f4f3a7bc0013c9ffe662f
24,906
import sys import os def upload_to_s3(local_filepath, file_name, s3_path, bucket_name=BUCKET_NAME): """ Returns ---------- Uploads local file to appropriate s3 key, and prints status Parameters ---------- local_filepath : str ex. 'my/local/path' file_name : str ex. 'cleaned_data.csv' or 'model.pkl'...
52b34550dc534743b15072929acc750b685044c4
24,907
def morph(word, rootlist, Indo = False, n = 5): """ Bagi sesuatu perkataan ("word"), kembalikan n analisis morphologi yang paling mungkin berdasarkan senarai akar ("rootlist"). Format output: akar, perkataan, proklitik/awalan, akhiran/enklitik, apitan, reduplikasi @param Indo: Jika benar, awalan N-...
320ee4767b87ee336df4c132fb282d2a6a987412
24,908
def get_logger(name): """ Returns a logger from the registry Parameters ---------- name : str the name indicating the logger to return Returns ------- :class:`delira.logging.base_logger.Logger` the specified logger object """ return _AVAILABLE_LOGGERS[name]
3228e2e0bff57795c590868a06276a0ec57ea985
24,909
from typing import Union from pathlib import Path import yaml def load_yaml(path: Union[str, Path], pure: bool = False) -> dict: """config.yaml file loader. This function converts the config.yaml file to `dict` object. Args: path: .yaml configuration filepath pure: If True, just load the ....
163f48dc48e8dff998ce35dd5f9f1dcfce94eeee
24,910
def InterpolatedCurveOnSurfaceUV1(thisSurface, points, tolerance, closed, closedSurfaceHandling, multiple=False): """ Returns a curve that interpolates points on a surface. The interpolant lies on the surface. Args: points (System.Collections.Generic.IEnumerable<Point2d>): List of at least two UV p...
84ef7894b7d2f3aba43d494212f900ddb683bb92
24,911
def show(request, url, alias_model, template): """List all vouched users with this group.""" group_alias = get_object_or_404(alias_model, url=url) if group_alias.alias.url != url: return redirect('groups:show_group', url=group_alias.alias.url) group = group_alias.alias in_group = group.memb...
f2fccbc267ac8ce589182ff9bdf520c0d91cf294
24,912
import re def index(): """ Home page. Displays subscription info and smart-sorted episodes. """ client = JsonClient(session["username"], session["password"]) subs = get_subscriptions(client, session["username"]) recent_episodes = smart_sort(client, session["username"]) for ep in recent_episodes: ...
5596198aa8e8f257f0f2531dd4e76d4f3ec9d23a
24,913
from typing import Optional def range( lower: int, upper: int, step: Optional[int] = None, name: Optional[str] = None ) -> Series: """ Create a Series that ranges from lower bound to upper bound. Parameters ---------- lower Lower bound value. upper Upper bound value. st...
849cb808495d89294768d8d98d7444f03eade593
24,914
def local_gpu_masked_careduce(node): """ Detects eligible CAReduce{add}(GpuElemwise{Switch}) instances and replaces them with a masked CAReduce. """ # TODO: Probably don't need this hack checking for both GpuCAReduce and its # non-gpu counterpart anymore. Just the GPU should be fine. if not...
9ca5a78cd61f1857b62c5066d724fec32751dfd5
24,915
import bisect def ticks_lt(exact_price): """ Returns a generator for all the ticks below the given price. >>> list(ticks_lt(Decimal('0.35'))) [Decimal('0.34'), Decimal('0.33'), Decimal('0.20'), Decimal('0.10'), Decimal('0.01')] >>> list(ticks_lt(Decimal('0.20'))) [Decimal('0.10'), Decimal('0....
aa291f00021e4b3bfe78c7fb406aa81beb9d3467
24,916
def _decode_to_string(to_decode): """ This function is needed for Python 3, because a subprocess can return bytes instead of a string. """ try: return to_decode.decode("utf-8") except AttributeError: # bytesToDecode was of type string before return to_decode
3a9f4ef2719f74e259e119dc1e43a9cbdd655dd5
24,917
def nn(x_dict): """ Implementation of a shallow neural network.""" # Extract Input. x = x_dict["images"] # First Hidden Layer. layer_1 = tf.layers.dense(x, 256) # Second Hidden Layer. layer_2 = tf.layers.dense(layer_1, 256) # Output Layer. output_layer = tf.layers.dense(layer_2, 10)...
6e47efcd03c335137f0ce30665978a9d38c7df3f
24,918
def find_negamax_move_alphabeta(game_state, valid_moves, depth, alpha, beta, turn_multiplier): """ NegaMax algorithm with alpha beta pruning. Alpha beta pruning eliminates the need to check all moves within the game_state tree when a better branch has been found or a branch has too low of a score. ...
de245eaa7a675af7348348d84e61972138663270
24,919
def sum_kernel(X, Y, kernels = None): """ Meta Kernel for summing multiple kernels. """ _sum = 0 for kernel in kernels: print("Doing", kernel["class"], "with parameters:", kernel["parameters"]) _sum = _sum + globals()[kernel["class"]](X, Y, **kernel["parameters"]) return _sum
a2b042b08026e4c87f028687c4521cc1e81c4af5
24,920
def pretvori_v_sekunde(niz): """ Pretvori niz, ki predstavlja dolžino skladbe v formatu hh:mm:ss v število sekund. """ h, m, s = map(int, niz.split(":")) return s + m*60 + h*3600
db0cc5872109b15e635b2b1e8731a5343d63f518
24,921
import logging def _get_profiling_data(filename): """Read a given file and parse its content for profiling data.""" data, timestamps = [], [] try: with open(filename, "r") as f: file_data = f.readlines() except Exception: logging.error("Could not read profiling data.", exc...
85f434c9aa22d60bae06205162623cde83e5a716
24,922
def parse_dataset_name(dataset_name: str) -> (str, str): """ Split the string of the dataset name into two parts: dataset source name (e.g., cnc_in_domain) and dataset part (e.g., train). :param dataset_name: :return: dataset source name (e.g., cnc_in_domain) and dataset part (e.g., train). """ ...
e308d3f29e37b5453d47a36ef2baf94454ac90d3
24,923
import os import glob def get_analytics_zoo_classpath(): """ Get and return the jar path for analytics-zoo if exists. """ if os.getenv("BIGDL_CLASSPATH"): return os.environ["BIGDL_CLASSPATH"] jar_dir = os.path.abspath(__file__ + "/../../") jar_paths = glob.glob(os.path.join(jar_dir, "s...
e56bf7e81d42de6a20e8f77159a39e78ac150804
24,924
def plot_pq(df_pq, df_pq_std=None, columns=('mae', 'r2s'), title='Performance-Quantile'): """Plot the quantile performance plot from the prepared metrics table. Args: df_pq (pd.DataFrame): The QP table information with mean values. df_pq_std (pd.DataFrame): The QP table information ...
3bd02080c74b1bf05f9f6a8cda3b0d22ac847e9f
24,925
def protoToOpenAPISchemaRecursive(lines, schemas, schemaPrefix, basename): """ Recursively create a schema from lines read from a proto file. This method is recursive because proto messages can contain internal messages and enums. If this is the case the method will call itself recursively. :param...
c011a37ddc3fa9fea7c141f24f60a178ac0f7032
24,926
import typing def to_binary(s: typing.Union[str, bytes], encoding='utf8') -> bytes: """Cast function. :param s: object to be converted to bytes. """ return s if isinstance(s, bytes) else bytes(s, encoding=encoding)
ddc442a8124b7d55618cdc06081e496930d292a5
24,927
import gzip def load_numpy(data_path, save_disk_flag=True): """Load numpy.""" if save_disk_flag: # Save space but slow f_data = gzip.GzipFile(f'{data_path}.gz', "r") data = np.load(f_data) else: data = np.load(data_path) return data
9979e2e232fcc96d5fe865ba01a4ba5d36fd1b11
24,928
def mock_weather_for_coordinates(*args, **kwargs): # noqa: F841 """Return mock data for request weather product type.""" if args[2] == aiohere.WeatherProductType[MODE_ASTRONOMY]: return astronomy_response if args[2] == aiohere.WeatherProductType[MODE_HOURLY]: return hourly_response if a...
527bd91866984cc966ff6ad2e1b438591bc7f9d2
24,929
def get_user(request, project_key): """Return the ID of the current user for the given project""" projects = request.cookies.get('projects') if projects is None: return None try: projects = json.loads(projects) except (ValueError, KeyError, TypeError): print "JSON format erro...
4edb40eb0ccece32bd1c0fc3f44ab42e97b9770c
24,930
def extract_month(cube, month): """ Slice cube to get only the data belonging to a specific month. Parameters ---------- cube: iris.cube.Cube Original data month: int Month to extract as a number from 1 to 12 Returns ------- iris.cube.Cube data cube for spec...
31e51654875abb08f727ecf6eb226a3b3b008657
24,931
def is_insert_grad_of_statement(node): """Check whether a context manager calls `insert_grad_of`. Args: node: The context manager node. Returns: Whether or not this node contains `insert_grad_of` calls. Raises: ValueError: If the `insert_grad_of` calls are mixed with other calls. """ tangent_...
f1a8494716577f349b780880210d80cc4a941c1e
24,932
import typing import random import itertools def get_word(count: typing.Union[int, typing.Tuple[int]] = 1, # pylint: disable=dangerous-default-value sep: str = ' ', func: typing.Optional[typing.Union[str, typing.Callable[[str], str]]] = None, args: typing.Tuple[str] = (), kwarg...
3d5e1f82a4f32eae88016c0a89e9295b80d382e5
24,933
def button_debug(): """ Debugger for testing websocket sent signals from RPi buttons (for now simulated in in browser) """ return render_template('button_debug.html')
4ec37f35d5c51a13299c4158279e3ef01dc66bd2
24,934
import codecs def get_int(b): """@TODO: Docs. Contribution is welcome.""" return int(codecs.encode(b, "hex"), 16)
14be8bb32e2a4c025c85223ef5dbec654611ea19
24,935
def chrom_exp_cusp(toas, freqs, log10_Amp=-7, sign_param=-1.0, t0=54000, log10_tau=1.7, idx=2): """ Chromatic exponential-cusp delay term in TOAs. :param t0: time of exponential minimum [MJD] :param tau: 1/e time of exponential [s] :param log10_Amp: amplitude of cusp :param ...
4075901c5dcbe10ad8554835c20a0a22d29f1af7
24,936
def powerspectrum_t(flist, mMax=30, rbins=50, paramname=None, parallel=True, spacing='linear'): """ Calculates the power spectrum along the angular direction for a whole simulation (see powerspectrum). Loops through snapshots in a simulation, in parallel. Uses the same radial ...
e2dd0ab1fa06a111530350e2ab2da119607dc9eb
24,937
def score(scores, main_channel, whiten_filter): """ Whiten scores using whitening filter Parameters ---------- scores: np.array (n_data, n_features, n_neigh) n_data is the number of spikes n_feature is the number features n_neigh is the number of neighboring channels conside...
b416bd38a874f6c8ee3b26b8fec35a19b0604de0
24,938
def make_title(raw_input): """Capitalize and strip""" return raw_input.title().strip()
517977638d72a8e5c8026147246739231be6258f
24,939
def perform(target, write_function=None): """ Perform an HTTP request against a given target gathering some basic timing and content size values. """ fnc = write_function or (lambda x: None) assert target connection = pycurl.Curl() connection.setopt(pycurl.URL, target) connection.s...
0cecdb6bc43acd80ebca701b4607b2013b612d93
24,940
import xml.etree.ElementTree as ET import os def load_xml_images(renderer, filename, _filter=[], by_name=False): """ Load images from a TextureAtlas XML file. Images may be filtered and are return in a list, or optionally, a dict images indexed by the name found in the xml file. :param renderer: renderer to att...
b61ffcda72769fe065f44c0ca8df5c48d955ab24
24,941
import typing def merge_property_into_method( l: Signature, r: typing.Tuple[Metadata, OutputType] ) -> Signature: """ Merges a property into a method by just using method """ return l
ae626fece9dbd36567f0b8c79cddfbe58c0a2cb4
24,942
import os def get_image_paths(dir_path, image_filename_pattern="img_{:05d}.jpg", fps=15): """each dir contains the same number of flow_x_{:05d}.jpg, flow_y_{:05d}.jpg, img_{:05d}.jpg. Index starts at 1, not 0, thus there is no img_00000.jpg, etc. """ num_rgb_images = int(len(os.listdir(dir_path)) / 3)...
5f9272285e3b0f57068d86000497e4858e8ecf1e
24,943
def _serve_archive(content_hash, file_name, mime_type): """Serve a file from the archive or by generating an external URL.""" url = archive.generate_url(content_hash, file_name=file_name, mime_type=mime_type) if url is not None: return re...
be30f5585efd229518671b99c1560d44510db2c6
24,944
def preprocess(path ,scale = 3): """ This method prepares labels and downscaled image given path of image and scale. Modcrop is used on the image label to ensure length and width of image is divisible by scale. Inputs: path: the image directory path scale: scale to ...
6b02b81dca775ad9e614b8d285d3784aec433ca2
24,945
import math def get_goal_sample_rate(start, goal): """Modifie la probabilité d'obtenir directement le but comme point selon la distance entre le départ et le but. Utile pour la précision et les performances.""" try : dx = goal[0]-start[0] dy = goal[1]-start[1] d = math.sqrt(dx * d...
a48ad7adba534455a149142cfeae9c47e3a25677
24,946
import warnings def sample_cov(prices, returns_data=False, frequency=252, log_returns=False, **kwargs): """ Calculate the annualised sample covariance matrix of (daily) asset returns. :param prices: adjusted closing prices of the asset, each row is a date and each column is a ticker/id....
3e60ef20b976bf35d9ee818c27dfb7b877fe1f3f
24,947
import argparse def str2bool(v): """Transforms string flag into boolean :param v: boolean as type or string :type v: str :return: bool or argparse error (if it's not recognized) :rtype: bool """ if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): ...
728131e1498c212d57b221aabb7e5ae4c441c4ef
24,948
from typing import Dict def read_prev_timings(junit_report_path: str) -> Dict[str, float]: """Read the JUnit XML report in `junit_report_path` and returns its timings grouped by class name. """ tree = ET.parse(junit_report_path) if tree is None: pytest.exit(f"Could not find timings in JUni...
8c796845289fc08ffb815d649c732fdd1ae626b3
24,949
def update_model(): """ Updates a model """ data = request.get_json() params = data.get('params', {'model_id': 1}) entry = Model.objects(model_id=params.model_id).first() if not entry: return {'error': ModelNotFoundError()} entry.update(**params) return entry.to_json()
8ba13df354c21e72045d319b3c47d8ef4e291182
24,950
def SmartConnect(protocol='https', host='localhost', port=443, user='root', pwd='', service="hostd", path="/sdk", preferredApiVersions=None, keyFile=None, certFile=Non...
19fafca3767b221d0b35c8377c0b367c097a2c8c
24,951
def _pseudoArrayFromScalars(scalarvalues, type): """Wrap a scalar in a buffer so it can be used as an array""" arr = _bufferPool.getBuffer() arr._check_overflow = 1 newtype = type # _numtypedict[type] arr._strides = (newtype.bytes,) arr._type = newtype arr._itemsize = newtype.bytes arr._...
ac2953eeff6b6549ef633de2728d72220e61bd76
24,952
def triangulate_ellipse(corners, num_segments=100): """Determines the triangulation of a path. The resulting `offsets` can multiplied by a `width` scalar and be added to the resulting `centers` to generate the vertices of the triangles for the triangulation, i.e. `vertices = centers + width*offsets`. Us...
feae8b79020c612185dcdcbd9f3d3b9bd897b11b
24,953
def is_dbenv_loaded(): """ Return True of the dbenv was already loaded (with a call to load_dbenv), False otherwise. """ return settings.LOAD_DBENV_CALLED
a4dc5c6b69e457aedf31f7729dd6bab0a75aaa07
24,954
def parse_python_settings_for_dmlab2d( lab2d_settings: config_dict.ConfigDict) -> Settings: """Flatten lab2d_settings into Lua-friendly properties.""" # Since config_dicts disallow "." in keys, we must use a different character, # "$", in our config and then convert it to "." here. This is particularly # im...
5cdf1d1a9a6b82e23f0dffc022bbc0a352f65766
24,955
import IPython import re def get_new_name(x: str) -> str: """ Obtains a new name for the given site. Args: x: The original name. Returns: The new name. """ y = x.lower() if y == "cervical": return "cervical_spine" m = re.match(r"^([lr])\s+(.+)$", y) i...
0481c54c43ddb58758513bd654b7d5b1a7539761
24,956
from typing import Dict from typing import Any def u2f_from_dict(data: Dict[str, Any]) -> U2F: """ Create an U2F instance from a dict. :param data: Credential parameters from database """ return U2F.from_dict(data)
53d90b86fc0a7fd44938b7eb2f9d9f178161642f
24,957
import pandas import sys def get_sequences(datafile, seq_column = "sequence_1D", test = False, test_size=100): """ Read DF, return sequences. So we do not hold the DF in memory. We could only read csv and grab the sequence column in the future. :return: """ if datafile.endswith(".csv"): ...
f8d067731f19dd9cd656e2b009c47bf44f67b057
24,958
def filterForDoxygen (contents): """ filterForDoxygen(contents) -> contents Massage the content of a python file to better suit Doxygen's expectations. """ contents = filterContents(contents) contents = filterDocStrings(contents) return contents
c216328bed4d9af656dfd61477add1a15ee34bd6
24,959
from typing import List from typing import Callable def calculate_quantum_volume( *, num_qubits: int, depth: int, num_circuits: int, seed: int, device: cirq.google.xmon_device.XmonDevice, samplers: List[cirq.Sampler], compiler: Callable[[cirq.Circuit], c...
da1f2eb072f5d91ec99be8fa6a447c2661aabb6d
24,960
import os def get_plugin_translator(plugin_path): """Returns a new ui.Translator object for plugin specified by plugin_path argument. If a file is passed, the last path component is removed. """ if os.path.isfile(plugin_path): plugin_path = os.path.split(plugin_path)[0] path = os.path....
48c6df60f88252438f2a63d81d8165c115e5a38d
24,961
def get_key(item, key_length): """ key + value = item number of words of key = key_length function returns key """ word = item.strip().split() if key_length == 0: # fix return item elif len(word) == key_length: return item else: return ' '.join(word[0:key_le...
6407d98d62a4d83bf577e82be696b6aee1f6d2e8
24,962
from typing import Tuple def identity(shape: Tuple[int, ...], gain: float = 1) -> JaxArray: """Returns the identity matrix. This initializer was proposed in `A Simple Way to Initialize Recurrent Networks of Rectified Linear Units <https://arxiv.org/abs/1504.00941>`_. Args: shape: Shape of the...
59fb436485a04b5861bfdcfbe9bf36f4084aeb3d
24,963
from typing import Optional from typing import Dict def pyreq_nlu_trytrain(httpreq_handler: HTTPRequestHandler, project_id: int, locale: str) -> Optional[Dict]: """ Get try-annotation on utterance with latest run-time NLU model for a Mix project and locale, by sending requests to Mix API endpoint with Pyt...
7103fae177535f5c7d37ce183e9d828ebdca7b7a
24,964
from typing import Tuple def month_boundaries(month: int, year: int) -> Tuple[datetime_.datetime, datetime_.datetime]: """ Return the boundary datetimes of a given month. """ start_date = datetime_.date(year, month, 1) end_date = start_date + relativedelta(months=1) return (midnight(start_date...
f727ae0d8f28bd75f0a326305d172ea45ec29982
24,965
def calculate_Hubble_flow_velocity_from_cMpc(cMpc, cosmology="Planck15"): """ Calculates the Hubble flow recession velocity from comoving distance Parameters ---------- cMpc : array-like, shape (N, ) The distance in units of comoving megaparsecs. Must be 1D or scalar. cosmology : strin...
994722494de5ae918c3f1855b1b58fec21849f7e
24,966
def join_items( *items, separator="\n", description_mode=None, start="", end="", newlines=1 ): """ joins items using separator, ending with end and newlines Args: *items - the things to join separator - what seperates items description_mode - what mode to use for description...
0df5b55f10d73600ea2f55b0e9df86c17622e779
24,967
def JacobianSpace(Slist, thetalist): """Computes the space Jacobian for an open chain robot :param Slist: The joint screw axes in the space frame when the manipulator is at the home position, in the format of a matrix with axes as the columns :param thetalist: A list of j...
e0f3fba57b2d1595a59b708a452fd2b57c6011e7
24,968
async def delete_bank(org_id: str, bank_id:str, user: users_schemas.User = Depends(is_authenticated), db:Session = Depends(get_db)): """delete a given bank of id bank_id. Args: bank_id: a unique identifier of the bank object. user: authenticates that the user is a logged ...
537159c6c19c6bb1dde02eec13f5c55932f9d6ee
24,969
from typing import Union from typing import Iterable from typing import Any def label_encode( df: pd.DataFrame, column_names: Union[str, Iterable[str], Any] ) -> pd.DataFrame: """ Convert labels into numerical data. This method will create a new column with the string "_enc" appended after the or...
62d937dc8bb02db8a099a5647bf0673005489605
24,970
import tempfile import os def chainable(func): """ If no output_path is specified, generate an intermediate file and pass it to the function. Add the path of the intermediate file to the resulting Video.intermediate_files list before returning it. If an output_path is specified, use it and then delete...
f1ee128e84b67d453d04601a3710025f13de21a2
24,971
def get_server_now_with_delta_str(timedelta): """Get the server now date string with delta""" server_now_with_delta = get_server_now_with_delta(timedelta) result = server_now_with_delta.strftime(DATE_FORMAT_NAMEX_SEARCH) return result
f555ed28ec98f9edfa62d7f52627ea06cad9513b
24,972
def GetPrimaryKeyFromURI(uri): """ example: GetPrimaryKeyFromURI(u'mujin:/\u691c\u8a3c\u52d5\u4f5c1_121122.mujin.dae') returns u'%E6%A4%9C%E8%A8%BC%E5%8B%95%E4%BD%9C1_121122' """ return uriutils.GetPrimaryKeyFromURI(uri, fragmentSeparator=uriutils.FRAGMENT_SEPARATOR_AT, primaryKeySeparator=...
49a489d02af3195ea7ed0a7f41b9fbb19bb16407
24,973
import math def normalize(score, alpha=15): """ Normalize the score to be between -1 and 1 using an alpha that approximates the max expected value """ norm_score = score/math.sqrt((score*score) + alpha) if norm_score < -1.0: return -1.0 elif norm_score > 1.0: return 1.0 else: return...
ec158416a4199d17948986dfb3f8d659d82e07b7
24,974
from datetime import datetime import pytz def get_timestamp(request): """ hhs_oauth_server.request_logging.RequestTimeLoggingMiddleware adds request._logging_start_dt we grab it or set a timestamp and return it. """ if not hasattr(request, '_logging_start_dt'): return datetime.n...
f3117a66ebfde0b1dc48591e0665c3d7120826fd
24,975
from typing import Optional from typing import List def human_size(bytes: int | float, units: Optional[List[str]] = None) -> str: """ Convert bytes into a more human-friendly format :param bytes: int Number of bytes :param units: Optional[List[str]] units used :return: str ...
9b652f0a09024c22dcefa5909c17f7b14d0183f4
24,976
def ray_casting_2d(p: Point, poly: Poly) -> bool: """Implements ray-casting algorithm to check if a point p is inside a (closed) polygon poly""" intersections = [int(rayintersectseg(p, edge)) for edge in poly.edges] return _odd(sum(intersections))
149f797bdcecce483cf87ed012fe7a21370c2ab6
24,977
def average_price(offers): """Returns the average price of a set of items. The first item is ignored as this is hopefully underpriced. The last item is ignored as it is often greatly overpriced. IMPORTANT: It is important to only trade items with are represented on the market in great numbers. This...
4849996d13e4c00d845f5fb6a5a150397c9b84f0
24,978
import sys def main(argv=sys.argv): """Main point of Entry""" return pbparser_runner( argv=argv[1:], parser=_get_parser(), args_runner_func=_args_runner, contract_runner_func=_resolved_tool_contract_runner, alog=log, setup_log_func=setup_log)
76978672961efd1c9aa60af98f6f602aabdd270d
24,979
def get_train_data(): """get all the train data from some paths Returns: X: Input data Y_: Compare data """ TrainExamples = [8, 9, 10, 11, 12, 14] # from path set_22 to set_35 path = PATH_SIMPLE + str(5) + '/' X, Y_ = generate(path, isNormalize=True) maxvalue = (get_ima...
01517db3cb4b5987b895c2b435771c745837bf65
24,980
def effective_dimension_vector(emb, normalize=False, is_cov=False): """Effective dimensionality of a set of points in space. Effection dimensionality is the number of orthogonal dimensions needed to capture the overall correlational structure of data. See Del Giudice, M. (2020). Effective Dimensionality: A...
5d4247b92216bc9e77eabbd35746c06fec22161c
24,981
def getProductMinInventory(db, productID): """ Gives back the minimum inventory for a given product :param db: database pointer :param productID: int :return: int """ # make the query and receive a single tuple (first() allows us to do this) result = db.session.query(Product).filter(Prod...
032c95685e1c578f9251d269899f4ee04d93e326
24,982
import re def read_config6(section, option, filename='', verbosity=None): #format result: {aaa:[bbb, ccc], ddd:[eee, fff], ggg:[hhh, qqq], xxx:[yyy:zzz]} """ option: section, option, filename='' format result: {aaa:bbb, ccc:ddd, eee:fff, ggg:hhh, qqq:xxx, yyy:zzz} """ fil...
e80c80b2033b10c03c7ee0b2a5e25c5739777f3f
24,983
def bboxes_iou(boxes1, boxes2): """ boxes: [xmin, ymin, xmax, ymax] format coordinates. """ boxes1 = np.array(boxes1) boxes2 = np.array(boxes2) boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1]) boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., ...
ca2083dd0138a6bd1ee741fc58739340dc1bac61
24,984
import re import os import zipfile import html def zip_all_downloadables(getZipped_n_clicks, value, session_data): """Create a downloadable zip of USER selected set of output files. Args: getZipped_n_clicks: int value: str session_data: Dash.dcc.Store(type='session') Retu...
385dc9a2d37adf26655dd11fb72a020470a104d3
24,985
import torch import collections def predict_all_task(trained_model_path, config, subject_specific): """Predict. Parameters ---------- model_path : str Description of parameter `model_path`. config : dict A dictionary of hyper-parameters used in the network. Returns ------...
ae179d41cff63b52c9836f7bbb25675618e1aa86
24,986
def hjorth(X): """ Compute Hjorth mobility and complexity of a time series. Notes ----- To speed up, it is recommended to compute D before calling this function because D may also be used by other functions whereas computing it here again will slow down. Parameters ---------- X : a...
8ca56b45e2c5af0d28d34c181cc1b6bc915e507d
24,987
def check_and_set_owner(func): """ Decorator that applies to functions expecting the "owner" name as a second argument. It will check if a user exists with this name and if so add to the request instance a member variable called owner_user pointing to the User instance corresponding to the owner. If the...
9c5ba9d0b0bb1058ddf830da5fc59df3724b2c0e
24,988
def schedule(self: Client) -> ScheduleProxy: """Delegates to a :py:class:`mcipc.rcon.je.commands.schedule.ScheduleProxy` """ return ScheduleProxy(self, 'schedule')
a8402088fa9fa697e988b2bdb8f185b14f012873
24,989
def check_permission(permission): """Returns true if the user has the given permission.""" if 'permissions' not in flask.session: return False # Admins always have access to everything. if Permissions.ADMIN in flask.session['permissions']: return True # Otherwise check if the permission is present in ...
b4c45b15a68a07140c70b3f46001f0ca6a737ea5
24,990
from datetime import datetime def get_current_max_change_version(context, start_after, school_year: int, use_change_queries: bool): """ If job is configured to use change queries, get the newest change version number from the target Ed-Fi API. Upload data to data lake. """ if use_change_querie...
49f8a2e1c1f38daa70d950c614ce711942c8a3ca
24,991
import subprocess def number_of_jobs_in_queue(): """ This functions returns the number of jobs in queue for a given user. """ # Initialize # user_name = get_username() process = subprocess.check_output(["squeue", "-u", user_name]) return len([line for line in process.split("\n") if...
83c448eba706fc5e9287c672c9396312c611c815
24,992
def Energy_value (x): """ Energy of an input signal """ y = np.sum(x**2) return y
cf2c650c20f2a7dac8bf35db21f25b8af428404e
24,993
import re def get_int(): """Read a line of text from standard input and return the equivalent int.""" while True: s = get_string(); if s is None: return None if re.search(r"^[+-]?\d+$", s): try: i = int(s, 10) if type(i) is int: #...
e6f4e1c49f4b4bc0306af50283728f016db524d7
24,994
def create_save_featvec_homogenous_time(yourpath, times, intensities, filelabel, version=0, save=True): """Produces the feature vectors for each light curve and saves them all into a single fits file. requires all light curves on the same time axis parameters: * yourpath = folder you want the file s...
29250aad4cfa1aa5bbd89b880f93a7a70a775dfb
24,995
import asyncio async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Eaton xComfort Bridge from a config entry.""" ip_address = entry.data.get(CONF_IP_ADDRESS) auth_key = entry.data.get("authkey") bridge = Bridge(ip_address, auth_key) # bridge.logger = lambda x: _LOGGER...
b24b78054c1e8236b5a29fed7287db4150f9deb0
24,996
def _cpu_string(platform_type, settings): """Generates a <platform>_<arch> string for the current target based on the given parameters.""" if platform_type == "ios": ios_cpus = settings["//command_line_option:ios_multi_cpus"] if ios_cpus: return "ios_{}".format(ios_cpus[0]) c...
7cf483c45bb209a9e3e0775538934945324281a7
24,997
def Check2DBounds(atomMatch,mol,pcophore): """ checks to see if a particular mapping of features onto a molecule satisfies a pharmacophore's 2D restrictions >>> activeFeats = [ChemicalFeatures.FreeChemicalFeature('Acceptor', Geometry.Point3D(0.0, 0.0, 0.0)), ... ChemicalFeatures.FreeChemicalFeature('Dono...
d119645de037eeaf536e290766d4dacf9c2e2f08
24,998
def get_sdk_dir(fips_dir) : """return the platform-specific SDK dir""" return util.get_workspace_dir(fips_dir) + '/fips-sdks/' + util.get_host_platform()
f3fcf05a8dd1ae0f14431a84ae570c56dd900c69
24,999