content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def deprecated() -> None: """Run the command and print a deprecated notice.""" LOG.warning("c2cwsgiutils_coverage_report.py is deprecated; use c2cwsgiutils-coverage-report instead") return main()
ea3309fc308dd969872f7a4630c137e76a3659b0
7,400
def build_syscall_Linux(syscall, arg_list, arch_bits, constraint=None, assertion = None, clmax=SYSCALL_LMAX, optimizeLen=False): """ arch_bits = 32 or 64 :) """ # Check args if( syscall.nb_args() != len(arg_list)): error("Error. Expected {} arguments, got {}".format(len(syscall.arg_types), ...
1fc9e5eadb688e58f2e6ac3de4d678e3040a1086
7,401
def gamma(x): """Diffusion error (normalized)""" CFL = x[0] kh = x[1] return ( 1. / (-2) * ( 4. * CFL ** 2 / 3 - 7. * CFL / 3 + (-23. * CFL ** 2 / 12 + 35 * CFL / 12) * np.cos(kh) + (2. * CFL ** 2 / 3 - 2 * CFL / 3) * np.cos(2 * kh)...
c8689e1388338cc4d6b1b135f09db90f0e866346
7,402
import re def copylabel(original_name): """create names/labels with the sequence (Copy), (Copy 2), (Copy 3), etc.""" copylabel = pgettext_lazy("this is a copy", "Copy") copy_re = f"\\({copylabel}( [0-9]*)?\\)" match = re.search(copy_re, original_name) if match is None: label = f"{original_...
1f838c33faf347b4219ca23083b664bda01cb9ef
7,403
def load_opts_from_mrjob_confs(runner_alias, conf_paths=None): """Load a list of dictionaries representing the options in a given list of mrjob config files for a specific runner. Returns ``[(path, values), ...]``. If a path is not found, use ``(None, {})`` as its value. If *conf_paths* is ``None``...
6ef2acc7dce0de5e467456d376a52c8078336c55
7,404
def clut8_rgb888(i): """Reference CLUT for wasp-os. Technically speaking this is not a CLUT because the we lookup the colours algorithmically to avoid the cost of a genuine CLUT. The palette is designed to be fairly easy to generate algorithmically. The palette includes all 216 web-safe colours to...
ca95c95306f7f4762add01f2ffc113f348e29d3b
7,405
def get_file_from_rcsb(pdb_id,data_type='pdb'): """ (file_name) -> file_path fetch pdb or structure factor file for pdb_id from the RCSB website Args: file_name: a pdb file name data_type (str): 'pdb' -> pdb 'xray' -> structure factor Returns: a file path for the pdb file_name """ ...
19a557a0bf4f69ba132d6d4520a124aef931f816
7,406
def parse_events(fobj): """Parse a trace-events file into {event_num: (name, arg1, ...)}.""" def get_argnames(args): """Extract argument names from a parameter list.""" return tuple(arg.split()[-1].lstrip('*') for arg in args.split(',')) events = {dropped_event_id: ('dropped', 'count')} ...
af35deff9c5b76d4d46700a738186822032d4190
7,407
def enu2ECEF(phi, lam, x, y, z, t=0.0): """ Convert ENU local coordinates (East, North, Up) to Earth centered - Earth fixed (ECEF) Cartesian, correcting for Earth rotation if needed. ENU coordinates can be transformed to ECEF by two rotations: 1. A clockwise rotation over east-axis...
494078d7c3bf9933fcc5a1b8ac62e105233722b8
7,408
def _load_container_by_name(container_name, version=None): """ Try and find a container in a variety of methods. Returns the container or raises a KeyError if it could not be found """ for meth in (database.load_container, # From the labware database _load_weird_container): # honest...
924675bc174fb8664bb2dbeb7cf21af223c73545
7,409
def get_login(discord_id): """Get login info for a specific user.""" discord_id_str = str(discord_id) logins = get_all_logins() if discord_id_str in logins: return logins[discord_id_str] return None
16b7690dd4f95df1647c7060200f3938b80993c0
7,410
import json from typing import OrderedDict def to_json_dict(json_data): """Given a dictionary or JSON string; return a dictionary. :param json_data: json_data(dict, str): Input JSON object. :return: A Python dictionary/OrderedDict with the contents of the JSON object. :raises TypeError: If the input ...
e1264d88a4424630f7348cbe7794ca072c057bdf
7,411
def get_keypoints(): """Get the COCO keypoints and their left/right flip coorespondence map.""" # Keypoints are not available in the COCO json for the test split, so we # provide them here. keypoints = [ 'nose', 'neck', 'right_shoulder', 'right_elbow', 'right_wris...
1bedcee8c5f38bdefcd00251dd95530966a41353
7,412
def has_mtu_mismatch(iface: CoreInterface) -> bool: """ Helper to detect MTU mismatch and add the appropriate OSPF mtu-ignore command. This is needed when e.g. a node is linked via a GreTap device. """ if iface.mtu != DEFAULT_MTU: return True if not iface.net: return False ...
a9415ed9fbcb276a53df8dac159f48aaac831744
7,413
def phrase_boxes_alignment(flatten_boxes, ori_phrases_boxes): """ align the bounding boxes with corresponding phrases. """ phrases_boxes = list() ori_pb_boxes_count = list() for ph_boxes in ori_phrases_boxes: ori_pb_boxes_count.append(len(ph_boxes)) strat_point = 0 for pb_boxes_num in ...
e961a90f61917f217ac6908263f5b6c74bc42b26
7,414
import tempfile import subprocess from pathlib import Path def editor(initial_contents=None, filename=None, editor=None): """ Open a text editor, user edits, return results ARGUMENTS initial_contents If not None, this string is written to the file before the editor is opened. ...
a488d20901a512e582c4e52d771bd092467d61c9
7,415
def dismiss_notification(request): """ Dismisses a notification ### Response * Status code 200 (When the notification is successsfully dismissed) { "success": <boolean: true> } * `success` - Whether the dismissal request succeeded or not * Status code...
97cbd560fd16da8ba0d081616e3e2504a2dbf8a0
7,416
def log_at_level(logger, message_level, verbose_level, msg): """ writes to log if message_level > verbose level Returns anything written in case we might want to drop down and output at a lower log level """ if message_level <= verbose_level: logger.info(msg) return True retu...
4b88ee137f7c2cb638b8a058b2dceb534329c0d9
7,417
def datafile(tmp_path_factory): """Make a temp HDF5 Ocat details file within 60 arcmin of 3c273 for obsids before 2021-Nov that persists for the testing session.""" datafile = str(tmp_path_factory.mktemp('ocat') / 'target_table.h5') update_ocat_local(datafile, target_name='3c273', resolve_name=True, rad...
16448a80385ab29ebbaef8e593f96ff0167c1fdb
7,418
def _collect_scalars(values): """Given a list containing scalars (float or int) collect scalars into a single prefactor. Input list is modified.""" prefactor = 1.0 for i in range(len(values)-1, -1, -1): if isinstance(values[i], (int, float)): prefactor *= values.pop(i) return p...
bea7e54eec16a9b29552439cd12ce29b9e82d40b
7,419
from pathlib import Path def create_output_directory(validated_cfg: ValidatedConfig) -> Path: """ Creates a top level download directory if it does not already exist, and returns the Path to the download directory. """ download_path = validated_cfg.output_directory / f"{validated_cfg.version}" ...
720f45885e177b55ddbdf492655b17275c4097f8
7,420
def presentation_logistique(regression,sig=False): """ Mise en forme des résultats de régression logistique Paramètres ---------- regression: modèle de régression de statsmodel sig: optionnel, booléen Retours ------- DataFrame : tableau de la régression logistique """ # Pa...
bef9e08f463c9bc0fbb1d737a412472ab792051e
7,421
def handle_colname_collisions(df: pd.DataFrame, mapper: dict, protected_cols: list) -> (pd.DataFrame, dict, dict): """ Description ----------- Identify mapper columns that match protected column names. When found, update the mapper and dataframe, and keep a dict of these changes to return to the...
56819ff256cc3c1bcd2062fab0cac29bce7a0c15
7,422
import codecs import json def process_file(filename): """Read a file from disk and parse it into a structured dict.""" try: with codecs.open(filename, encoding='utf-8', mode='r') as f: file_contents = f.read() except IOError as e: log.info('Unable to index file: %s, error :%s',...
864c04449cbd998394c07790858ccbdc2d4eea6d
7,423
def revive(grid: Grid, coord: Point) -> Grid: """Generates a set of all cells which can be revived near coord""" revives = set() for offset in NEIGHBOR_OFFSETS: possible_revive = addpos(coord, offset) if possible_revive in grid: continue active_count = live_around(grid, possible_revive) if active_count == ...
94e928ce9dff7015f2785e5a0186f06c4f754cda
7,424
def process_table_creation_surplus(region, exchanges_list): """Add docstring.""" ar = dict() ar["@type"] = "Process" ar["allocationFactors"] = "" ar["defaultAllocationMethod"] = "" ar["exchanges"] = exchanges_list ar["location"] = location(region) ar["parameters"] = "" ar["processDoc...
0669fce0363d807ee018b59125a13c95417294a7
7,425
import requests import json import os def upload_event(): """ Expect a well formatted event data packet (list of events) Verify the access token in the request Verify the packet if verified then send to event hub else return a failure message """ # authenticate the access token with ok...
9cb77e0319df209659877970f5b395910ad285e8
7,426
import copy def makepath_coupled(model_hybrid,T,h,ode_method,sample_rate): """ Compute paths of coupled exact-hybrid model using CHV ode_method. """ voxel = 0 # make copy of model with exact dynamics model_exact = copy.deepcopy(model_hybrid) for e in model_exact.events: e.hybridType = SLOW...
95e26ec633b5c10797a040583cbc6ad6d6ad9127
7,427
import torch def process_image_keypoints(img, keypoints, input_res=224): """Read image, do preprocessing and possibly crop it according to the bounding box. If there are bounding box annotations, use them to crop the image. If no bounding box is specified but openpose detections are available, use them to...
e30e9c9b5de106c968d538a56062fefab7c1b3ee
7,428
import html import logging import os import shutil def update_output( list_of_contents, list_of_names, list_of_dates, initiate_pipeline_n_clicks, clear_pipeline_n_clicks, append_uploads_n_clicks, refresh_uploads_n_clicks, clear_uploads_n_clicks, memory, user_login_n_clicks, ...
db5f61c4850368c3f939cc35034cad9c6b9255a5
7,429
from typing import Dict from typing import Iterable from typing import Union def _load_outputs(dict_: Dict) -> Iterable[Union[HtmlOutput, EbookConvertOutput]]: """Translates a dictionary into a list of output objects. The dictionary is assumed to have the following structure:: { 'outputs...
229eeb33ca34266a397dca56b13f004a8647e8e5
7,430
def _async_friendly_contextmanager(func): """ Equivalent to @contextmanager, except the resulting (non-async) context manager works correctly as a decorator on async functions. """ @wraps(func) def helper(*args, **kwargs): return _AsyncFriendlyGeneratorContextManager(func, args, kwargs) ...
453fb89ca52101e178e0bd2c5895804ca2cc54e6
7,431
import itertools def all_inputs(n): """ returns an iterator for all {-1,1}-vectors of length `n`. """ return itertools.product((-1, +1), repeat=n)
526dff9332cf606f56dcb0c31b5c16a0124478ed
7,432
import logging def brightness(df: pd.DataFrame, gain: float = 1.5) -> pd.DataFrame: """ Enhance image brightness. Parameters ---------- df The dataset as a dataframe. Returns ------- df A new dataframe with follwing changes: * 'filename', overwrited with new ...
1bc7778a6843f31448ebd218a1a5d2b42582ef79
7,433
def generate_winner_list(winners): """ Takes a list of winners, and combines them into a string. """ return ", ".join(winner.name for winner in winners)
2586292d4a96f63bf40c0d043111f5087c46f7a9
7,434
def stampify_url(): """The stampified version of the URL passed in args.""" url = request.args.get('url') max_pages = request.args.get('max_pages') enable_animations = bool(request.args.get('animations') == 'on') if not max_pages: max_pages = DEFAULT_MAX_PAGES _stampifier = Stampifier...
136d95adedeeddcdc4166a9bce20414e909fa21f
7,435
import os def pleasant_lgr_stand_alone_parent(pleasant_lgr_test_cfg_path, tmpdir): """Stand-alone version of lgr parent model for comparing with LGR results. """ # Edit the configuration file before the file paths within it are converted to absolute # (model.load_cfg converts the file paths) cfg =...
a097f3e4a884bcc4c350955e8b24f886fdf9e009
7,436
from re import T def twitter_channel(): """ RESTful CRUD controller for Twitter channels - appears in the administration menu Only 1 of these normally in existence @ToDo: Don't enforce """ #try: # import tweepy #except: # session.error = T("tweepy mod...
05627d4445a7c99d05c61bfef923b9d52d774512
7,437
def init_time(p, **kwargs): """Initialize time data.""" time_data = { 'times': [p['parse']], 'slots': p['slots'], } time_data.update(**kwargs) return time_data
2aff3819d561f0dc9e0c9b49702b8f3fbb6e9252
7,438
import os def welcome(): """ The code that executes at launch. It guides the user through menus and starts other functions from the other folders based on the users choices. """ clear() print(msg) print(Style.RESET_ALL) print("\n") print("Welcome!") input("Press ENTER key to be...
c9821f4133e7d52f3a59a0d4f810d9120429772a
7,439
def bsplslib_D0(*args): """ :param U: :type U: float :param V: :type V: float :param UIndex: :type UIndex: int :param VIndex: :type VIndex: int :param Poles: :type Poles: TColgp_Array2OfPnt :param Weights: :type Weights: TColStd_Array2OfReal & :param UKnots: :ty...
4c7a95448c116ef04fac36168c05a22597bc0684
7,440
def b_cross(self) -> tuple: """ Solve cross one piece at a time. Returns ------- tuple of (list of str, dict of {'CROSS': int}) Moves to solve cross, statistics (move count in ETM). Notes ----- The cube is rotated so that the white centre is facing down. The four white cro...
f0a82ea6b6634b78e4252ac264a537af87be0fc1
7,441
def get_db(): """Creates a 'SQLAlchemy' instance. Creates a 'SQLAlchemy' instance and store it to 'flask.g.db'. Before this function is called, Flask's application context must be exist. Returns: a 'SQLAlchemy' instance. """ if 'db' not in g: current_app.logger.debug('construc...
903e2e94a81112603d159f5d1186ecbc2e954afa
7,442
def retain_groundtruth(tensor_dict, valid_indices): """Retains groundtruth by valid indices. Args: tensor_dict: a dictionary of following groundtruth tensors - fields.InputDataFields.groundtruth_boxes fields.InputDataFields.groundtruth_classes fields.InputDataFields.groundtruth_confidences ...
a6681d8e6b3c8c44fa4fee9143ab57538eac2661
7,443
import json def cluster_list_node(realm, id): """ this function add a cluster node """ cluster = Cluster(ES) account = Account(ES) account_email = json.loads(request.cookies.get('account'))["email"] if account.is_active_realm_member(account_email, realm): return Response(json.dumps(cluste...
eebccc3c7c3c710fc2c26ee0dfba5481e2e2043a
7,444
import logging import os def compute_features_for_audio_file(audio_file): """ Parameters ---------- audio_file: str Path to the audio file. Returns ------- features: dict Dictionary of audio features. """ # Load Audio logging.info("Loading audio file %s" % os.path.basename(audio_file)) audio, sr = lib...
49f9a42b505d5847d5f9dae09a893b9faebc0396
7,445
def complete_json(input_data, ref_keys='minimal', input_root=None, output_fname=None, output_root=None): """ Parameters ---------- input_data : str or os.PathLike or list-of-dict Filepath to JSON with data or list of dictionaries with information about annotations r...
1a732c87670c890b406e935494ca2c51a0f0dc83
7,446
def BuildSystem(input_dir, info_dict, block_list=None): """Build the (sparse) system image and return the name of a temp file containing it.""" return CreateImage(input_dir, info_dict, "system", block_list=block_list)
4537da68b322e7d7714faa2c365ece1c67b255f2
7,447
def add_upgrades(ws, cols, lnth): """ """ for col in cols: cell = "{}1".format(col) ws[cell] = "='New_4G_Sites'!{}".format(cell) for col in cols[:2]: for i in range(2, lnth): cell = "{}{}".format(col, i) ws[cell] = "='New_4G_Sites'!{}".format(cel...
a5c33a59992976dfbdd775ce55c6017cef7d7f1d
7,448
import torch def vae_loss(recon_x, x, mu, logvar, reduction="mean"): """ Effects ------- Reconstruction + KL divergence losses summed over all elements and batch See Appendix B from VAE paper: Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014 https://arxiv.org/abs/1312.6114 ...
ecdabfd62d7e7c7aa858b36669a73e6081891f83
7,449
from functools import reduce def Or(*args): """Defines the three valued ``Or`` behaviour for a 2-tuple of three valued logic values""" def reduce_or(cmp_intervala, cmp_intervalb): if cmp_intervala[0] is True or cmp_intervalb[0] is True: first = True elif cmp_intervala[0] is No...
fc252c0129904d7ad58c18adad0b08c638b2bd11
7,450
def create_task(): """Create a new task""" data = request.get_json() # In advanced solution, a generic validation should be done if (TaskValidator._validate_title(data)): TaskPersistence.create(title=data['title']) return {'success': True, 'message': 'Task has been saved'} # Simple...
e42b06ed297b589cacedae522b81c898a01d6b72
7,451
import socket def get_socket_with_reuseaddr() -> socket.socket: """Returns a new socket with `SO_REUSEADDR` option on, so an address can be reused immediately, without waiting for TIME_WAIT socket state to finish. On Windows, `SO_EXCLUSIVEADDRUSE` is used instead. This is because ...
6edbc0f0aaaeaebd9c6d0f31257de0b4dfe7df1c
7,452
def get_systemd_services(service_names): """ :param service_names: {'service_unit_id': 'service_display_name'} e.g., {'cloudify-rabbitmq.service': 'RabbitMQ'} """ systemd_services = get_services(service_names) statuses = [] services = {} for service in systemd_services: is_servic...
523efae5fb536c9326978d84ea9055aecf47da05
7,453
import datetime from werkzeug.local import LocalProxy def json_handler(obj): """serialize non-serializable data for json""" # serialize date if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)): return unicode(obj) elif isinstance(obj, LocalProxy): return unicode(obj) else: raise Ty...
ea44a5d77e608f16458a1c3405665011f2d9c70c
7,454
def _random_prefix(sentences): """ prefix random generator input: list of input sentences output: random word """ words = _word_dict(sentences) return choice(words)
7a81b5825bc0dc2ac4b75bff40a9b76af77486a3
7,455
def user_logout(*args, **kwargs): # pylint: disable=unused-argument """ This endpoint is the landing page for the logged-in user """ # Delete the Oauth2 token for this session log.info('Logging out User: %r' % (current_user,)) delete_session_oauth2_token() logout_user() flash('You...
baaeb1f1b353eaa75bc1d81cb72a9bb931398047
7,456
def redraw_frame(image, names, aligned): """ Adds names and bounding boxes to the frame """ i = 0 unicode_font = ImageFont.truetype("DejaVuSansMono.ttf", size=17) img_pil = Image.fromarray(image) draw = ImageDraw.Draw(img_pil) for face in aligned: draw.rectangle((face[0], face[...
66adbbc42c4108855e1eea6494391957c3e91b4f
7,457
import sys import typing def _tp_relfq_name(tp, tp_name=None, assumed_globals=None, update_assumed_globals=None, implicit_globals=None): # _type: (type, Optional[Union[Set[Union[type, types.ModuleType]], Mapping[Union[type, types.ModuleType], str]]], Optional[bool]) -> str """Provides the fully qu...
b50b8a38e4e776d4a0a0da149ef45cfb90bcdf2f
7,458
from typing import Type def is_dapr_actor(cls: Type[Actor]) -> bool: """Checks if class inherits :class:`Actor`. Args: cls (type): The Actor implementation. Returns: bool: True if cls inherits :class:`Actor`. Otherwise, False """ return issubclass(cls, Actor)
1c3f5b4744cf9db91c869247ab297ffc10dcfc68
7,459
def unpickle(file): """ unpickle the data """ fo = open(file, 'rb') dict = cPickle.load(fo) fo.close() return dict
dbab180e31e7bff6ba965f48ee7a3018e2665763
7,460
def _calc_norm_gen_prob(sent_1, sent_2, mle_lambda, topic): """ Calculates and returns the length-normalized generative probability of sent_1 given sent_2. """ sent_1_len = sum([count for count in sent_1.raw_counts.values()]) return _calc_gen_prob(sent_1, sent_2, mle_lambda, topic) ** (1.0 / sent_1...
7f84f1b0de67f9d6f631ad29aa1c614d6d3f13d6
7,461
def isomorphic(l_op, r_op): """ Subject of definition, here it is equal operation. See limintations (vectorization.rst). """ if l_op.getopnum() == r_op.getopnum(): l_vecinfo = forwarded_vecinfo(l_op) r_vecinfo = forwarded_vecinfo(r_op) return l_vecinfo.bytesize == r_vecinfo.b...
e34c6928c4fdf10fed55bb20588cf3183172cab1
7,462
import numpy import math def partition5(l, left, right): """ Insertion Sort of list of at most 5 elements and return the position of the median. """ j = left for i in xrange(left, right + 1): t = numpy.copy(l[i]) for j in xrange(i, left - 1, -1): if l[j - 1][0] < t[0]: break l[j] = l[j - 1] l[j] ...
75c5c893c978e81a2b19b79c6000a2151ff6b088
7,463
def max_validator(max_value): """Return validator function that ensures upper bound of a number. Result validation function will validate the internal value of resource instance field with the ``value >= min_value`` check. Args: max_value: maximum value for new validator """ def valid...
6957f507f7140aa58a9c969a04b9bde65da54319
7,464
def standalone_job_op(name, image, command, gpus=0, cpu_limit=0, memory_limit=0, env=[], tensorboard=False, tensorboard_image=None, data=[], sync_source=None, annotations=[], metrics=['Train-accuracy:PERCENTAGE'], arena_image='cheyang/arena_launcher:v0.5', timeout_hours...
2c2c6c014fe841b6929153cd5590fa43210964ed
7,465
def load_randompdata(dataset_str, iter): """Load data.""" names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph'] objects = [] for i in range(len(names)): with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f: if sys.version_info > (3, 0): objects.appen...
353160ffd8b0474fc4c58532d1bcae80f4d6cbad
7,466
def page_to_reload(): """ Returns page that is refreshed every argument of content attribute in meta http-equiv="refresh". """ val = knob_thread.val year = int(val * 138./256 + 1880) return ( """<!DOCTYPE html> <html> <head><meta http-equiv="refresh" content=".2"> <style> h1 {{color:...
75c9a409a6dd936f23c9a54dae058fb7e8fd9e97
7,467
def svn_log_changed_path2_create(*args): """svn_log_changed_path2_create(apr_pool_t pool) -> svn_log_changed_path2_t""" return _core.svn_log_changed_path2_create(*args)
f40cf409bfb458d35cb38ba76fa93c319803a992
7,468
import os def plot_timeseries(model, radius, lon, save=False, tag=''): """ Plot the solar wind model timeseries at model radius and longitude closest to those specified. :param model: An instance of the HUXt class with a completed solution. :param radius: Radius to find the closest model radius to. ...
5538da1ee1cb62c60ba146a9709922b894a3cfca
7,469
import os import logging import csv def convert_csv_to_excel(csv_path): """ This function converts a csv file, given by its file path, to an excel file in the same directory with the same name. :param csv_path:string file path of CSV file to convert :return: string file path of converted Excel fil...
590505cdd3c53f0e860bb131d575956bae5c4031
7,470
def check_from_dict(method): """A wrapper that wrap a parameter checker to the original function(crop operation).""" @wraps(method) def new_method(self, *args, **kwargs): word_dict, = (list(args) + [None])[:1] if "word_dict" in kwargs: word_dict = kwargs.get("word_dict") ...
d45b68ccccbd4f97e585c7386f7da6547fdd86d6
7,471
def env_observation_space_info(instance_id): """ Get information (name and dimensions/bounds) of the env's observation_space Parameters: - instance_id: a short identifier (such as '3c657dbc') for the environment instance Returns: - info: a dict containing 'name' (such as 'Di...
2ee4b17a73ad49c6c63dc07f2822b0f2d1ece770
7,472
from typing import Set from typing import Dict def build_target_from_transitions( dynamics_function: TargetDynamics, initial_state: State, final_states: Set[State], ) -> Target: """ Initialize a service from transitions, initial state and final states. The set of states and the set of actions...
d1014560c05e6f3169c65725d94af20494d97f0a
7,473
from typing import Optional from datetime import datetime def citation(dll_version: Optional[str] = None) -> dict: """ Return a citation for the software. """ executed = datetime.now().strftime("%B %d, %Y") bmds_version = __version__ url = "https://pypi.org/project/bmds/" if not dll_versio...
1196e1de2c2431120467eac83701022f1b4d9840
7,474
def comment_pr_(ci_data, github_token): """Write either a staticman comment or non-staticman comment to github. """ return sequence( (comment_staticman(github_token) if is_staticman(ci_data) else comment_general), post(github_token, ci_data), lambda x: dict(status_code=x.status_c...
548f854a37fe95b83660bc2ec4012cda72317976
7,475
from re import L def response_loss_model(h, p, d_z, d_x, d_y, samples=1, use_upper_bound=False, gradient_samples=0): """ Create a Keras model that computes the loss of a response model on data. Parameters ---------- h : (tensor, tensor) -> Layer Method for building a model of y given p an...
898e72f29a9c531206d0243b8503761844468665
7,476
import numpy from datetime import datetime def get_hourly_load(session, endpoint_id, start_date, end_date): """ :param session: session for the database :param endpoint_id: id for the endpoint :param start_date: datetime object :param end_date: datetime object and: end_date >= start_date :retu...
cf619b12778edfaf27d89c43226079aafc650ac4
7,477
def startend(start=None, end=None): """Return TMIN, TAVG, TMAX.""" # Select statement sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)] if not end: # Calculate TMIN, TAVG, TMAX for dates greater than start results = session.query(*sel).\ ...
7b8f395fd177d5352b14c12902acea1a641c5df8
7,478
def configure_camera(config): """ Configures the camera. :param config: dictionary containing BARD configuration parameters optional parameters in camera. source (default 0), window size (default delegates to cv2.CAP_PROP_FRAME_WIDTH), calibration directory and roi (region of...
8accdaf9d710ff2ccff6d4ad5216611593e06ff0
7,479
def munsell_value_Moon1943(Y: FloatingOrArrayLike) -> FloatingOrNDArray: """ Return the *Munsell* value :math:`V` of given *luminance* :math:`Y` using *Moon and Spencer (1943)* method. Parameters ---------- Y *luminance* :math:`Y`. Returns ------- :class:`np.floating` or :...
7e419c8936fa49f35a5838aa7d3a5d99c93808f2
7,480
import functools import traceback def log_errors(func): """ A wrapper to print exceptions raised from functions that are called by callers that silently swallow exceptions, like render callbacks. """ @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*arg...
a15c26de36a8c784da0333382f27fc06b0ed78a0
7,481
def count_total_words(sentence_list): """ 문장 리스트에 있는 단어를 셉니다. :param sentence_list: 단어의 리스트로 구성된 문장 리스트 :return: 문장에 있는 단어의 개수 """ return sum( [count_words_per_sentence(sentence) for sentence in sentence_list] )
0abc550c26b40fd36d0b9540fc1cd001e40a7552
7,482
def translate_dbpedia_url(url): """ Convert an object that's defined by a DBPedia URL to a ConceptNet URI. We do this by finding the part of the URL that names the object, and using that as surface text for ConceptNet. This is, in some ways, abusing a naming convention in the Semantic Web. The ...
2a6b99ca59216c97dc1cfd90f1d8f4c01ad5f9f2
7,483
def setSecurityPolicy(aSecurityPolicy): """Set the system default security policy. This method should only be caused by system startup code. It should never, for example, be called during a web request. """ last = _ImplPython._defaultPolicy _ImplPython._defaultPolicy = aSecurityPolicy retur...
7063b83f1c2492b8684a43f64c9d2a49ae2ca61b
7,484
import re def map_sentence2ints(sentence): """Map a sentence to a list of words.""" word_list = re.findall(r"[\w']+|[.,!?;]", sentence) int_list = [const.INPUTVOCABULARY.index(word) for word in word_list] return np.array(int_list).astype(np.int32)
6dcb2917c817aa2e394c313fb273d466b6fb1ea9
7,485
def get_api_key( api_key_header: str = Security( APIKeyHeader(name=settings.API_KEY_HEADER, auto_error=False) ) ) -> str: """ This function checks the header and his value for correct authentication if not a 403 error is returned: - api_key_header = Security api header https://git...
50121c0d16455862552c58e7478ef383b68e71c7
7,486
def add_pred_to_test(test_df, pred_np, demo_col_list, days): """ derived from Tensorflow INPUT: - df (pandas DataFrame) - group (string) OUTPUT: - show_group_stats_viz """ test_df = test_df.copy() for c in demo_col_list: t...
aec48bd6201e1a9a1ebd6f96c4c8b7cfd9304607
7,487
def getCriticality(cvss): """ color convention fot the cells of the PDF """ if cvss == 0.0: return ("none", "#00ff00", (0, 255, 0)) if cvss < 3.1: return ("low", "#ffff00", (255, 255, 0)) if cvss < 6.1: return ("medium", "#ffc800", (255, 200, 0)) if cvss < 9.1: return...
a4167b2f576dcb361641f7fe0280c212673f0157
7,488
from typing import List def combine_groups(groups: List[np.ndarray], num_features: int) -> np.ndarray: """ Combines the given groups back into a 2d measurement matrix. Args: groups: A list of 1d, flattened groups num_features: The number of features in each measurement (D) Returns: ...
906c69fabcb62a60f12fd3c4bafc711aa971ad19
7,489
import functools def skippable(*prompts, argument=None): """ Decorator to allow a method on the :obj:`CustomCommand` to be skipped. Parameters: ---------- prompts: :obj:iter A series of prompts to display to the user when the method is being skipped. argument: :obj:`str` ...
879106f4cc0524660fb6639e56d688d40b115ac4
7,490
import torch def collate( samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False, input_feeding=True, ): """ 相对 fairseq.data.language_pair_dataset.collate 的区别是: 1. prev_output_tokens的key不再是target,而是 prev_output_tokens(因为自定义了prev_output_to...
0343a5adb70c163599b91e9742b5302c1482cca8
7,491
import hashlib def _cache_name(address): """Generates the key name of an object's cache entry""" addr_hash = hashlib.md5(address).hexdigest() return "unsub-{hash}".format(hash=addr_hash)
6933b1170933df5e3e57af03c81322d68a46d91f
7,492
def format_currency( value: Decimal, currency: str | None = None, show_if_zero: bool = False, invert: bool = False, ) -> str: """Format a value using the derived precision for a specified currency.""" if not value and not show_if_zero: return "" if value == ZERO: return g.led...
197dc15c799e1866526a944e0f1f8217e97cf785
7,493
import os from pathlib import Path from typing import Union from sys import version def guess_ghostscript() -> str: """Guess the path to ghostscript. Only guesses well on Windows. Should prevent people from needing to add ghostscript to PATH. """ if os.name != 'nt': return 'gs' # I'm not sure...
09e8761185f6029025d8d6cc6861672870e781b2
7,494
def supplemental_div(content): """ Standardize supplemental content listings Might not be possible if genus and tree content diverge """ return {'c': content}
b42e868ef32f387347cd4a97328794e6628fe634
7,495
def viewTypes(): """View types of item when sent through slash command""" user_id, user_name, channel_id = getUserData(request.form) checkUser(user_id) itemType = request.form.get('text') try: text = viewTypesItems(itemType) except ItemNotInPantry: reply = "Sorry! But either t...
aea7633a1092c68a5ccf3a5619eee9d74dafdca2
7,496
def load_and_preprocess(): """ Load the data (either train.csv or test.csv) and pre-process it with some simple transformations. Return in the correct form for usage in scikit-learn. Arguments --------- filestr: string string pointing to csv file to load into pandas Returns ...
3202c4aaf76af0695594c39641dd4892b1215d97
7,497
from datetime import datetime def _dates2absolute(dates, units): """ Absolute dates from datetime object Parameters ---------- dates : datetime instance or array_like of datetime instances Instances of pyjams.datetime class units : str 'day as %Y%m%d.%f', 'month as %Y%m.%f', o...
ef823887ec410d7f7d0c5c54d12005ab35744c0c
7,498
def Mix_GetNumMusicDecoders(): """Retrieves the number of available music decoders. The returned value can differ between runs of a program due to changes in the availability of the shared libraries required for supporting different formats. Returns: int: The number of available music ...
a91b84c42701cdaeb7f400a3091bb869e477ff06
7,499