content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def parse_field(source, loc, tokens): """ Returns the tokens of a field as key-value pair. """ name = tokens[0].lower() value = normalize_value(tokens[2]) if name == 'author' and ' and ' in value: value = [field.strip() for field in value.split(' and ')] return (name, value)
be5533cc53fc73fe84d8bd79465ef03ba22cfa5f
3,637,900
def evaluate_models_exploratory(X_normal:np.ndarray, X_te:np.ndarray, X_adv_deepfool:np.ndarray, X_adv_fgsm:np.ndarray, X_adv_pgd:np.ndarray, X_adv_dt:np.n...
17435e38512c9c158db6d6ae12ab44c38f573c61
3,637,901
def get_files_endpoint(entity_name): """ Given an entity name, generate a flask_restful `Resource` class. In `create_api_endpoints()`, these generated classes are registered with the API e.g. `api.add_resource(get_files_endpoint("Dataset"), "/datasets/<string:pid>/files")` :param entity_name: Name ...
7d2928b1b1545c9a2b7a7b44aafa64fbf7b77532
3,637,902
import re import os def get_name(path): """get the name from a repo path""" return re.sub(r"\.git$", "", os.path.basename(path))
42c410fd21e1d50270cf7703b9f054a8455c7efd
3,637,903
import os def abs_path(*paths): """Get the absolute path of the given file path. Args: *paths: path parts. Returns: An abs path string. """ return os.path.abspath(os.path.join(script_dir, '..', *paths))
d3d1b349e6df5ab1e22e913aac6e510c5bcc1cc5
3,637,904
from typing import Iterable from typing import Optional def is_valid_shipping_method( checkout: Checkout, lines: Iterable["CheckoutLineInfo"], discounts: Iterable[DiscountInfo], subtotal: Optional["TaxedMoney"] = None, ): """Check if shipping method is valid and remove (if not).""" if not chec...
01cbbc493d74057c8f2e252cfd217b3cd108b97c
3,637,905
async def load_gdq_index(): """ Returns the GDQ index (main) page, includes donation totals :return: json object """ return (await load_gdq_json(f"?type=event&id={config['event_id']}"))[0]['fields']
6d1383990a2fb98c7a42b4423f21728f4f473e1a
3,637,906
def deleteRestaurantForm(r_id): """Create form to delete existing restaurant Args: r_id: id extracted from URL """ session = createDBSession() restaurant = session.query(Restaurant).get(r_id) if restaurant is None: output = ("<p>The restaurant you're looking for doesn't exist.<...
530a03f17bb28e7967c375d7da6f6e077584cd37
3,637,907
import ast from datetime import datetime def password_account(data): """Modify account password. etcd_key: <ETCD_PREFIX>/account/<name> data: {'name': , 'pass': , 'pass2': } """ t_ret = (False, '') s_rsc = '{}/account/{}'.format(etcdc.prefix, data['name']) try: r = etcdc.read(s_rsc...
65dfec27cfa558c7a6f5758696acac063936337f
3,637,908
def split_pkg(pkg): """nice little code snippet from isuru and CJ""" if not pkg.endswith(".tar.bz2"): raise RuntimeError("Can only process packages that end in .tar.bz2") pkg = pkg[:-8] plat, pkg_name = pkg.split("/") name_ver, build = pkg_name.rsplit("-", 1) name, ver = name_ver.rsplit(...
3568fc28c54e7de16e969be627804fbb80938d65
3,637,909
def gaussian(k, x): """ gaussian function k - coefficient array, x - values """ return k[2] * np.exp( -(x - k[0]) * (x - k[0]) / (2 * k[1] * k[1])) + k[3]
f58279de58992efd34bd1fa84bbecc64e3dd52ee
3,637,910
def get_physical_locator(context, record_dict): """Get physical locator that matches the supplied uuid.""" try: query = context.session.query(models.PhysicalLocators) physical_locator = query.filter_by( uuid=record_dict['uuid'], ovsdb_identifier=record_dict['ovsdb_identif...
83067d4ad5a475a2f0ca5d22ba29837df8879609
3,637,911
def coins(n, arr): """ Counting all ways e.g.: (5,1) and (1,5) """ # Stop case if n < 0: return 0 if n == 0: return 1 ways = 0 for i in range(0, len(arr)): ways += coins(n - arr[i], arr) return ways
cb269db7aef58ae2368a6e6dc04ce6743ebd3d0e
3,637,912
def compute_diff(old, new): """ Compute a diff that, when applied to object `old`, will give object `new`. Do not modify `old` or `new`. """ if not isinstance(old, dict) or not isinstance(new, dict): return new diff = {} for key, val in new.items(): if key not in old: ...
f6e7674faa2a60be17994fbd110f8e1d67eb9886
3,637,913
import os def get_file_to_dict(fliepath,splitsign,name): """ 读取对应路径的文件,如果没有则创建 返回dict,splitsign为分隔符 """ if os.path.exists(fliepath+name+'.txt'): dict = {} with open(fliepath+name+'.txt',mode='r',encoding='utf-8') as ff: try: list = ff.read().splitlines()...
998daf4fa33453c30d6543febe275d46939113f3
3,637,914
def assign_nuts1_to_lad(c, lu=_LAD_NUTS1_LOOKUP): """Assigns nuts1 to LAD""" if c in lu.keys(): return lu[c] elif c[0] == "S": return "Scotland" elif c[0] == "W": return "Wales" elif c[0] == "N": return "Northern Ireland" else: return np.nan
7d9ceb2d2eaedf72eef8243d5880b547c989d2fb
3,637,915
async def get_all_persons(): """List of all people.""" with Session(DB.engine) as session: persons = session.query(Person).all() return [p.to_dict() for p in persons]
455533d6ee6b4139354c524d6fd6db29ff2ad123
3,637,916
from typing import List from typing import Dict def pivot_pull(pull: List[Dict[str, str]]): """Pivot so columns are measures and rows are dates.""" parsed_pull = parse_dates(pull) dates = sorted(list(set(row["sample_date"] for row in parsed_pull))) pivot = list() for date in dates: row = {...
53d945cff023c9cb0233b3198a89da1e57ba18d6
3,637,917
def _location_sensitive_score(W_query, W_fil, W_keys): """Impelements Bahdanau-style (cumulative) scoring function. This attention is described in: J. K. Chorowski, D. Bahdanau, D. Serdyuk, K. Cho, and Y. Ben- gio, “Attention-based models for speech recognition,” in Ad- vances in Neural Information Processing...
4c91f7f682c1a06303c877a81f434cb265dcb1af
3,637,918
def dh_noConv( value, pattern, limit ): """decoding helper for a single integer value, no conversion, no rounding""" return dh( value, pattern, encNoConv, decSinglVal, limit )
55c2306efc1873a283fc4ed24be6677816029122
3,637,919
def chooseFile(): """ Parameters ---------- None No parameters are specified. Returns ------- filenames: tuple A tuple that contains the list of files to be loaded. """ ## change the wd to dir containing the script curpath = os.path.dirname(os.path.realpath(__fi...
480125e9cef6e2334dd21a113fead441388b1f10
3,637,920
def reward_strategy(orig_reward, actualperf, judgeperf, weight={'TP':1, 'TN': 1, 'FP': -1, 'FN':-1}): """ """ assert list(weight.keys()) == ['TP', 'TN', 'FP', 'FN'], "Please assign weights to TP, TN, FP and FN." # assert sum(weight.values()) == 0, "Summation of weight values needs to be 0." if actua...
3bed44a11197898a94939ed2cc9a400243f604b6
3,637,921
def get_user_ids_from_primary_location_ids(domain, location_ids): """ Returns {user_id: primary_location_id, ...} """ result = ( UserES() .domain(domain) .primary_location(location_ids) .non_null('location_id') .fields(['location_id', '_id']) .run().hits ...
9707cda74324c983add4872ca4b27057b7ab8809
3,637,922
def get_next_states(state: State): """Create new states, but prioritize the following: asdjkgnmweormelfkmw Prioritize nothing... """ out = [] # First we check hallways. for i in HALLWAY_IND: # Check if the room has any crabs hall = state.rooms[i] if hall.is_empty(...
fdc270ef292ce1c1507937975743f8877844b063
3,637,923
def _build_trainstep(fcn, projector, optimizer, strategy, temp=1, tau_plus=0, beta=0, weight_decay=0): """ Build a distributed training step for SimCLR or HCL. Set tau_plus and beta to 0 for SimCLR parameters. :model: Keras projection model :optimizer: Keras optimizer :strategy: tf.dis...
2ceb7aa171835b45376f11e28fd4fe323d1ac7f1
3,637,924
import pyprind from LibrairieVideoAna import PositionTrack import os def GatherToDataframe( session, analysis, version , save = True, **kwargs ): """ Load external data (pickle files mostly) into a session dataframe or series of session dataframes columns. You can specify the analysis type and version of...
5cd2bc23c49258834ad3ed555a15f3608d9e5eb5
3,637,925
def get_environment(): """ Light-weight routine for reading the <Environment> block: does most of the work through side effects on PETRglobals """ ValidExclude = None ValidInclude = None ValidOnly = True ValidPause = 0 #PETRglobals.CodeWithPetrarch1 = True #PETRglobals.CodeWithPetrarch2...
966cb1ad713f5b0c87cdabe12475b4239d5b7469
3,637,926
def create_variables_from_samples(sample_z_logits, sample_z_logp, sample_b, batch_index, sequence_index): """ Create the variables for RELAX control variate. Assumes sampled tokens come from decoder. :param sample_z_logits: [B,T,V] tensor containing sampled processed logits created by stacking logits during...
615e73b136b16979257eb5b32ec9a696c17730be
3,637,927
from typing import OrderedDict import copy def get2DHisto_(detector,plotNumber,geometry): """ This function opens the appropiate ROOT file, extracts the TProfile2D and turns it into a Histogram, if it is a compound detector, this function takes care of the subdetectors' addition. Note t...
5759bc16686642e377c9bd37dde73374f74870ac
3,637,928
import shlex import json import traceback import time def binlog2sql(request): """ 通过解析binlog获取SQL :param request: :return: """ instance_name = request.POST.get('instance_name') save_sql = True if request.POST.get('save_sql') == 'true' else False instance = Instance.objects.get(instanc...
82cf06637024a0feb2c2ae0203cd795d3f6eb944
3,637,929
def smtp_config_generator_str(results, key, inp): """ Set server/username config. :param kwargs: Values. Refer to `:func:smtp_config_writer`. :type kwargs: dict :param key: Key for results dict. :type key: str :param inp: Input question. :type inp: str """ if results[key] is N...
f2cccfaf569f005e03bb351379db85de7146eda0
3,637,930
import logging def delete_object_by_name(name, ignore_errors=False): """ Attempts to find an object by the name given and deletes it from the scene. :param name: the name of this object :param ignore_errors: if True, no exception is raised when the object is deleted. Otherwise, you will get a ...
faff975ceb328cca8fe898075fb0cfb0decf437f
3,637,931
def default_rollout_step(policy, obs, step_num): """ The default rollout step function is the policy's compute_action function. A rollout step function allows a developer to specify the behavior that will occur at every step of the rollout--given a policy and the last observation from the env--to d...
a6e9dff784e46b9a59ae34334a027b427e8d230a
3,637,932
def perfilsersic(r_e, I_e, n, r): """Evaluate a Sersic Profile. funcion que evalua a un dado radio r el valor de brillo correspondiente a un perfil de sersic r_e : Radio de escala I_e : Intensidad de escala n : Indice de Sersic r : Radio medido desde el centr...
b8cd900d28be3fef1efc142c07012174f30c9f9d
3,637,933
import numpy as np from scipy import interpolate def background_profile(img, smo1=30, badval=None): """ helper routine to determine for the rotated image (spectrum in rows) the background using sigma clipping. """ bgimg = img.copy() nx = bgimg.shape[1] # number of points in direction of...
59b090a2c05d8a520a3c9f980885c9488bdc7615
3,637,934
def get_object(bucket,key,fname): """Given a bucket and a key, upload a file""" return aws_s3api(['get-object','--bucket',bucket,'--key',key,fname])
6687c657ba364757bd519f370c546ad9b7b033f7
3,637,935
import glob def find_file(filename): """ This helper function checks whether the file exists or not """ file_list = list(glob.glob("*.txt")) if filename in file_list: return True else: return False
42895e66e258ba960c890f871be8c261aec02852
3,637,936
import os def read(fname): """Read a file and return its content.""" with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read()
51e399082554fde2d0d8d429f8f50f743fcd0655
3,637,937
def tweetnacl_crypto_secretbox(max_messagelength=256): """ max_messagelength: maximum length of the message, in bytes. i.e., the symbolic execution will not consider messages longer than max_messagelength """ proj = tweetnaclProject() state = funcEntryState(proj, "crypto_secretbox_xsalsa20po...
b380c2848da0c271895dcf893adf1d12c5d86289
3,637,938
def parameterized_dropout(probs: Tensor, mask: Tensor, values: Tensor, random_rate: float = 0.5, epsilon: float = 0.1) -> Tensor: """ This function returns (values * mask) if random_rate == 1.0 and (value...
36d26d0deda5b4394457e235e61f334ea6dc767d
3,637,939
from typing import Optional def get_auto_scale_v_core(resource_group_name: Optional[str] = None, vcore_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAutoScaleVCoreResult: """ Represents an instance of an auto scale v...
e3eda57b7afdfe2a7e1b7e3e958b5140a7120a95
3,637,940
import json def text_output(xml,count): """Returns JSON-formatted text from the XML retured from E-Fetch""" xmldoc = minidom.parseString(xml.encode('utf-8').strip()) jsonout = [] for i in range(count): title = '' title = xmldoc.getElementsByTagName('ArticleTitle') title = parse_xml(title, i, '') pmid = ...
0c48a67b123b55ed5c8777d5fd0ad009578ba1ae
3,637,941
from datetime import datetime def datetime2str(target, fmt='%Y-%m-%d %H:%M:%S'): """ 将datetime对象转换成字符串 :param target: datetime :param fmt: string :return: string """ return datetime.datetime.strftime(target, fmt)
9111040a6136ef675929d30f3aba3eb983b45197
3,637,942
def periodic_targets_form(request, program): """ Returns a form for the periodic targets sub-section, used by the Indicator Form For historical reasons, the input is a POST of the whole indicator form sent via ajax from which a subset of fields are used to generate the returned template """ ...
62e6ef666f113c5aefda858e91c31f3dfd0bcacf
3,637,943
import sqlite3 def get_db(): """Returns an sqlite3.Connection object stored in g. Or creates it if doesn't exist yet.""" db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db
1a8be7a3d42123db213cd4c2a5968bdede92e677
3,637,944
def is_string_like(obj): # from John Hunter, types-free version """Check if obj is string.""" return isinstance(obj, basestring)
5b3b66dd0706f1f0e0257ea50ba48f463a07d6ca
3,637,945
import json def _export_gene_set_pan_genome(meth, pan_genome_id): """Export orthologs from Pangenome as external FeatureSet objects. [26] :param pan_genome_id: ID of pangenome object [26.1] :type pan_genome_id: kbtypes.KBaseGenomes.Pangenome :ui_name pan_genome_id: Pangenome ID :return: Gen...
5dfc5a6d253a66cf7ff50c736f9fdaa43a2334a8
3,637,946
import os def collect_includes(formula): """ one of the most basic things to know about a module is which include files it comes with: e.g. for boost you're supposed to #include "boost/regex/foo.h", not #include "regex/foo.h" or #include "foo.h". For most modules this list of...
54ec3516e3ef4adb80ee8d61dc11535848e8f6db
3,637,947
import logging import time from datetime import datetime def get_log_by_date(log_file, log_capture_date, log_capture_date_option, log_capture_maxlen, log_min_level): """ capture log files based on capture_date before or after fields :param log_file: :param log_capture_date epoch formatted field in mil...
1bd34317a30754e01865a17d3b96ff6252abbee8
3,637,948
def makeId(timestamp=0, machine=0, flow=0): """ using unix style timestamp, not python timestamp """ timestamp -= _base return (timestamp << 13) | (machine << 8) | flow
0443714cd5e87c93dc8ee8a156cd406f481c6d82
3,637,949
import time def _get_token(cls, token_type): """ when token expire flush,return token value """ assert token_type in ['tenant_access_token', 'app_access_token'], token_type if not hasattr(cls.request, token_type) or hasattr(cls.request, token_type) or\ time.time() >= getattr(cls.re...
15ee9c6926f929960b20ee68901f1d675f43639a
3,637,950
from typing import Iterator def chunk(it: Iterator, size: int) -> Iterator: """ Nice chunking method from: https://stackoverflow.com/a/22045226 """ it = iter(it) return iter(lambda: tuple(islice(it, size)), ())
8cd199b1d2092373a156dac74cd80b700fb70fcd
3,637,951
def sort_by_directory(path): """returns 0 if path is a directory, otherwise 1 (for sorting)""" return 1 - path.is_directory
1cd066e69885901ae1b2b167feb061e98ed5f3ed
3,637,952
import json def read_config(config): """ Read config file containing information of type and default values of fields :param config: path to config file :return: dictionary containing type and or default value for each field in the file """ dic_types = json.load(open(...
ebdf6a001f65fb2ad2c3da6015a5b8998f1fda4a
3,637,953
def is_right_hand_coordinate_system3(pose): """Checks whether the given pose follows the right-hand rule.""" n, o, a = pose[:3, 0], pose[:3, 1], pose[:3, 2] return n.dot(n).simplify() == 1 and o.dot(o).simplify() == 1 and a.dot(a).simplify() == 1 and sp.simplify(n.cross(o)) == a
f6b1fcff1d3502c78db294fe2ad496a214c13366
3,637,954
def model_airmassfit(hjd, am, rawflux, limbB1, limB2, inc, period, a_Rs, Rp_Rs, show=False): """ Return the bestfit model for the lightcurve using 4 models of airmass correction: 1. model with no airmass correction 2. model with exponential airmass correction 3. model with linear airmass correction ...
6cc74f5820aff6a36fdd89c37df141d82a558dab
3,637,955
def common_params_for_list(args, fields, field_labels): """Generate 'params' dict that is common for every 'list' command. :param args: arguments from command line. :param fields: possible fields for sorting. :param field_labels: possible field labels for sorting. :returns: a dict with params to pa...
6e432213a504b2423dca4add79c860d9bffe4ad4
3,637,956
def _finditem(obj, key): """ Check if giben key exists in an object :param obj: dictionary/list :param key: key :return: value at the key position """ if key in obj: return obj[key] for k, v in obj.items(): if isinstance(v, dict): item = _finditem(v, key) ...
0f7c5b801acfae6a66d175163d726cba22380f7c
3,637,957
def decompress(obj): """Decompress LZSS-compressed bytes or a file-like object. Shells out to decompress_file() or decompress_bytes() depending on whether or not the passed-in object has a 'read' attribute or not. Returns a bytearray.""" if hasattr(obj, 'read'): return decompress_file(obj)...
58f090f02e76e90606b7ec83d2f9567235b90213
3,637,958
def trailing_whitespace(text): """Gets trailing whitespace of text.""" trailing = "" while text and text[-1] in WHITESPACE_OR_NL_CHARS: trailing = text[-1] + trailing text = text[:-1] return trailing
ddb3fba9d41261f45a0ea3e0ffd03949950532ce
3,637,959
import numpy def rjust(a, width, fillchar=' '): """ Return an array with the elements of `a` right-justified in a string of length `width`. Calls `str.rjust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings ...
05d99fcd2600bcfee19c60b75f50af868d853a87
3,637,960
import tempfile def form_image_helper(caption_list, dummy=True, image_suffix='.jpg'): """ :param caption_list: <class 'list'> :param dummy: <class 'bool'> :param image_suffix: <class 'str'> :return: <class 'dict'> [dict of dummy images for form submission in django unittest] """ try: ...
b299ce536de33fe04821a7c1306dfff61000eed4
3,637,961
from typing import Any import inspect def is_complex_converter(obj: Any) -> bool: """Check if the object is a complex converter.`""" return isinstance(obj, ComplexConverterABC) or inspect.isclass(obj) and issubclass(obj, ComplexConverterABC)
d6069161819f348a4cec516f348ed93d59d38a74
3,637,962
def find_pool_or_vip_by_name(full_list, queried_name, fuzzy_search): """Wrapper function for searching the pools or VIPs.""" logger.debug( "Performing search for %s in %s partition", queried_name, ARGS.partition, ) if fuzzy_search: matches = find_resource_by_fuzzysearch...
bc94b5e3523f3abf8e01597d830a136ab21b23c9
3,637,963
def _get_spreadsheet_with_values(spreadsheet_id): """Gets all sheets and their cells.""" sheets = [] if not service: return sheets result = service.spreadsheets().get(spreadsheetId=spreadsheet_id, fields=FIELDS).execute() for sheet in result["sheets"]: if "merges" in sheet: ...
45ea52477dfb6dd951e4780064e8f0f51279a98a
3,637,964
def some_task(): """ Some task """ get_word_counts('python.txt') get_word_counts('go.txt') get_word_counts('erlang.txt') get_word_counts('javascript.txt') return "Task Done"
a6dcacaf22cb39b886feb4566d05b48c0e7db1e3
3,637,965
def _accelerate(f, n_devices): """JIT-compiled version of `f` running on `n_devices`.""" if n_devices == 1: return fastmath.jit(f) return fastmath.pmap(f, axis_name='batch')
f9735078b012d49e15aa16b9911b2c897f9987c1
3,637,966
from datetime import datetime def parse_shadowserver_time(time_string: Text) -> datetime.datetime: """Parse a date on the format '2018-10-17 20:36:23'""" try: return datetime.datetime.strptime(time_string[:19], '%Y-%m-%d %H:%M:%S') except: print(time_string) raise
9cf267bac24fcd4efdc73d4839493b9440c178ce
3,637,967
import random def sample_along_rays(rng, origins, directions, radii, num_samples, near, far, genspace_fn, ray_shape, sin...
0745c1e7ed152c93c49bfcf59bb0255422b018ec
3,637,968
import PIL def resize(img, size, interpolation=PIL.Image.BILINEAR): """Resize image to match the given shape. This method uses :mod:`cv2` or :mod:`PIL` for the backend. If :mod:`cv2` is installed, this function uses the implementation in :mod:`cv2`. This implementation is faster than the implementati...
fa2a407f42672e5ea91e8e2bd1c186d4ca05d98c
3,637,969
def build_punt(): """ Construye la ventana del registro del usuario""" easy = PA.dividir_puntajes("facil") medium = PA.dividir_puntajes("medio") hard = PA.dividir_puntajes("dificil") rows = len(max([easy, medium, hard], key=len)) def create_table(data, dif): return sg.Table( ...
a97dc74855ccb8e65096d74c7fe59d89d5a3f92b
3,637,970
def true_fov(M, fov_e=50): """Calulates the True Field of View (FOV) of the telescope & eyepiece pair Args: fov_e (float): FOV of eyepiece; default 50 deg M (float): Magnification of Telescope Returns: float: True Field of View (deg) """ return fov_e/M
7735135d326f3000ac60274972263a8a71648033
3,637,971
async def test_html_content_type_with_utf8_encoding(unused_tcp_port, postgres_db, database_name, async_finalizer): """Test whether API endpoints with a "text/html; charset=UTF-8" content-type work.""" configure(unused_tcp_port, database_name, postgres_db.port) html_content = "<html><body>test</body></html>...
74d76c70ede4ad7b6c65170142136a6278c39802
3,637,972
def _increment_inertia(centroid, reference_point, m, mass, cg, I): """helper method""" if m == 0.: return mass (x, y, z) = centroid - reference_point x2 = x * x y2 = y * y z2 = z * z I[0] += m * (y2 + z2) # Ixx I[1] += m * (x2 + z2) # Iyy I[2] += m * (x2 + y2) # Izz I[...
f95d8c01061243929fa1d3dd48903bedc938bbd8
3,637,973
def token_addresses( request, token_amount, number_of_tokens, blockchain_services, cached_genesis, register_tokens): """ Fixture that yields `number_of_tokens` ERC20 token addresses, where the `token_amount` (per token) is distributed among the addresses behind `b...
8c79175f3a1ca312dfb03de60262f019b74b965c
3,637,974
def saturating_sigmoid(x): """Saturating sigmoid: 1.2 * sigmoid(x) - 0.1 cut to [0, 1].""" with tf.name_scope("saturating_sigmoid", [x]): y = tf.sigmoid(x) return tf.minimum(1.0, tf.maximum(0.0, 1.2 * y - 0.1))
d779f059251cc99e40bf5d13ee2d31bc786c48b7
3,637,975
def simulate_strategy(game, strategies, init_states, func): """ Harvest an accurate average payoff with the two strategies, considering traversing all possible private cards dealt by nature game : the pyspiel game strategies : the index of player's strategy, a length two list ...
47f60a2998ed8deba95b32edfa4221d7f2d767cc
3,637,976
async def is_nsfw_and_guild_predicate(ctx): """A predicate to test if a command was run in an NSFW channel and inside a guild :param ctx: The context of the predicate """ if not ctx.guild or not ctx.channel.is_nsfw(): raise NotNSFWOrGuild() return True
20e5ec228f337fcae1e28ad12cde515be9e50f4b
3,637,977
from typing import Optional def get_account(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAccountResult: """ Get information on your DigitalOcean account. ## Example Usage Get the account: ```python import pulumi import pulumi_digitalocean as digitalocean example = di...
64758aacd0f294a2f08e60d59edec6c088942e11
3,637,978
import six def get_partition_leaders(cluster_config): """Return the current leaders of all partitions. Partitions are returned as a "topic-partition" string. :param cluster_config: the cluster :type cluster_config: kafka_utils.utils.config.ClusterConfig :returns: leaders for partitions :rtype...
07aed255fa6d2ec65854d4a5ed1ab1ada6dcca73
3,637,979
import pathlib import os import json def xyzToAtomsPositionsWrapper( xyzFileOrDir, outDir=None, outFileBaseName=None, fileExt=None, noOutFile=False): """ Wrapper for the xyzToAtomsPositions function. Returns atom positions (order) given a molecule9s) in an xyz forma...
a3e5613676414fc2cf689c978404d3913f9d4169
3,637,980
import pathlib def find_mod_names(file_path=__file__): """Find Ice module names that start with 'ice_test_'. The returned names are without the extension '.ice'. TODO: Needs to recurse in `test_` sub directories. """ directory = pathlib.Path(file_path).absolute().parent # pylint: disable=no-m...
05b85ab7b500e5ff51e5425a8b79e87e5d67291b
3,637,981
def WR(df, N=10, N1=6): """ 威廉指标 :param df: :param N: :param N1: :return: """ HIGH = df['high'] LOW = df['low'] CLOSE = df['close'] WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N)) WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1)) ...
28cccd0b5f7d0a0a772327901b838e9bf8aa862d
3,637,982
from hask3.lang.hindley_milner import Function def make_fn_type(params): """Turn type parameters into corresponding internal type system object. Returned object will represent the type of a function over the parameters. :param params: a list of type paramaters, e.g. from a type signature....
876d1d9c4243e0ed8a71b9fda2b2469519f4c89b
3,637,983
def export(request, wid): """Export the logs from the given workflow :param request: HTML request :param pk: pk of the workflow to export :return: Return a CSV download of the logs """ dataset = LogResource().export( Log.objects.filter(user=request.user, workflow__id=wid) ) # C...
ff06c49642a4ab84b7c779522a13ce56e19cc9a9
3,637,984
def _validate_valid_xml(value): """ Checks whether the given value is well-formed and valid XML. """ try: # Try to create an XML tree from the given String value. _value = XML_DECL.sub(u'', value) _ = etree.fromstring(_value.encode('utf-8')) return True except et...
dbdcce58a6dbbbaf90b98c6f56fa7f9c6f830e00
3,637,985
import importlib import pkgutil def import_submodules(package, recursive=True): """Import all submodules of a module, recursively, including subpackages :param recursive: bool :param package: package (name or actual module) :type package: str | module :rtype: dict[str, types.ModuleType] """ ...
df1756f59763adf446a6e42f92c5bb193a8740bd
3,637,986
def seasonal_pattern(season_time): """Just an arbitrary pattern, you can change it if you wish""" return np.where(season_time < 0.4, np.sin(season_time * 2), 1 / np.exp(3 * season_time))
06430ce5d3da7d44fc4a8b5e32ca4d5567b1cc15
3,637,987
def dice(labels, predictions, axis, weights=1.0, scope=None, loss_collection=tf.GraphKeys.LOSSES, reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): """Dice loss for binary segmentation. The Dice loss is one minus the Dice coefficient, and therefore this loss converges towards zero. The Dice loss between predict...
70e0e44e7d9b07350497a2c048f2bdd1c8ea952e
3,637,988
def air_density(temp, patm, pw = 0): """ Calculates the density of dry air by means of the universal gas law as a function of air temperature and atmospheric pressure. m / V = [Pw / (Rv * T)] + [Pd / (Rd * T)] where: Pd: Patm - Pw Rw: specific gas constant for water vapour ...
1af7afbf562fec105566a2c934f83c73f0be1173
3,637,989
def index(dataset: Dataset, min_df=5, inplace=False, **kwargs): """ Indexes the tokens of a textual :class:`quapy.data.base.Dataset` of string documents. To index a document means to replace each different token by a unique numerical index. Rare words (i.e., words occurring less than `min_df` times) are...
8cde5ed740e4879d62f4a73bf06d1da7b78bc22a
3,637,990
def PerpendicularFrameAt(thisCurve, t, multiple=False): """ Return a 3d frame at a parameter. This is slightly different than FrameAt in that the frame is computed in a way so there is minimal rotation from one frame to the next. Args: t (double): Evaluation parameter. Returns: ...
14216aa0091f82cb47dafe0970d685463529cfbb
3,637,991
from typing import Collection def _attributes_cosmo2dict(cosmo): """ Converts CoSMoMVPA-like attributes to a dictionary form Parameters ---------- cosmo: dict Dictionary that may contains fields 'sa', 'fa', 'a'. For any of these fields the contents can be a dict, np.ndarray (objec...
3d3369ce0a1f65cd1bc1b8629ca028a4561224ca
3,637,992
def is_instrument_port(port_name): """test if a string can be a com of gpib port""" answer = False if isinstance(port_name, str): ports = ["COM", "com", "GPIB0::", "gpib0::"] for port in ports: if port in port_name: answer = not (port == port_name) return answ...
f45f47d35a9172264d0474502b0df883685071a0
3,637,993
import os def get_anvil_path(): """Gets the anvil/ path. Returns: The full path to the anvil/ source. """ return os.path.normpath(os.path.dirname(__file__))
2b8b0b0d99764634a5307f12864d85fe9b75ad57
3,637,994
import types def share_data(value): """ Take a value and use the same value from the store, if the value isn't in the store this one becomes the shared version. """ # We don't want to change the types of strings, between str <=> unicode # and hash('a') == hash(u'a') ... so use different stores. ...
70edaad0ef52e6f6866049bcd199ef109ebb825d
3,637,995
import math def gaussian_dropout(incoming, keep_prob, mc, scale_during_training = True, name=None): """ Gaussian Dropout. Outputs the input element multiplied by a random variable sampled from a Gaussian distribution with mean 1 and either variance keep_prob*(1-keep_prob) (scale_during_training False) or (1-k...
225c88e0f45c2b319cfabfcb6c65162a5a21f778
3,637,996
import os def checkTimeStamp(op, graph, frm, to): """ Confirm the timestamp formats within the metadata did not change. :param op: :param graph: :param frm: :param to: :return: """ edge = graph.get_edge(frm, to) pred = graph.predecessors(to) if pred<2: ffile = os.pa...
527a22f3e09b64ea9398f2e793c57bb5d96960e1
3,637,997
def bottom_up_low_space(N,K,ts): """ Recursive algorithm. args: N :: int length of ts K :: int ts :: list of ints returns: res :: bool True :: if a subset of ts sums to K False :: otherwise subset :: list of tuples ...
31e810871088309fded97b2ab844c3f910c84ffb
3,637,998
import ctypes def sincpt(method, target, et, fixref, abcorr, obsrvr, dref, dvec): """ Given an observer and a direction vector defining a ray, compute the surface intercept of the ray on a target body at a specified epoch, optionally corrected for light time and stellar aberration. This routi...
7de9e6362aade6cf331ad317ac4f1c2146aa5048
3,637,999