text
stringlengths
1
927k
d = dict() l = [] for i in range(int(input())): x, y = input().split() d[y] = x l.append(y) l.sort() for i in range(len(l)): if d[l[i]] == "Percy": print(i+1) break
DATA = [ { 'name': 'Facundo', 'age': 72, 'organization': 'Platzi', 'position': 'Technical Mentor', 'language': 'python', }, { 'name': 'Luisana', 'age': 33, 'organization': 'Globant', 'position': 'UX Designer', 'language': 'javas...
# -*- coding: utf-8 -*- """ babel.messages.catalog ~~~~~~~~~~~~~~~~~~~~~~ Data structures for message catalogs. :copyright: (c) 2013 by the Babel Team. :license: BSD, see LICENSE for more details. """ import re import time from cgi import parse_header from datetime import datetime, time as time_...
import psycopg2 import psycopg2.extras import os url = os.getenv('DATABASE_URL') def connection(url): conn = psycopg2.connect(url) return conn def init_db(): con = connection(url) return con def create_tables(): conn = connection(url) curr = conn.cursor() queries = tables() for qu...
from datetime import datetime from django.db import models from django.contrib.auth.models import User class PointManager(models.Manager): """Manager for Pressure Points.""" def recently_added(self, count=10): return self.order_by('-time_added')[:count] class City(models.Model): """City the Press...
from flask import Blueprint bp = Blueprint('api', __name__, url_prefix='/api') from flask import jsonify @bp.route('/', methods=['GET']) def index(): return jsonify({"message": "This is the /api endpoint"})
#!/usr/bin/env python import json import logging import os from os import path from pathlib import Path import time from reconstruction import reconstruct from futils import timeit from tqdm import tqdm from matching import Library, Sequence, match_library import plac # Logging configuration current_file = path.b...
from . import common from audio_toolbox import sox class PitchDeformer: SUFFIX = '.pitch@n' def __init__(self, input_files_key, output_files_key, semitones): self.input_files_key = input_files_key self.output_files_key = output_files_key self.semitones = semitones def execute(sel...
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse('user:create') TOKEN_URL = reverse('user:token') ME_URL = reverse('user:me') def create_user(**params)...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
import math import configparser from util import tex_coords CONFIG_PATH = "config.ini" config = configparser.ConfigParser() config.read(CONFIG_PATH) WIDTH = config.getint("window", "width") HEIGHT = config.getint("window", "height") CAPTION = config["window"]["caption"] TICKS_PER_SEC = config.getint("game", "ticks_...
import base64 import json import logging import os import time import traceback from urllib.parse import urlparse, quote from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest from botocore.credentials import get_credentials from botocore.endpoint import BotocoreHTTPSession from botocore.sessio...
print('Hello! This is an example python file.')
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.freesurfer.utils import SurfaceSnapshots def test_SurfaceSnapshots_inputs(): input_map = dict(annot_file=dict(argstr='-annotation %s', xor=['annot_name'], ), annot_name=dict(argstr='-ann...
from sfepy.linalg import norm_l2_along_axis from quantum_common import common def fun_v(ts, coor, mode=None, region=None, ig=None): from numpy import sqrt if not mode == 'qp': return out = {} C = 0.5 r = norm_l2_along_axis(coor, axis=1) V = - C * 1.0 / r V.shape = (V.shape[0], 1, 1) ...
# -*- coding: utf-8 -*- """URLs for all views.""" from django.urls import path from djthia.dashboard import views urlpatterns = [ path('<str:oid>/detail/', views.detail, name='gearup_detail'), path('search/', views.search, name='gearup_search'), path('', views.home, name='dashboard_home'), ]
import alembic.command import alembic.config import alembic.migration import alembic.script from collections import defaultdict import copy from datetime import datetime import json import logging import os import six from sqlalchemy.engine import create_engine from sqlalchemy.engine import Engine # NOQA from sqlalche...
import argparse import os import requests from git import Repo def main(): parser = argparse.ArgumentParser(description="A tool to clone github only repositories of user or group") parser.add_argument("--u", help="target of massive download", dest='target', required=True) parser.ad...
import os basedir = os.path.abspath(os.path.dirname(__file__)) # Keeping track of various configurations of the Flask app class Config(object): ALLOWED_EXTENSIONS = set(['csv']) UPLOAD_FOLDER = './files/uploads/' DOWNLOAD_FOLDER = './files/downloads/' SECRET_KEY = os.environ.get('SECRET_KEY') or \ ...
import FWCore.ParameterSet.Config as cms from Configuration.Generator.Pythia8CommonSettings_cfi import * from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import * generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter", pythiaHepMCVerbosity = cms.untracked.bool(False), ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
from setuptools import setup, find_packages import django_gcs setup_options = { 'name': 'django-gcloud-storage', 'version': django_gcs.__version__, 'packages': find_packages(), 'author': 'Colin Su', 'author_email': 'littleq0903@gmail.com', 'license': 'MIT', 'de...
import string import spacy import pickle from nltk.stem.wordnet import WordNetLemmatizer from gensim.models import Phrases, Word2Vec from nltk.corpus import stopwords import warnings warnings.filterwarnings("ignore") class WordProcessor(): ''' This is a utility class that loads data related to processing words...
# auth0login/auth0backend.py from urllib import request from jose import jwt from social_core.backends.oauth import BaseOAuth2 from accounts.models import UserProfile class Auth0(BaseOAuth2): """Auth0 OAuth authentication backend""" name = 'auth0' SCOPE_SEPARATOR = ' ' ACCESS_TOKEN_METHOD = 'POST' ...
# # Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list ...
from __future__ import unicode_literals import boto3 import json import os import uuid from jose import jws from moto import mock_cognitoidp import sure # noqa @mock_cognitoidp def test_create_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) value = str(uuid.uuid4...
# -*- coding: utf-8 -*- import unittest from unittest.mock import MagicMock, patch from dashboard.exceptions import PageOutOfRange from dashboard.history import BuildSetsPaginated class TestBuildSets(unittest.TestCase): @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_create_buildsets_history...
from flask import abort, request from marshmallow import ValidationError from webargs.flaskparser import use_args from dataservice.extensions import db from dataservice.api.common.pagination import paginated, Pagination from dataservice.api.outcome.models import Outcome from dataservice.api.outcome.schemas import Outc...
def choose_level(n_pregunta, p_level): # Construir lógica para escoger el nivel ################################################## #pass if n_pregunta <= int(p_level): level = "basicas" elif n_pregunta <= 2 * p_level: level = "intermedias" else: level = "avanzadas" ...
""" Test the scipy based interpolator. """ import warnings import pytest import pandas as pd import numpy as np import numpy.testing as npt from ..scipygridder import ScipyGridder from ..coordinates import grid_coordinates from ..datasets.synthetic import CheckerBoard def test_scipy_gridder_same_points(): "See ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
import logging import time import urllib from contextlib import contextmanager import pyodbc import sqlalchemy as db from dagster import Field, IntSource, StringSource, check from dagster.core.storage.sql import get_alembic_config, handle_schema_errors from sqlalchemy.ext.compiler import compiles MSSQL_POOL_RECYCLE...
# Copyright The OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# coding=utf-8 """Using 2 different textures in the same Fragment Shader""" import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import grafica.transformations as tr import grafica.basic_sh...
import sys, os import numpy as np import tensorflow as tf from bert_tagging import DataProcessor, BertTagging import modeling import optimization import time from tagging_eval import score_f tf.logging.set_verbosity(tf.logging.ERROR) DEBUG = False def evaluate(FLAGS, label_list=None): gpuid = FLAGS.gpuid max_s...
#!/usr/bin/env python3 import argparse import os import subprocess import nibabel import numpy from glob import glob __version__ = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'version')).read() def run(command, env={}): merged_env = os.environ merged_env.upda...
"""Support for Azure DevOps.""" import logging from typing import Any, Dict from aioazuredevops.client import DevOpsClient import aiohttp from homeassistant.components.azure_devops.const import ( CONF_ORG, CONF_PAT, CONF_PROJECT, DATA_AZURE_DEVOPS_CLIENT, DOMAIN, ) from homeassistant.config_entrie...
#!/usr/bin/env python3 # Extensible library for opening URLs # https://docs.python.org/3/library/urllib.request.html import urllib.request from urllib.error import URLError from dprs.default_variables import DEFAULT_MIRROR_URL from dprs.exceptions import MirrorURLNotAccessible def get_contents_file_list(mirror_url:...
import pytest import random import numpy as np from numpy.random import rand import lib.algorithms as al @pytest.fixture(scope="session") def unif_1D(): """ Test case: one dimension, samples evenly distributed. """ data = np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], ...
from math import sqrt, sin, pi class Liked: def __init__(self, *args) -> None: self.data = [] for arg in args: for line in arg: self.data.append(line) def likes(self) -> dict: self.emojis = [":)", ";)", ")", ":(", ";(", "("] output = dict() ...
import os import argparse import pickle from utils import decode_from_tokens from vocabulary import Vocabulary from configuration_file import ConfigurationFile from model.encoder import SCNEncoder from model.decoder import SemSynANDecoder import h5py import torch import numpy as np if __name__ == '__main__': pars...
# TODO: Add exception checking # TODO: Use wrong uuids as input import os import cv2 import shutil import numpy as np from enum import Enum from uuid import uuid4 from pathlib import Path from dotenv import load_dotenv from fastapi import APIRouter, File, UploadFile from fastapi.responses import FileResponse load_dot...
# scaleGenerator.py # Scales are in terms of times per cycle (period) rather # than pitch. # import math SCALE = ['C', 'Cx', 'D', 'Dx', 'E', 'F', 'Fx', 'G', 'Gx', 'A', 'Ax', 'B'] def calculateOctave(baseLength): periods = [baseLength / math.exp(x*math.log(2)/12) for x in range(0, 12)] periods = [int(rou...
# # Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import pytest import pathlib from unittest.mock import patch from o3de import project_properties TEST_DE...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
checkpoint_config = dict(interval=10) log_config = dict( interval=5, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = None resume_from = None workflow = [('train', 1)] optimizer = dict(type='SGD', lr=0.001, mome...
def heapify(heap, root): newRoot = root leftChild = 2*root+1 rightChild = 2*root+2 if leftChild < len(heap) and heap[leftChild] > heap[newRoot]: newRoot = leftChild if rightChild < len(heap) and heap[rightChild] > heap[newRoot]: newRoot = rightChild if root!=newRoot: heap[root],heap[newRoot]=heap[newRoot],h...
import torch.nn as nn import torch from shalstm import SHALSTM from shalstm.utils import top_k_top_p_filtering class SHALSTMforQuestionAnswering(SHALSTM): def forward(self, input, attention_mask=None, type_ids=None, hidden=None, mems=None, return_loss=False, lm_loss=False): """ all arguments have...
# Copyright 2017 AT&T Corporation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RGsodr(RPackage): """A Global Surface Summary of the Day (GSOD) Weather Data Client for R ...
#!/usr/bin/env python import os import csv import math from geometry_msgs.msg import Quaternion from styx_msgs.msg import Lane, Waypoint import tf import rospy CSV_HEADER = ['x', 'y', 'z', 'yaw'] MAX_DECEL = 1.0 class WaypointLoader(object): def __init__(self): rospy.init_node('waypoint_loader', log...
class FFalgorithm: def __init__(self): def caculate_bandwidth(S7_PORT2,S5_PORT1,S1_PORT2,S9_PORT4,S11_PORT3,S5_PORT2,S2_PORT4,S7_PORT1,S6_PORT1,S3_PORT1,S10_PORT3,S6_PORT2,S4_PORT2): ''' link1's bandwidth '''
from __future__ import absolute_import from sentry.testutils import TestCase from clims.api.serializers.models.workbatch import WorkBatchSerializer from clims.models.work_batch import WorkBatch class WorkBatchSerializerTest(TestCase): def test_can_serialize_task(self): model = WorkBatch(id=1, name="Test...
# Generated by Django 2.1 on 2018-09-06 14:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djasana', '0007_auto_20180819_1518'), ] operations = [ migrations.AlterField( model_name='customfield', name='descrip...
from paraview.simple import * firststep = 50 #names = ['0_ts*', '0-0_ts*', '0-0-0_ts*'] names = ['0_ts*', '0-0_ts*'] for name in names: acs = FindSource(name) SetActiveSource(acs) laststep = int(acs.TimestepValues[-1]) extractTimeSteps = ExtractTimeSteps(Input=acs) extractTimeSteps.TimeStepIndices...
# # GSC-18128-1, "Core Flight Executive Version 6.7" # # Copyright (c) 2006-2019 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this fi...
"""create frame and block table Revision ID: 1fc165a90d68 Revises: Create Date: 2021-03-12 15:41:50.150507 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "1fc165a90d68" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### comma...
from django.conf.urls.defaults import * urlpatterns = patterns('ftruck.views', url(r'^$', 'mainmap', name='map'), url(r'^tweets/$', 'tweets', name='tweets') )
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=19 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode def make_circuit(n: int, input_qubit): c = cirq.Ci...
__license__ = 'MIT'
#!/usr/bin/env python # coding=utf-8 # # Block for making tree copies # from __future__ import unicode_literals from pytreex.core.block import Block __author__ = "Ondřej Dušek" __date__ = "2012" class SetGlobal(Block): def __init__(self, scenario, args): """\ Constructor, sets the arguments giv...
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u...
from django.urls import path from . import views app_name = 'links' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('vote/', views.VoteView.as_view(), name='vote'), path('votes/', views.vote, name='votes'), path('result/', views.ResultView.as_view(), name='result'), ]
# encoding: UTF-8 ''' 本文件中包含的是CTA模块的回测引擎,回测引擎的API和CTA引擎一致, 可以使用和实盘相同的代码进行回测。 ''' from __future__ import division from itertools import product import copy import os import sys import re import csv import time import multiprocessing import json import pymongo import threading from datetime import datetime from collect...
from flask import Flask, render_template, request import config import os import json import ee import time import calendar import datetime import threading import logging, logging.config, yaml from pymemcache.client.hash import Client #from google.appengine.api import memcache as mc ###############################...
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 1, 'code': 1, 'title': 'Individual ensemble forecast, control and perturbe...
# -*- coding: utf-8 -*- # source from https://github.com/keon/deep-q-learning/blob/master/dqn.py import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam EPISODES = 1000 class DQNAgent: def __init...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ Wrapper for ngram_repeat_block cuda extension """ from torch import nn from torch.autograd import Function import ngram_repeat_block_cuda class NGramRepeatBlockFunction(Function): """ forward inputs to ngram_repeat_block cuda extensi...
"""Copyright 2014 Cyrus Dasadia Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr...
from sympy import sqrt, Symbol,symbols,conjugate,I,flatten,simplify,expand from numpy import array,arange,triu,tril,nonzero,append,unique, vectorize,sum,prod from ..util import MatrixProd,Deriv,Tuples def GetAssumptions(Sym,assL): tmpA=[] for i in assL: try: tmpA.append(Sym.assumptions0[...
#!/usr/bin/env python import os import csv import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport ''' You can use this file to test your DBW code against a bag recorded with a reference implementation. The bag can be found at https://s3-us-west-1.a...
# -*- coding: utf-8 -*- """ basic constants and utility functions """ import datetime as dt import os import time import logging import inspect from decimal import Decimal import requests from functools import wraps from simplejson.errors import JSONDecodeError import pandas as pd from pyecharts.options import ( ...
""" Temperature monitoring with Intel Edison and Samsung ARTIK Cloud """ import sys import os import time from math import log import statistics from collections import deque import artikcloud from artikcloud.rest import ApiException import pyupm_grove as grove import mraa import requests # Setting credentials from t...
from dsa_queue import DSAQueue class DSAShufflingQueue(DSAQueue): def enqueue(self, obj: object) -> None: if self.is_full(): raise ValueError("Queue is full.") self._array[self._size] = obj self._size += 1 def dequeue(self) -> object: tmp = self.peek() for ...
class Optimizer(object): """Base abstract class for all optimizers Get network parameters and its gradients and create steps """ def __init__(self, params, grad_params): self.params = params self.grad_params = grad_params def step(self): pass
import logging import os import pytest from rasa_nlu import data_router, config from rasa_nlu.components import ComponentBuilder from rasa_nlu.model import Trainer from rasa_nlu.utils import zip_folder from rasa_nlu import training_data logging.basicConfig(level="DEBUG") CONFIG_DEFAULTS_PATH = "sample_configs/config...
#Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. #This program is free software; you can redistribute it and/or modify it under the terms of the BSD 3-Clause License. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ...
from AbstractObject import * class ConstantObject(AbstractObject): def __init__(self, value): super(ConstantObject, self).__init__(value._value) def generate(self, out_code): out_code.append(PUSH(self._value))
from output.models.nist_data.atomic.g_month_day.schema_instance.nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd.nistschema_sv_iv_atomic_g_month_day_pattern_2 import NistschemaSvIvAtomicGMonthDayPattern2 __all__ = [ "NistschemaSvIvAtomicGMonthDayPattern2", ]
"""Logistic Regression Classifier.""" import numpy as np from sklearn.linear_model import LogisticRegression as SKLogisticRegression from skopt.space import Real from blocktorch.model_family import ModelFamily from blocktorch.pipelines.components.estimators import Estimator from blocktorch.problem_types import Problem...
import unicornhat as unicorn import time, colorsys import random def run(params): m = [[0 for i in range(8)] for i in range(8)] while True: if 1 in m[-1]: top = [0.5 * i for i in m[-1]] elif 0.5 in m[-1]: top = [0] * 8 else: top = [random.randint(0,...
# Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from scipy.special import erfc import time from ..core.errors import InvalidConfigError def compute_integrated_acquisition(acquisition,x): ''' Used to compute the acquisition function when s...
from django.contrib import admin # Register your models here. from .models import Usuario, Preferencias admin.site.register(Usuario) admin.site.register(Preferencias)
{ # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. "variables": { "target_arch%": "x86", "library%": "static_library", "openssl_enable_asm%": 0, # only supported with the Visual Studi...
import datetime import sys import uuid from collections import Counter, namedtuple from unittest.mock import MagicMock import pendulum import pytest import prefect from prefect.client.client import Client, FlowRunInfoResult, TaskRunInfoResult from prefect.engine.cloud import CloudFlowRunner, CloudTaskRunner from pref...
#-------------------------------- # Name: fishnet_generator.py # Purpose: GSFLOW fishnet generator # Notes: ArcGIS 10.2+ Version # Python: 2.7 #-------------------------------- import argparse import ConfigParser import datetime as dt from decimal import Decimal import logging import os impor...
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test addrv2 relay """ import time from test_framework.messages import ( CAddress, msg_addrv2, ...
class ExploitFrame(object): """Exploit object""" def __init__(self, serviceInfo): self.serviceInfo = serviceInfo def exploit(self): raise NotImplementedError() def exploitSuccess(self): raise NotImplementedError()
import boto3 import botocore import Settings class SQSConnection: session = boto3.Session( aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS, aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS, ) sqs = session.client('sqs', region_name=Settings.AWS_REGION_SQS) ...
""" Units Manged By Systemctl (services) ==================================== Parsers included in this module are: ListUnits - command ``/bin/systemctl list-units`` ------------------------------------------------- UnitFiles - command ``/bin/systemctl list-unit-files`` -----------------------------------------------...
import pytest import time from ethfinex.public_client import PublicClient @pytest.fixture(scope='module') def client(): return PublicClient() @pytest.mark.usefixtures('client') class TestPublicClient(object): @staticmethod def teardown_method(): time.sleep(.5) # Avoid rate limit def test...
import copy from dataclasses import dataclass from typing import List, Optional import torch from torch.nn import CrossEntropyLoss, Module from torch.utils.data import DataLoader def federated_averaging(models: List[Module]) -> Module: global_model = copy.deepcopy(models[0]) global_weights = global_model.sta...
#coding:utf-8 # # id: bugs.core_3474 # title: Regression in joins on procedures # decription: # tracker_id: CORE-3474 # min_versions: ['2.5.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0 # resources: None substituti...
from wtforms import Form from wtforms import StringField, PasswordField from wtforms.fields.html5 import EmailField from wtforms import validators from mainapp.models.tables import User class UserCreateForm(Form): username = StringField("Usuário", [ valida...
import json from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import timezone from django.utils.translation import activate from rest_framework.test import APIClient from rest_framework_jwt.settings import api_settings from api.accounts.models import MyUser from api.team....
"""Setup learnable_primitives""" from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension from itertools import dropwhile import numpy as np from os import path def collect_docstring(lines): """Return document docstring if it exists""" lines = dropwhile(l...
# Imports Error & running as Python Scripts. """ IMPORT ERROR if your module is already imported, you can import it the same way, but if you want to access something inside in it, python will look into the module & give you an error because it's going to be back n forth, called `circular import` [bad thing] """ """ ...
from epidemic_simulation.simulation import SimulationManager import pytest @pytest.fixture def test_data(): test_calc=SimulationManager([],{'infection_r':100,'infection_p':0.99,'sickness_duration':6}) return test_calc def test_infection_prob_between_0_1(test_data): """ infection_prob must be between 0...
from transformers import EvalPrediction from sklearn.metrics import precision_recall_fscore_support import numpy as np def compute_metrics(pred: EvalPrediction): """Compute recall at the masked position """ mask = pred.label_ids != -100 # filter everything except the masked position and flatten tensor...
class VORDInstance: def __init__(self, video_id, video_path, frame_count, fps, width, height, subject_objects, trajectories, relation_instances): self.video_id = video_id self.video_path = video_path self.frame_count = frame_count self.fps = fps self.height ...