id
stringlengths
3
8
content
stringlengths
100
981k
11578268
import unittest import numpy as np try: import nifty except ImportError: nifty = None @unittest.skipUnless(nifty, "Need nifty") class TestOperations(unittest.TestCase): def _test_op_array(self, op, op_exp, inplace): shape = 3 * (64,) block_shape = 3 * (16,) x = np.random.rand(*sha...
11578307
import numpy as np class SurvivalAnalysis(object): """ This class contains methods used in survival analysis. """ def c_index(self, risk, T, C): """Calculate concordance index to evaluate model prediction. C-index calulates the fraction of all pairs of subjects whose predicted su...
11578327
import os from unittest.mock import patch, mock_open from unittest import mock import pytest import cryptowatch from cryptowatch.auth import read_config from cryptowatch import rest_endpoint def test_stream_auth_api_key_missing(): # No API key set, should raise an exception with pytest.raises(cryptowatch.er...
11578384
import numpy as np import chainer.links as L from chainer import Variable from lda2vec import dirichlet_likelihood def test_concentration(): """ Test that alpha > 1.0 on a dense vector has a higher likelihood than alpha < 1.0 on a dense vector, and test that a sparse vector has the opposite character. ""...
11578417
import pkg_resources from pikachu.drawing.drawing import Drawer, Options, draw_multiple from pikachu.math_functions import Vector import datetime class MolFileWriter: """ NOTE: This MolFileWriter purely exports atom coordinates (x and y) found by PIKAChU; these are unitless and should not be interpreted a...
11578456
class Solution: def cleanRoom(self, robot, move = [(-1, 0), (0, -1), (1, 0), (0, 1)]): def dfs(i, j, cleaned, ind): robot.clean() cleaned.add((i, j)) k = 0 for x, y in move[ind:] + move[:ind]: if (i + x, j + y) not in cleaned and robot.move(): ...
11578476
from __future__ import division import numpy as np class VogelsteinClassifier(object): """Oncogene and TSG classifier based on the 20/20 rule. Essentially the 20/20 rule states that oncogenes have at least 20% recurrent missense mutations. While tumor suppressor genes have atleast 20% deleterius mutat...
11578487
import numpy import sklearn import pandas #import eli5 import dill import xgboost import hdbscan print('All package imported succesfully')
11578511
from newspaperdemo import app from newspaperdemo.controllers import article if __name__ == '__main__': app.register_blueprint(article.mod) app.run(debug=True)
11578587
import os.path import logging import kpm.utils import re __all__ = ['new_package'] logger = logging.getLogger(__name__) DIRECTORIES = ['templates'] MANIFEST = """--- package: name: {name} author: <author> version: 1.0.0 description: {app} license: MIT # Defaults variables # i.e: # variables: # namespac...
11578592
class Solution: def minDeletionSize(self, A: List[str]) -> int: return sum(list(column) != sorted(column) for column in zip(*A))
11578668
from django.shortcuts import render from rest_framework.response import Response import json from ibm_watson import VisualRecognitionV3 from rest_framework.views import status from django.http import JsonResponse, HttpResponse from django.conf import settings def object_detection(request, picture_url): visual_recogn...
11578670
from __future__ import absolute_import, division, print_function import os import re import tensorflow as tf from absl import app, flags from albert import AlbertConfig, AlbertModel from albert_model import pretrain_model FLAGS = flags.FLAGS os.environ["CUDA_VISIBLE_DEVICES"] = "7" flags.DEFINE_enum("model_type","...
11578672
import numpy as np import napari from .utils import * # Shift, Control, Alt, Meta, Up, Down, Left, Right, PageUp, PageDown, Insert, # Delete, Home, End, Escape, Backspace, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, # F11, F12, Space, Enter, Tab KEYS = {"focus_next": "]", "focus_previous": "[", "hide_o...
11578751
from asynctest import mock from meltano.core.block.ioblock import IOBlock from meltano.core.block.parser import generate_job_id, is_command_block from meltano.core.environment import Environment class TestParserUtils: def test_is_command_block(self, tap, dbt): """Verify that the is_command_block function ...
11578901
import shutil import uuid from time import time import matplotlib.pyplot as plt import numpy as np import pandas as pd import pyspark from pyspark.sql.functions import col, rand, when from deltalake import DeltaTable spark = ( pyspark.sql.SparkSession.builder.appName("deltalake") .config("spark.jars.packages...
11578905
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^$', 'tests.views.someview'), )
11578950
print("bienvenido a nuestro cine \nIngrese su edad para consultar el precio del boleto \nSi desea dejar de agregar introduzca -1") edad = int(input("Edad: ")) while edad >= 0: if edad >= 0 and edad < 3: print("El boleto es gratis") elif edad >=3 and edad < 12: print("El boleto cuesta $10...
11578997
from http import HTTPStatus import typing class HTTPError(Exception): """Raised when an HTTP error occurs. You can raise this within a view or an error handler to interrupt request processing. # Parameters status (int or HTTPStatus): the status code of the error. detail (any): ...
11579020
import os from betamax import Betamax import pytest import xbox from xbox.tests import TestBase class TestgamerProfile(TestBase): def test_gamer_profile_init(self): settings = [{ "id": "AppDisplayName", "value": "FakeProfile" }, { "id": "DisplayPic", ...
11579049
from icevision.models.fastai.unet import backbones from icevision.models.fastai.unet.dataloaders import * from icevision.models.fastai.unet.model import * from icevision.models.fastai.unet.prediction import * from icevision.models.fastai.unet.show_results import * from icevision.soft_dependencies import SoftDependenci...
11579080
import uuid from datetime import timedelta from typing import Any, List, Optional, Tuple import pytest import temporalio.api.enums.v1 import temporalio.api.workflowservice.v1 import temporalio.common import temporalio.exceptions from temporalio.client import ( CancelWorkflowInput, Client, Interceptor, ...
11579154
from typing import Callable from web3.contract import Contract from raiden_contracts.constants import TEST_SETTLE_TIMEOUT_MIN, ChannelEvent from raiden_contracts.tests.utils import call_and_transact from raiden_contracts.utils.events import check_channel_opened, check_new_deposit def test_channel_open_with_deposit_...
11579183
from pytest_testrail.plugin import pytestrail @pytestrail.case("C1") @pytestrail.case("C1") def test_with_multiple_pytestrail_decorator() -> None: assert True
11579200
from gym_malware.envs.malware_env import MalwareEnv from gym_malware.envs.malware_score_env import MalwareScoreEnv from gym_malware.envs import utils
11579235
import shutil import os.path from paraview.simple import * from paraview import smtesting smtesting.ProcessCommandLineArguments() canex2 = OpenDataFile(smtesting.DataDir + "/Testing/Data/can.ex2") # get animation scene animationScene1 = GetAnimationScene() # update animation scene based on data timesteps animationSc...
11579249
import redis range=100 factor=32 port=6666 r = redis.StrictRedis(host='localhost', port=port, db=0, password='<PASSWORD>') # string rst = r.set('foo', 2) # update old assert rst rst = r.set('foo2', 2) # add new assert rst rst = r.setex('foo_ex', 7200, 2) assert rst # zset rst = r.zadd('zfoo', 4, 'd') assert(rst ...
11579347
from unittest import TestCase import numpy as np from qilib.data_set import DataArray, DataSet from scipy.signal import sawtooth from qtt.measurements.post_processing import ProcessSawtooth1D class TestProcessSawtooth1D(TestCase): def test_run_process_has_correct_shape(self): sample_rate = 21e7 ...
11579353
import unittest from rl_starterpack import OpenAIGym, RandomAgent, experiment class TestRandomAgent(unittest.TestCase): def test_cartpole(self): env = OpenAIGym(level='CartPole', max_timesteps=100) agent = RandomAgent(state_space=env.state_space, action_space=env.action_space) experiment...
11579437
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester dtSummaryClients = DQMEDHarvester("DTSummaryClients")
11579465
import pandas as pd import os import pickle import logging from tqdm import tqdm import sys from flashtext import KeywordProcessor import joblib import multiprocessing import numpy as np import urllib.request import zipfile import numpy as np import hashlib import json from .flags import flags logging.basicConfig(lev...
11579525
from string import ascii_lowercase as letters def shift(list, num): """ this function shifts the position of an existing list or string and returns it as a new list """ list = [x for x in list] for i in range(num): first = list[0] list.pop(0) list.append(first) return ...
11579546
import threading import time from dataclasses import asdict from datetime import datetime from typing import Optional, Tuple, List, Dict, Set from uuid import uuid4 as uuid from server.queue.fake.log_storage import FakeTaskLogStorage from server.queue.fake.safe_observer import SafeObserver from server.queue.framework ...
11579604
import pytest from multiprocessing import Pool from covidsimulation.cache import get_signature def get_parameters(arg): from covidsimulation.regions.br_saopaulo import params as br_saopaulo_params return br_saopaulo_params def test_parameters_have_stable_signature(): p = Pool(2) params = p.map(get_...
11579625
import os from glob import glob from typing import List, Tuple import cv2 import numpy as np from matplotlib import pyplot as plt from tqdm import tqdm from tools.correlational_tracker.multi_tracker_with_merge_on_fly import initialize_tracker from tools.correlational_tracker.multi_tracker_with_merge_on_fly import mer...
11579653
import unittest from sacrerouge.common.testing.util import sacrerouge_command_exists class TestDUC2004Subcommand(unittest.TestCase): def test_command_exists(self): assert sacrerouge_command_exists(['setup-dataset', 'duc2004'])
11579658
from unittest import mock import pytest from asserts import assert_cli_runner from meltano.cli import cli from meltano.core.plugin import PluginType from meltano.core.project_add_service import PluginAlreadyAddedException class TestCliRemove: @pytest.fixture(scope="class") def tap_gitlab(self, project_add_se...
11579675
import torch import numpy as np import sys import torch.nn.functional as torch_nn_func class SineGen(torch.nn.Module): """ Definition of sine generator SineGen(samp_rate, harmonic_num = 0, sine_amp = 0.1, noise_std = 0.003, voiced_threshold = 0, flag_for_pulse=False) s...
11579713
import datetime from django.db.models import Count from reviews.models import Review def get_books_read(username): """Get the list of books read by a user. :param: str username for whom the book records should be returned :return: list of dict of books read and date of posting the review """ bo...
11579740
import torch.nn as nn import torch import numpy as np from ValidationUtils import RunningAverage from ValidationUtils import MovingAverage from DataVisualization import DataVisualization from EarlyStopping import EarlyStopping from ValidationUtils import Metrics import logging class ModelTrainer: def __init__(sel...
11579744
from ..check import Check class CheckFlags(Check): '''Ensure tests don't contain any contradicting or redundant flag combinations.''' ID = 'FLAGS' def run(self, name, meta, source): if meta is None or meta.get('flags') is None: return flags = meta['flags'] onlyStrict ...
11579778
import torch import torchvision as tv import torchvision.transforms as transforms import torch.nn as nn import torch.optim as optim import argparse import numpy as np device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class LeNet(nn.Module): def __init__(self): super(LeN...
11579790
from pytest import mark from coinflip import randtests_refimpl as randtests from .examples import * @mark.parametrize(example_fields, examples) def test_examples(randtest, bits, statistic_expect, p_expect, kwargs): randtest_method = getattr(randtests, randtest) statistic, p = randtest_method(bits, **kwargs...
11579805
import os import platform from time import sleep from moviepy.editor import * def mp4_conversion(mp4_path, mp3_path): try: video = VideoFileClip(os.path.join(mp4_path)) except OSError as e: print() print(f"** ERROR: the file at {mp4_path} could not be found! **") print() t...
11579820
import json from typing import Optional import zquantum.core.graph from zquantum.core.graph import save_graph from zquantum.core.typing import Specs from zquantum.core.utils import create_object def _make_sampler(specs: Optional[Specs] = None) -> zquantum.core.graph.Sampler: if specs is None: return zqua...
11579873
class Solution: def findComplement(self, num): """ :type num: int :rtype: int """ return int("".join([str((int(i)+1)%2) for i in bin(num)[2:]]),2)
11579877
import json import requests import re import threading import time import urllib2 initial_words = ['hello', 'bob', 'how','are','you','there','twitter','static','check','cracker','apple','pear', 'after', 'finish', 'his', 'just', 'word', 'yet', 'random', 'destroy', 'monster', 'killer', 'gun', 'ravage', 'ramp', 'original...
11579905
import pkg.plant.poison.eggplant print pkg print pkg.plant print pkg.plant.poison print pkg.plant.poison.eggplant
11579916
import os, time, json, hashlib, threading cachedir = os.path.expanduser('~') + '/.cache/scrycall/' cachelimit = 86400 # 24 hours # object to handle cache for a particular query class CacheFile: def __init__(self, url): # make sure the cache directory exists checkcachedir() # cache file name is a hash of the a...
11579930
import tempfile import subprocess as sp import sys from pathlib import Path from functools import partial import pytest run_cmd = partial(sp.run, encoding="utf-8", stdout=sp.PIPE) @pytest.fixture(scope="session") def tmpdir() -> Path: with tempfile.TemporaryDirectory() as dir_name: yield Path(dir_name) ...
11579945
class MemorySet(list): def __init__(self, *args, **kwargs): """ A ordered set that keeps track of the last iteration trough it and starts at the end in the next iteration. """ self.last_len = 0 super(MemorySet, self).__init__(*args, **kwargs) def __iter__(self): ...
11579964
from pylab import * def get_trunc(particle,cluster,ic): cluster.neighbor_trunc = int(ceil((cluster.nsigma_trunc-cluster.nsigma_box)/2/\ cluster.nsigma_box)) cluster.trunc_length = cluster.nsigma_trunc*particle.sigma/2+1e-5 # loop through all clusters ista = cluster.ista[ic] ie...
11579981
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.utils import _pair from .a2c_ppo_acktr.utils import init import numpy as np import math def _calculate_fan_in_and_fan_out(tensor): dimensions = tensor.dim() if dimensions < 2: raise ValueError("Fan in and fan out c...
11579996
import torch import torch.nn.functional as F import torch.nn as nn from models.smp_layers import SimplifiedFastSMPLayer, FastSMPLayer, SMPLayer from models.utils.layers import GraphExtractor, EdgeCounter, BatchNorm from models.utils.misc import create_batch_info, map_x_to_u class SMP(torch.nn.Module): def __init_...
11580011
import matplotlib.pyplot as plt import time from copy import copy from itertools import product import Q_functions, Q_functions_optimized, G_functions from input_validator import validate_input2 # ---------------------------------------------------------------------------------------------------------------------- #...
11580019
from model.utils import * from dataloader.util_func import * class BERTCompareRetrieval(nn.Module): def __init__(self, **args): super(BERTCompareRetrieval, self).__init__() model = args['pretrained_model'] self.inner_bsz = args['inner_bsz'] self.num_labels = args['num_labels'] ...
11580059
from simple_salesforce import Salesforce from simple_salesforce.exceptions import SalesforceExpiredSession import pandas as pd import os class sf_Manager: def __init__(self): # Create a free SalesForce account: https://developer.salesforce.com/signup self.sf = Salesforce( username=os.g...
11580184
import subprocess from torchpack.utils.logging import logger import argparse import time if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str) parser.add_argument('--name', type=str) # parser.add_argument('--space', type=str) parser.add_argument('-...
11580212
from __future__ import print_function import os import tensorflow as tf import cv2 import numpy as np data_dir = 'training_set/' class_names = [ "Black", "White", "Red", "Green", "Blue", "Orange", "Yellow", "Purple", ] if (os.path.isdir(data_dir)): print('Training set folder was f...
11580242
from __future__ import absolute_import from django.test import TestCase from .models import Person class PropertyTests(TestCase): def setUp(self): self.a = Person(first_name='John', last_name='Lennon') self.a.save() def test_getter(self): self.assertEqual(self.a.full_name, '<NAME>'...
11580258
OUT_LOGGER = "ab-out" OUT_LOGGER_FORMAT = "%(message)s" TIMESTAMP_FORMAT = "%Y%m%d-%H%M%S%f" TIMESTAMP_FORMAT_TOGETHER = "%Y%m%d%H%M%S%f" NO_CACHE_TAG = "no-cache" # configuration related constants ANNOTATIONS_KEY = "annotations" # ansible playbook template in yaml PLAYBOOK_TEMPLATE = """--- - name: Containerized ver...
11580269
from requests_mock import Mocker from howfairis import Checker from howfairis import Compliance from howfairis import Repo from howfairis.readme import Readme from tests.contracts.checker import Contract from tests.helpers import list_user_files_from_local_data def get_checker(): user_files = list_user_files_from...
11580295
from app import application, flask_db, database from models import * from views import * def create_tables(): # Create table for each model if it does not exist. database.create_tables([Entry, Tag, EntryTags, FTSEntry], safe=True) if __name__ == '__main__': create_tables() # Run on port 8000 for San...
11580318
import torch import random import torchvision.transforms as transforms from PIL import Image def random_distort( img, brightness_delta=32/255., contrast_delta=0.5, saturation_delta=0.5, hue_delta=0.1): '''A color related data augmentation used in SSD. Args: img: (PIL.Image) image t...
11580360
from __future__ import print_function from __future__ import division from OpenGL.GL import GL_FRONT, GL_AMBIENT_AND_DIFFUSE, GL_SPECULAR, GL_SHININESS, glMaterialfv, glMaterialf import numpy as np import copy import time; currentMillis = lambda: int(round(time.time() * 1000)) from illuminance.helper_illuminance ...
11580385
import os import random import numpy as np import networkx as nx import matplotlib.pyplot as plt import time from mesa import Model from mesa.datacollection import DataCollector from mesa.space import MultiGrid from mesa.time import RandomActivation from .agent import Human, Wall, FireExit, Furniture, Fire, Door cl...
11580412
import win32com.client as wincl from tkinter import * def text2Speech(): text = e.get() speak = wincl.Dispatch("SAPI.SpVoice") speak.Speak(text) #window configs tts = Tk() tts.wm_title("Text to Speech") tts.geometry("225x105") tts.config(background="#708090") f=Frame(tts,height=280,width=500,b...
11580417
from braintree.search import Search class IdsSearch: ids = Search.MultipleValueNodeBuilder("ids")
11580422
from selenium.webdriver import Chrome browser = Chrome() browser.get('http://selenium.dunossauro.live/aula_11_b') browser.current_window_handle # id da janela atual wids = browser.window_handles # ids de todas as janelas def find_window(url: str): wids = browser.window_handles for window in wids: ...
11580459
from typing import Callable, List, Tuple from EventManager.Models.RobotRunnerEvents import RobotRunnerEvents class EventSubscriptionController: __call_back_register: dict = dict() @staticmethod def subscribe_to_single_event(event: RobotRunnerEvents, callback_method: Callable): EventSubscriptio...
11580471
from pyFHE.mulfft import PolyMul, TwistGen,TwistFFT,TwistIFFT from pyFHE.utils import dtot32 from pyFHE.key import SecretKey import numpy as np N = 1024 Bg = 1024 twist = TwistGen(N) for i in range(10000): a = dtot32(np.random.random(N)) * 2 ** -32 b = np.int32(np.random.randint(-Bg // 2, Bg // 2, N)) # choos...
11580476
import concurrent.futures import logging import os import queue import re import threading from pathlib import Path from typing import Optional, Tuple import boto3 import botocore from botocore.endpoint import MAX_POOL_CONNECTIONS from botocore.exceptions import NoCredentialsError from .exceptions import DirectoryDoe...
11580486
import gym import rospy import roslaunch import time import numpy as np from gym import utils, spaces from gym_gazebo.envs import gazebo_env from geometry_msgs.msg import Twist from std_srvs.srv import Empty from sensor_msgs.msg import LaserScan from gym.utils import seeding class GazeboRoundTurtlebotLidarEnv(gazeb...
11580510
from .client_proxy import ProxyKB from .client_async import AsyncKB from .client_sync import SyncKB from .server import launch __all__ = ( "SyncKB", "AsyncKB", "ProxyKB", "launch", )
11580564
import unittest import pytest from tfsnippet.examples.utils import MLConfig class MLConfigTestCase(unittest.TestCase): def test_assign(self): class MyConfig(MLConfig): a = 123 config = MyConfig() self.assertEqual(config.a, 123) config.a = 234 self.assertEqua...
11580600
import pytest import datetime from cryptocompy import helper_functions @pytest.mark.parametrize("to_ts, timestamp", [ ("FALSE", False), (datetime.datetime(2019, 5, 16, 18, 1, 48), 1558022508), (1558022508, 1558022508), ("1558022508", 1558022508), ]) def test_to_ts_args_to_timestamp(to_ts, timestamp):...
11580634
import numpy import chainer from chainer import functions, cuda from chainer import links from chainer import reporter from chainer_pointnet.models.linear_block import LinearBlock from chainer_pointnet.models.pointnet2.set_abstraction_all_block import \ SetAbstractionGroupAllModule from chainer_pointnet.models.po...
11580664
import argparse import os import sys import tabulate import time import torch import torch.nn.functional as F import curves import data import models import utils import numpy as np parser = argparse.ArgumentParser(description='DNN curve training') parser.add_argument('--dir', type=str, default='injection_Baseline50...
11580714
from sympy import (residue, Symbol, Function, sin, I, exp, log, pi, factorial, sqrt, Rational, cot) from sympy.testing.pytest import XFAIL, raises from sympy.abc import x, z, a, s def test_basic1(): assert residue(1/x, x, 0) == 1 assert residue(-2/x, x, 0) == -2 assert residue(81/x, x, ...
11580754
import basix def to_x(p): if len(p) == 1: return 100 * p[0] if len(p) == 2: return 100 * p[0] if len(p) == 3: return 100 * p[0] + 30 * p[1] def to_y(p): if len(p) == 1: return 120 if len(p) == 2: return 120 - 100 * p[1] if len(p) == 3: return 120...
11580761
import requests import hashlib from decouple import config def send_request(start_char): """ The function sends a request to the API with the URL containing first 5 characters of the hashed password """ # Concatenating first 5 characters of hashed password to the URL url = "https://api.pwnedpa...
11580764
import tensorflow as tf import numpy as np import data_loader as dl class Model: def __init__(self, train=False, fromCheckpoint=None): self.IMG_SIZE = 40 self.NUM_LABEL = 10 self.setupModel() self.dataset = dl.Dataset() if (train): self.setupTraining() ...
11580769
import torch.nn as nn import torch.nn.functional as F # https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5836943/pdf/MINF-37-na.pdf class CharRNN(nn.Module): def __init__(self, vocab_size, emb_size, max_len=320): super(CharRNN, self).__init__() self.max_len = max_len self.emb = nn.Embedding(vo...
11580773
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('cadillac.png') rows,cols,ch = img.shape() pts1 = np.float32([[50,50],[200,50],[50,200]]) pts2 = np.float32([[10,100],[200,50],[100,250]]) M = cv2.getAffineTransform(pts1,pts2) dst = cv2.warpAffine(img,M,(cols,rows)) plt.subplot(12...
11580774
from itertools import dropwhile import os import subprocess ext2lang = { '.py': 'Python', } def execute(*args): popen = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = popen.communicate() popen.wait() if errors: raise RuntimeError('Errors while exec...
11580777
import os import re from loguru import logger from flexget import plugin from flexget.event import event logger = logger.bind(name='rtorrent_magnet') pat = re.compile('xt=urn:btih:([^&/]+)') class PluginRtorrentMagnet: """ Process Magnet URI's into rtorrent compatible torrent files Magnet URI's will l...
11580799
def get_dolphot_idc(cam, ccdchip, filt, forward=True): IDC = fits_table('dolphot-idc-%s.fits' % (cam.lower())) IDC.order = 4 if forward: dirn = 'FORWARD' else: dirn = 'INVERSE' row = np.flatnonzero((IDC.direction == dirn) * (IDC.detchip == ccdchip) * ...
11580825
import datetime import locale dt = datetime.datetime(2018, 1, 1) print(dt) # 2018-01-01 00:00:00 print(dt.strftime('%A, %a, %B, %b')) # Monday, Mon, January, Jan print(locale.getlocale(locale.LC_TIME)) # (None, None) locale.setlocale(locale.LC_TIME, 'ja_JP.UTF-8') print(locale.getlocale(locale.LC_TIME)) # ('ja_JP',...
11580837
import numpy as np import sacc from srd_models import ( add_srci_lensj_ell_cl, add_lensi_lensi_ell_cl, add_srci_srcj_ell_cl, add_lens_tracers, add_src_tracers ) sacc_data = sacc.Sacc() #################################### # first lets add the tracers add_src_tracers(sacc_data) add_lens_tracers(s...
11580838
import json import pprint import sys from elasticsearch import Elasticsearch def get_top_k(query, k=5): results = es.search(index='python-code', params={"q": query})['hits']['hits'][:k] for doc in results: print("Score: ", doc['_score']) print("Docstring: ", doc['_source']['doc']['docstring'])...
11580854
from helpers import serialize_text, deserialize_text, translate, hash import yaml import sys import os import re class DB: def __init__(self, path): self.path = path self.db = {} def load(self): if os.path.exists(self.path): with open(self.path) as input_file: ...
11580859
r""" This file implements the functional equivalence test, which ensures that functional yield attributes which return the same value as a numerical setting (or in the case of the AGB yield settings, an un-modified interpolator), predict numerically similar results. In practice, this tests passes with a percent differ...
11580916
from processes.paying_for_won_item.saga import PayingForWonItem, PayingForWonItemData from processes.paying_for_won_item.saga_handler import PayingForWonItemHandler __all__ = ["PayingForWonItem", "PayingForWonItemData", "PayingForWonItemHandler"]
11580959
import geosoft.gxpy.gx as gx import geosoft.gxpy.map as gxmap import geosoft.gxpy.view as gxview import geosoft.gxpy.group as gxgroup import geosoft.gxpy.agg as gxagg import geosoft.gxpy.grid as gxgrd import geosoft.gxpy.viewer as gxviewer gxc = gx.GXpy() # create a map from grid coordinate system and extent with gxg...
11580983
class Result(): def __init__( self, status=None, full_name=None, failed_expectations=None, deprecation_warnings=None, runnable_id=None, description=None, pending_reason=None ): if failed_expectations is None:...
11580996
def main(): N = int(input()) for _ in range(N): A,B,C = map(int, input().split()) sol = False for x in range(-22, 23): if sol: break if x*x <= C: for y in range(-100, 101): if sol: break ...
11581007
from contextlib import suppress from typing import ClassVar, List from frozendict import frozendict from logger import log from test_infra import consts from test_infra.assisted_service_api import ClientFactory, InventoryClient from test_infra.consts import resources from test_infra.utils import utils from test_infra....
11581044
from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as func from torchsupport.interacting.off_policy_training import OffPolicyTraining class CRRTraining(OffPolicyTraining): def __init__(self, policy, value, agent, environment, beta=1.0, clip=None, tau=5e-3, **kwar...
11581059
from itertools import chain from enum import Enum class BertSampleProviderTypes(Enum): """ Supported format types. """ """ Default formatter """ CLASSIF_M = 0 """ Natural Language Inference samplers paper: https://www.aclweb.org/anthology/N19-1035.pdf """ QA_M = 1 ...
11581103
from matplotlib.backend_bases import FigureCanvasBase from matplotlib.backend_bases import RendererBase import matplotlib.pyplot as plt import matplotlib.transforms as transforms import matplotlib.path as path import numpy as np import os import shutil import tempfile def test_uses_per_path(): id = transforms.A...