text stringlengths 2 999k |
|---|
from typing import TypeVar, Callable
import unittest
from ._types import TestMethod
_F = TypeVar("_F", bound=TestMethod)
def test(method: _F) -> _F:
"""Decorator that flags a method as a test method."""
method._dectest_test = True # type: ignore
return method
def before(method: _F) -> _F:
"""Deco... |
# Databricks notebook source
# MAGIC %md
# MAGIC # CCU013_08 Paper subset data to cohort
# MAGIC
# MAGIC **Description**
# MAGIC
# MAGIC This notebook subsets the covid trajectory, severity and events tables to the cohort used for the phenotype severity paper.
# MAGIC
# MAGIC **Project(s)** CCU0013
# MAGIC
# MAG... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import re
from keyword import kwlist
from ._compat import isidentifier
dict_list = [x for x in dict.__dict__]
kwset = set(kwlist + dict_list) # this is faster than iskeyword()
pat_identifier = re.compile(r"^[a-zA-Z_]\w*$")
def is_invalid_key(s):
# type: ... |
# Owner(s): ["oncall: fx"]
import torch
import torch.fx.experimental.fx_acc.acc_ops as acc_ops
from torch.testing._internal.common_fx2trt import AccTestCase, InputTensorSpec
from parameterized import parameterized
from torch.testing._internal.common_utils import run_tests
class TestReshapeConverter(AccTestCase):
... |
from __future__ import print_function, division, absolute_import
import time
import matplotlib
matplotlib.use('Agg') # fix execution of tests involving matplotlib on travis
import numpy as np
import six.moves as sm
import cv2
from scipy import ndimage
import imgaug as ia
from imgaug import augmenters as iaa
from im... |
import sys
from setuptools import setup, find_packages
install_requires = [
'boto3>=1.2.3,<2.0',
'clint>0.5,<1.0',
'PyYAML>=3,<4.0',
'troposphere==2.0',
'Jinja2>=2.8,<3.0',
'six>1.9,<2.0'
]
# as of Python >= 2.7 argparse module is maintained within Python.
if sys.version_info < (2, 7):
in... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
target = '1kB'
radeg = np.pi/180
def cart_to_pol(x,y):
r = np.sqrt(x**2 + y**2)
phi = np.arctan2(y,x)
return r, phi
def pol_to_cart(r,phi):
x = r*np.cos(... |
import codecs
import os
import re
from setuptools import find_packages, setup
###############################################################################
# Using setup.py from Attrs as a template for finding components, awesome config.
# Original reference: https://github.com/python-attrs/attrs/blob/master/setup.... |
from random import randint
from os import system
c = 0
#Limpa tela
system('cls')
print('=-'*20)
print('VAMOS JOGAR PAR OU IMPAR')
print('=-'*20)
#Loop do programa
while True:
n = int(input('Diga um valor: '))
computador = randint (0, 10)
while True:
decisao = str(input('Par ou impar [P/I] ')).u... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
# Directly download tasks when nlp format is different than original dataset
SQUAD_TASKS = {"squad_v1", "squad_v2"}
DIRECT_DOWNLOAD_TASKS_TO_DATA_URLS = {
"wsc": f"https://dl.fbaipublicfiles.com/glue/superglue/data/v2/WSC.zip",
"multirc": f"https://dl.fbaipublicfiles.com/glue/superglue/data/v2/MultiRC.zip",
... |
import json
from types import SimpleNamespace
with open('./config/config.json') as json_file:
data = json.load(json_file, object_hook=lambda d: SimpleNamespace(**d)) |
# Robot to enter weekly sales data into the RobotSpareBin Industries Intranet.
import os
from Browser import Browser
from Browser.utils.data_types import SelectAttribute
from RPA.Excel.Files import Files
from RPA.HTTP import HTTP
from RPA.PDF import PDF
browser = Browser()
def open_the_intranet_website():
bro... |
import os
import re
import sys
import time
from subprocess import PIPE, run
from types import ModuleType
from typing import Union
import docker
import requests
import storm.__main__ as storm
from lazycluster import Runtime, RuntimeGroup, RuntimeManager, RuntimeTask
from .config import RUNTIME_DOCKER_IMAGE, RUNTIME_N... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019 by University of Kassel, Tu Dortmund, RWTH Aachen University and Fraunhofer
# Institute for Energy Economics and Energy System Technology (IEE) Kassel and individual
# contributors (see AUTHORS file for details). All rights reserved.
import numpy as np
from pandas import S... |
"""Example systems created in Python
"""
import numpy as np
from pysim.cythonsystem import Sys
class VanDerPol(Sys):
"""Simple example of a class representing a VanDerPol oscillator.
"""
def __init__(self):
self.add_state_scalar("x", "dx")
self.add_state_scalar("y", "dy")
self.add_... |
from enum import Enum
from .durations import MINUTE, HOUR
class OpenshiftVersion(Enum):
VERSION_4_6 = "4.6"
VERSION_4_7 = "4.7"
VERSION_4_8 = "4.8"
VERSION_4_9 = "4.9"
class NetworkType:
OpenShiftSDN = "OpenShiftSDN"
OVNKubernetes = "OVNKubernetes"
WORKING_DIR = "build"
TF_FOLDER = f"{WOR... |
from gym.envs.registration import register
register(
id='SimpleFlappy-v0',
entry_point='gym_simpleflappy.envs:FlappyEnv',
)
register(
id='SimpleFlappyDistance-v0',
entry_point='gym_simpleflappy.envs:FlappyEnvDistance',
)
|
from haystack import indexes
from peeldb.models import (
JobPost,
Skill,
City,
FunctionalArea,
Industry,
Qualification,
State,
)
from datetime import datetime
from django.core import serializers
from mpcomp.views import get_absolute_url
class jobIndex(indexes.SearchIndex, indexes.Indexable... |
#coding:utf-8
#
# id: bugs.core_5097
# title: COMPUTED-BY expressions are not converted to their field type inside the engine
# decription:
#
# tracker_id: CORE-5097
# min_versions: ['3.0']
# versions: 3.0
# qmid: None
import pytest
from firebird.qa import db_factory, ... |
from enum import Enum
from typing import Any
from importlib import import_module
class ValidationError(Exception):
"""
Error class for validation failed
"""
def __init__(self, payload: dict):
"""
:param message: error message
"""
self.payload = payload
def generate... |
from engine.utils import RF_sq64, sq64_to_sq120, print_board
def react_chess_board_to_IZII_board(board):
if board is None:
exit()
izii_board = ["x"] * 120
pieces = board.split(',')
for i in range(len(izii_board)):
if i >= 20 and i < 100:
if i % 10 != 0 and i % 10 != 9:
... |
import numpy as np
import pandas as pd
import pytest
import ibis
import ibis.expr.datatypes as dt
from ibis.backends.pandas.udf import udf
def make_t():
return ibis.table(
[
('_timestamp', 'int32'),
('dim1', 'int32'),
('dim2', 'int32'),
('valid_seconds', 'i... |
import time
from threading import Thread
def timestamp_datetime(value):
format = '%Y-%m-%d %H:%M:%S'
value = time.localtime(value)
dt = time.strftime(format, value)
return dt
def log(s):
print("[",timestamp_datetime(time.time()),"]",s)
|
from time import sleep
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
from celery.schedules import crontab
from celery.task import periodic_task
from crypto.models import Cryptocurrency
# @shared_task
@periodic_task(
run_every=(crontab(minute="*/15")),
name="create_cryptocurrency"... |
# generated by datamodel-codegen:
# filename: schema/entity/data/database.json
# timestamp: 2021-09-27T15:46:37+00:00
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, Field, constr
from ...type import basic, entityReference, usageDetails
class DatabaseName(BaseMo... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
from django.conf import settings
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Creates and... |
import re
import pickle
import tempfile
import pytest
from _pytest.config import Config
from _pytest._io.terminalwriter import TerminalWriter
from _pytest.reports import TestReport
from pytest_fold.tui_pytermtk import main as tuitk
from pytest_fold.tui_textual1 import main as tuitxt1
from pytest_fold.tui_textual2 impo... |
import argparse
import os
import sys
import time
import numpy as np
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import UniformFloatHyperparameter, \
UniformIntegerHyperparameter, CategoricalHyperparameter, \
UnParametrizedHyperparameter, Constant
from sklearn... |
# Copyright 2015 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... |
'''HDF5 operating system operations.
license: HDF5Application/license.txt
Main authors:
Philipp Bucher
Michael Andre
'''
import KratosMultiphysics
import KratosMultiphysics.kratos_utilities as _utils
import os
class DeleteOldH5Files(object):
'''Delete h5-files from previous simulations.'''
def __ca... |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField, SelectField
from wtforms.validators import Required
class CommentsForm(FlaskForm):
comment = TextAreaField('Comment', validators=[Required()])
submit = SubmitField('SUBMIT')
class UpdateProfile(FlaskForm):
bio = Tex... |
"""
NLP Sandbox Date Annotator API
# Overview The OpenAPI specification implemented by NLP Sandbox Annotators. # noqa: E501
The version of the OpenAPI document: 1.1.1
Contact: thomas.schaffter@sagebionetworks.org
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
impo... |
import json
from datetime import datetime
from typing import Dict
import requests
import demistomock as demisto
from CommonServerPython import *
""" IMPORTS """
# Disable insecure warnings from urllib3
# - this does not disable SSL checking, just the warnings logged from urllib3
requests.packages.urllib3.disable_w... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 9
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_8_2_2.models.drives_... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from branches import region, branch, resource
urlpatterns = [
url(r'^$', region.region_list, name='branches'),
url(r'^region/add/$', region.region_add, name='region_add'),
url(r'^region/list/$', region.region_list, nam... |
"""awards URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
import requests
import sqlalchemy
import xmltodict
from sqlalchemy import create_engine, MetaData
from collections import defaultdict
import datetime
from utils import *
class Capture(object):
def __init__(self,
schema,
database='projetocurio'
):
... |
# -*- coding: utf-8 -*-
# Copyright 2013-2017 Ent. Services Development Corporation LP
#
# Redistribution and use of this software 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 copyrigh... |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
from .idw import inverse_distance_weighting
|
#
# PySNMP MIB module IPX-INTERFACE-MANAGEMENT-PRIVATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IPX-INTERFACE-MANAGEMENT-PRIVATE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:56:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# U... |
"""Support for setting the Transmission BitTorrent client Turtle Mode."""
import logging
from homeassistant.const import CONF_NAME, STATE_OFF, STATE_ON
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import ToggleEntity
fr... |
import csv
import time
import os
import pandas as pd
DATA_ROOT = "C:\\RS\\Amazon\\All\\"
MINIMUM_X_CATEGORIES_FILENAME = 'minimum_2_Categories.csv'
timestamp = time.strftime('%y%m%d%H%M%S')
out_filename = os.path.join(DATA_ROOT, timestamp + 'categories_permutations.csv')
with open(out_filename, 'w', newline='', enc... |
from persistent.interfaces import IPersistent
import lxml.objectify
import mock
import unittest
import zeit.cms.workingcopy.interfaces
import zeit.edit.container
import zeit.edit.testing
import zeit.edit.tests.fixture
import zope.interface
import zope.security.proxy
class TestContainer(unittest.TestCase):
def ge... |
from django.contrib import admin
from .models import Artists, Albums, Tracks
# Register your models here.
admin.site.register([Artists, Albums, Tracks]) |
import numpy as np
import astropy.units as u
from astropy.convolution.kernels import Gaussian2DKernel
from scipy import signal
from ..clean import clean, ms_clean, component, radial_prolate_sphereoidal,\
vec_radial_prolate_sphereoidal
from ..transform import dft_map, idft_map
def test_clean_ideal():
n = m =... |
# -*-coding:Utf-8 -*
from mplotlab import App
from matplotlib.backend_bases import NavigationToolbar2
import wx
class Cursors:
# this class is only used as a simple namespace
HAND, POINTER, SELECT_REGION, MOVE = list(range(4))
cursors = Cursors()
cursord = {
cursors.MOVE : wx.CURSOR_HAND,
... |
"""
UnitTests of the python interface to the neuron class.
Items declared in neuron/__init__.py
$Id$
"""
import unittest
import neuron
from neuron import h
class NeuronTestCase(unittest.TestCase):
"""Tests of neuron"""
def testHClass(self):
"""Test subclass of hoc class."""
from ._subclass... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 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 BIP66 (DER SIG).
Test that the DERSIG soft-fork activates at (regtest) height 1251.
"""
from tes... |
import collections
EstimatorSetting = collections.namedtuple(
'EstimatorSetting', ['title', 'estimator', 'parameter_space'])
|
# coding=utf-8
from OTLMOW.PostenMapping.StandaardPost import StandaardPost
from OTLMOW.PostenMapping.StandaardPostMapping import StandaardPostMapping
# Generated with PostenCreator. To modify: extend, do not edit
class Post060339901(StandaardPost):
def __init__(self):
super().__init__(
nummer... |
import sys, inspect, re
from os.path import basename, split
__all__ = ['this_tests']
class RegisterTestsPerAPI:
apiTestsMap = dict()
@staticmethod
def this_tests(testedapi):
prev_frame = inspect.currentframe().f_back.f_back
pathfilename, line_number, test_function_name, lines, index = ins... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import math
import numpy as np
import dace
import polybench
N = dace.symbol('N')
#datatypes = [dace.float64, dace.int32, dace.float32]
datatype = dace.float64
# Dataset sizes
sizes = [{N: 40}, {N: 120}, {N: 400}, {N: 2000}, {N: 4000}]
args ... |
import pandas as pd
import numpy as np
COLORS_QTY: int = 5
# =============================================================================
# Argument parsing.
# =============================================================================
import argparse
from scipy import integrate
argument_parser: argparse.ArgumentP... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import math
import numpy as np
FIELD_SCORE_NUM_OFFSET=6
class Waypoints:
def __init__(self, path, side):
self.points = []
self.number = 0
self.Waypoints_Lap = 0
self.next_target_idx = -1
self.all_field_score = np.on... |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... |
class Page(object):
start: int
end: int
domain: str
all_urls: Any
m3u8_dict: dict
__slots__ = ("start", "end", "domain", "all_urls", "m3u8_dict")
def __init__(self, start, end, domain, all_urls = [], **m3u8_dict):
# super().__init__()
self.start = start
self.end = e... |
import config
import models
import tensorflow as tf
import numpy as np
import os
from sys import argv
os.environ['CUDA_VISIBLE_DEVICES']='0'
#Input training files from benchmarks/FB15K/ folder.
con = config.Config()
#True: Input test files from the same folder.
con.set_in_path("./benchmarks/FB15K237/")
con.set_test_li... |
from database.database_util import connect_to_skip_database
from skip_dataset.generate_histogram import generate_histogram
from skip_dataset.generate_track_data import generate_track_data
from skip_dataset.plot_track_sum import plot_track_sum
# File used to execute different functions related to Spotify Sequential Ski... |
# Copyright 2018 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... |
dnas = [
['wVW*?', 48, 52, 15.52, 40, 10, -0.23, {'ott_len': 35, 'ott_percent': 209, 'ott_bw': 120, 'tps_qty_index': 3, 'max_risk': 30}],
['ftUQf', 46, 66, 10.18, 58, 12, 3.51, {'ott_len': 33, 'ott_percent': 246, 'ott_bw': 117, 'tps_qty_index': 65, 'max_risk': 54}],
['ui*5<', 44, 84, 12.12, 42, 14, 6.81, {'ott_len': 35... |
#!/usr/bin/env python
##################################################################
# Copyright (c) 2012, Sergej Srepfler <sergej.srepfler@gmail.com>
# February 2012 - May 2012
# Version 0.2.8, Last change on May 31, 2012
# This software is distributed under the terms of BSD license.
##########################... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the isValid function below.
def isValid(s):
ss = list(set(s))
fs = []
for c in ss:
fs.append(s.count(c))
if (len(list(set(fs))))==1:
return 'YES'
elif len(list(set(fs)))==2:
mx= max(fs)... |
"""Test Axis user management.
pytest --cov-report term-missing --cov=axis.pwdgrp_cgi tests/test_pwdgrp_cgi.py
"""
import pytest
from unittest.mock import Mock
from axis.pwdgrp_cgi import SGRP_ADMIN, User, Users
def test_users():
"""Verify that you can list users."""
mock_request = Mock()
users = Users(... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2021/12/20 14:52
Desc: 南华期货-商品指数历史走势-价格指数-数值
http://www.nanhua.net/nhzc/varietytrend.html
1000 点开始, 用收益率累计
http://www.nanhua.net/ianalysis/varietyindex/price/A.json?t=1574932974280
"""
import time
import requests
import pandas as pd
def futures_nh_index_symbol_t... |
"""Custom COVID19 Compartmental model
"""
from ..model import CompartmentalModel
class COVID19(CompartmentalModel):
def __init__(self,
N,
beta,
incubation_rate = 1/3.7,
recovery_rate_asymptomatic = 1/4.7,
recovery_rate_mild = 1/4.7,
... |
from lib.utils import top_k
from TraditionalRecommenderSystems.MatrixFactorization.Models import BaseMF
import numpy as np
import pandas as pd
import torch
from torch import nn
import torch.utils.data as data
from tqdm import tqdm
class MatrixFactorization(object):
def __init__(self, user_item_pairs, user_list, i... |
import numpy as np
import copy
def softmax(x):
probs = np.exp(x - np.max(x))
probs /= np.sum(probs)
return probs
class TreeNode(object):
"""A node in the MCTS tree. Each node keeps track of its own value Q, prior probability P, and
its visit-count-adjusted prior score u.
"""
def __init_... |
#!/usr/bin/env python
from vtk import *
source = vtkRandomGraphSource()
source.SetNumberOfVertices(15)
source.SetStartWithTree(True)
source.SetIncludeEdgeWeights(True)
bfs = vtkBoostBreadthFirstSearch()
bfs.AddInputConnection(source.GetOutputPort())
bfs.SetOriginVertex(0)
view = vtkGraphLayoutView()
vie... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
# coding=utf8
import os
import re
import json
import argparse
from sql.evaluator import compare_sqls
def evaluate(path, timeout=120):
with open(path, 'r') as f:
predictions = json.load(f)
total = len(predictions)
correct = 0
for pidx, p in enumerate(predictions):
truth = p['truth... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from proj.archs.cluster.vgg import VGGNet
from proj.archs.segmentation.net10a import SegmentationNet10aTrunk, \
SegmentationNet10a
from proj.utils.segmentation.baselines.general import get_patches
__all__ = ["SegmentationNet10aDoersch"]
class Do... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
# Copyright (c) 2009-2010 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modi... |
__version__ = "0.0.18"
__banner__ = \
"""
# minidump %s
# Author: Tamas Jos @skelsec (skelsecprojects@gmail.com)
""" % __version__ |
#
# SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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... |
from toposort import toposort
import contextlib
import numpy as np
import tensorflow as tf
import tensorflow.contrib.graph_editor as ge
import time
import sys
sys.setrecursionlimit(10000)
# refers back to current module if we decide to split helpers out
util = sys.modules[__name__]
# getting rid of "WARNING:tensorflow... |
"""
Script taken from: https://github.com/orlp/pygrafix
Appropriate Licence applies!
"""
import argparse
import os
import pathlib
import re
def generate_pxd(glew_header_loc, dest="."):
with open(glew_header_loc) as fin:
data = fin.read()
# cython doesn't support const
data = re.sub(r"\bconst\b",... |
import logging
from urllib.parse import urljoin
import requests
from eth_typing import ChecksumAddress
from safe_transaction_service.tokens.clients.exceptions import CannotGetPrice
logger = logging.getLogger(__name__)
class CoingeckoClient:
base_url = 'https://api.coingecko.com/'
def __init__(self):
... |
# -*- coding: utf-8 -*-
from selenium_tests.UserDriverTest import UserDriverTest
from selenium.webdriver.common.by import By
class TestHideApplication(UserDriverTest):
def test_hide_application(self):
self.wait_until_application_list_loaded()
self.type_text_in_element_located(By.ID, "search-input... |
import anachronos
from e2e_test.runner import http
class ExceptionResourceTest(anachronos.TestCase):
def setUp(self):
self.http = http.with_path("/api/error")
def test_got500OnInternalServerError(self):
response = self.http.get("")
self.assertEqual(500, response.status_code)
d... |
from st_library import Library
st_lib = Library()
st_lib.set_token('token')
st_lib.set_config_id('52db99d3-edfb-44c5-b97a-f09df4402081')
print(st_lib.unstruct_data.download_file("19a29b9b-bea2-40fb-89c4-555bba829539","image.jpg"))
|
# Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... |
from .core import *
from .usual_models import *
|
import pandas as pd
import re
data = pd.read_csv("BIPMetadata_current.csv")
def format_date(date_column):
# formatting the date data to display as yyyy-mm-dd
new_dates = []
for date in date_column:
month = date[0:date.find('/')]
date = date[date.find('/')+1:]
day = date[0:date.find... |
import os
from wellcomeml.ml.clustering import TextClustering
from wellcomeml.viz.visualize_clusters import visualize_clusters
def test_output_html(tmp_path):
"""Tests that the output html is generated correclty by the clustering function"""
# This will be the file to
temporary_file = os.path.join(tmp_p... |
#!/usr/bin/env python
import numpy as np
from collections import defaultdict
import itertools
from sklearn.metrics import confusion_matrix
def print_data_stats(sens_attr, class_labels):
"""Print a few numbers about the data: Total number of points, number of
protected examples and unprotected examples, and num... |
# (C) 2022 GoodData Corporation
from __future__ import annotations
from pathlib import Path
from typing import List, Optional, Type
import attr
from gooddata_metadata_client.model.declarative_user import DeclarativeUser
from gooddata_metadata_client.model.declarative_users import DeclarativeUsers
from gooddata_sdk.c... |
import logging
from collections import namedtuple
from typing import (Any, Callable, Dict, # pylint: disable=unused-import
Generator, Iterable, List, Optional, Text, Union, cast)
import schema_salad.validate as validate
from schema_salad.sourceline import SourceLine, bullets, strip_dup_lineno
impo... |
from isserviceup.services.models.statuspage import StatusPagePlugin
class Loggly(StatusPagePlugin):
name = 'Loggly'
status_url = 'http://status.loggly.com//'
icon_url = '/images/icons/loggly.jpg'
|
import tensorflow as tf
from contextlib import contextmanager
from PIL import Image
from keras import backend as K
from keras.utils.data_utils import OrderedEnqueuer
def heteroscedastic_loss(attention=False,
block_attention_gradient=False,
mode='l2'):
''' Heteroscedastic loss.'''
def h... |
from __future__ import absolute_import
from __future__ import print_function
import requests, sys, threading, time, os, random
from random import randint
from six.moves import input
CheckVersion = str (sys.version)
import re
from datetime import datetime
print ('''
.... ... |
#!/usr/bin/env python
#from gevent import monkey
#monkey.patch_all(aggressive=True)
#from psycogreen.gevent import patch_psycopg
#patch_psycopg()
#import eventlet
#eventlet.monkey_patch()
#from psycogreen.eventlet import patch_psycopg
#patch_psycopg()
import os
import sys
if __name__ == "__main__":
os.environ.s... |
class AutoVivification(dict):
"""Implementation of perl's autovivification."""
def __missing__(self, key):
value = self[key] = type(self)()
return value
weather = AutoVivification()
weather['china']['guangdong']['shenzhen'] = 'sunny'
weather['china']['hubei']['wuhan'] = 'sunny'
weather['USA'][... |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Helpful routines for regression testing."""
from base64 import b64encode
from binascii import hexlify,... |
import unittest
from steem.utils import (
constructIdentifier,
sanitizePermlink,
derivePermlink,
resolveIdentifier,
yaml_parse_file,
formatTime,
)
class Testcases(unittest.TestCase) :
def test_constructIdentifier(self):
self.assertEqual(constructIdentifier("A", "B"), "@A/B")
... |
"""File utility functions for Sphinx."""
import os
import posixpath
from typing import TYPE_CHECKING, Callable, Dict
from docutils.utils import relative_path
from sphinx.util.osutil import copyfile, ensuredir
from sphinx.util.typing import PathMatcher
if TYPE_CHECKING:
from sphinx.util.template import BaseRende... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Marc Anthony Reyes and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestGame(unittest.TestCase):
pass
|
#!/bin/env python3
def puzzle2():
entries = set()
allowed1 = {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"}
valid = 0
# Read in all the rules
with open('input.txt', 'r') as input:
l = 0
for line in input:
l += 1
if line == "\n":
# print(entr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.