content stringlengths 5 1.05M |
|---|
"""
Created on Feb 4, 2016
@author: Gregory Kramida
@licence: Apache v2
Copyright 2016 Gregory Kramida
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.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import example
class ExampleTests(unittest.TestCase):
def test_add_2_and_2(self):
self.assertEqual(
4,
example.add(2, 2)
)
def test_add_12_and_24(self):
self.assertEqual(
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 5 03:06:09 2021
@author: moeez
"""
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
df = pd.read_csv('MyData.csv')
df = df.fillna(0) #set null /empty value witho
l = 5000
ht1AllNode = [] #ht 1 mode all node
ht1AllEdge = [] # ht... |
try:
import httptools
except ImportError as exc: # pragma: no cover
from uvicorn.protocols.http.h11_impl import H11Protocol
AutoHTTPProtocol = H11Protocol
else:
from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol
AutoHTTPProtocol = HttpToolsProtocol
|
def foo():
for vars in range(5):
for info in range(5):
for obj in range(5):
pass
|
# Block size: 8
# NonML: processes 1 second of audio in 0.0815474 seconds
# ML: processes 1 second of audio in 0.0529038 seconds
# Block size: 16
# NonML: processes 1 second of audio in 0.077933 seconds
# ML: processes 1 second of audio in 0.0463063 seconds
# Block size: 32
# NonML: processes 1 second of audio in 0.079... |
from __future__ import absolute_import
from utils import setup_logger
logger = setup_logger(__name__)
def download_models():
pass
|
import torch
import torch.nn as nn
from torch.nn import Linear, Conv2d, BatchNorm2d, LeakyReLU, ConvTranspose2d, ReLU, Tanh, InstanceNorm2d, ReplicationPad2d
import torch.nn.functional as F
import random
from utils import gaussian, to_var, to_data, save_image
from vgg import GramMSELoss, SemanticFeature
import numpy as... |
'''
arxiv_scraper.py
This application acts as a web crawler and scraper.
Starting with https://export.arxiv.org/, the crawler will first extract the links to all the 'new' pages on the website. After completing this,
the crawler will visit each page in turn and scrape all paper metadata.
Once finished, each pag... |
"""
PAPI
=======
PAPI stands for Python API and is a simple API documentation
generator specifically written for Python.
"""
VERSION = "0.0.1"
|
"""Databricks specific DataSets"""
import logging
from typing import Any, Dict
from delta.tables import DeltaTable
from kedro.extras.datasets.spark import SparkDataSet
from kedro.io.core import Version
logger = logging.getLogger(__name__)
class DeltaTableDataset(SparkDataSet):
"""
Schema validation: https:... |
'''
$$\ $$\ $$\ $$$$$$\
$$ | $$ | $$ | $$ __$$\
$$ |$$ / $$$$$$\ $$$$$$$\ $$$$$$\... |
#!/usr/bin/env python
# coding: utf-8
"""
Unit tests for SSEClient. Tests were mosly copied from:
https://github.com/EventSource/eventsource/blob/master/test/eventsource_test.js
"""
import os
import sys
import struct
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import sseclient # n... |
# coding: utf-8
#
# Copyright 2013 Google Inc. 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 ... |
from data_prep.load.survey_data import create_survey_data
def create_data_subject(data_raw):
data_subject = data_raw[[
'run_id', 'chinFirst', 'choiceTask_amountLeftFirst',
'browser', 'browser_version', 'device',
'platform', 'platform_version', 'user_agent',
'chosenAmount', 'chosenD... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'transform_img_ui.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtC... |
# -*- coding: utf-8 -*-
"""
vollib.black_scholes_merton.greeks.analytical
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A library for option pricing, implied volatility, and
greek calculation. vollib is based on lets_be_rational,
a Python wrapper for LetsBeRational by Peter Jaeckel as
desc... |
from apiclient.discovery import build
import os
from .info import Info
class VidQuerier(Info):
def __init__(
self,
keyword,
maxlen,
order="relevance",
type="video",
videoCategoryId=27,
id=None,
):
self.keyword = keyword
self.maxlen = max... |
from setuptools import find_packages
from setuptools import setup
F = 'README.md'
with open(F, 'r') as readme:
LONG_DESCRIPTION = readme.read()
CLASSIFIERS = [
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Sc... |
import numpy as np
import pytest
from alphacsc.utils import check_dimension
def test_check_dimension():
X = np.empty((2, 3, 4))
dims = check_dimension(X, expected_shape="n_trials, n_channels, n_times")
assert dims == X.shape
dims = check_dimension(X[0], expected_shape="n_trials, n_channels")
asse... |
# coding: utf-8
import platform
import sys
from datetime import date, datetime, timedelta, tzinfo
from functools import partial, wraps
from types import ModuleType
import pytest
import pytz
import six
from apscheduler.job import Job
from apscheduler.util import (asbool, asint, astimezone, check_callable_args,
... |
def gmatmul_canon(expr, args):
return expr.A @ args[0], []
|
import unittest
class Test(unittest.TestCase):
def test_case_a(self):
ar = [1] * 10
del ar[8]
self.assertEqual(9, len(ar))
def test_case_max(self):
ar = [1] * 10
self.assertRaises(IndexError, lambda: ar[11])
|
import os
import subprocess
import sys
import json
from bottle import route, run, static_file
@route('/static/<name:path>')
def get_file(name):
response = static_file(name, os.getcwd())
response.set_header('Cache-Control', 'no-cache, max-age=0')
#response.set_header('Expires', '0')
#response.set_header('Pragm... |
import csv
import json
from pprint import pformat
from types import SimpleNamespace
from typing import Any, Union
from black import main, format_file_contents, Mode
import _jsonnet as jsonnet
from IPython.core.display import display
from joblib import load, dump
from witwidget import WitConfigBuilder, WitWidget
from ... |
from terminaltables import DoubleTable
def GlobalViewer(TargetDict):
"""
** TargetDict: Dictionary of a model or entered data
Takes Dicationary and recognize it's type (Model or Data) based on Keys and display the data in terminal tables
"""
# Check if the Dict is Model based on value Key
... |
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
from django.urls import path, include
from .views import PlaybookAPIView
urlpatterns = [
path("", PlaybookAPIView.as_view()),
path("v1/", include("ansible_app.urls")),
]
|
# Generated by Django 3.1.7 on 2021-02-23 09:17
from django.db import migrations
from utils.fixer import FixerApi
from django.conf import settings
from product.models import Currency
class Migration(migrations.Migration):
dependencies = [
('product', '0002_remove_order_total'),
]
def get_currenc... |
import media
import my_page
toy_story = media.Movie("Toy Story",
"A story of a boy and his toys that come to life",
"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg",
"https://www.youtube.com/watch?v=KYz2wyBy3kc")
avatar = media.Mo... |
# Databricks notebook source
# MAGIC %md # CCU002_03-D01-project_table_freeze
# MAGIC
# MAGIC **Description** This notebook extracts the data from specified time point (batchId) and then applies a specified common cutoff date (i.e. any records beyond this time are dropped).
# MAGIC
# MAGIC **Author(s)** Sam Hollings... |
from sha3 import (
keccak_256 as _keccak_256,
)
def keccak256(prehash: bytes) -> bytes:
return _keccak_256(prehash).digest()
|
#!/usr/bin/env python
# coding: utf-8
import torch
import torch.optim as optim
import torch.nn as nn
import numpy as np
import os
import csv
import random
import time
from .dataset import get_auc
from .dataset import str_labels as class_names
from .opts import get_opt
args = get_opt()
# ## Fixing the ... |
#
# PySNMP MIB module GENERAL-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GENERAL-MGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:19:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
import json
import urllib
import urllib.request
def read_webhose_key():
"""
Reads the Webhose API key from a file called 'search.key'.
Returns either None (no key found), or a string representing the key.
Remember: put search.key in your .gitignore file to avoid committing it!
"""
# See Python... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 11 15:36:21 2017
@author: Yugal
"""
from keras.utils import plot_model
from keras.models import Sequential
from keras.layers import Convolution2D, Dropout, Dense, Flatten, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator, load_img
from numpy import a... |
from collections.abc import Mapping
from itertools import chain
from typing import Iterable
from gquant._common import _namedtuple_with_defaults
__all__ = ['PortsSpecSchema', 'NodePorts', 'ConfSchema', 'MetaData']
_NodePorts = _namedtuple_with_defaults(
'_NodePorts',
['inports', 'outports'],
{'inports':... |
import pytest
from getnet.services.token import Service, CardNumber
from getnet.services.token.card_token import CardToken
@pytest.mark.vcr()
def test_generate(client):
service = Service(client)
number_token = service.generate(CardNumber("5155901222280001", "customer_21081826"))
assert isinstance(number... |
"""
Tests pickling and unpickling of an audiosegment.
"""
import sys
sys.path.insert(0, '../')
import audiosegment
import numpy as np
import pickle
import unittest
class TestSerde(unittest.TestCase):
"""
Test serialization and deserialization does not corrupt data.
"""
def test_pack_and_unpack_pickle(s... |
# -*- coding: utf-8 -*-
import logging
from django.utils.deprecation import MiddlewareMixin
from .shortcuts import get_oauth2_app
from .toolkit_settings import API_VERSION, MIDDLEWARE_ACCESS_LOG_FORMAT
logger = logging.getLogger(__name__)
class VersionHeaderMiddleware(MiddlewareMixin):
"""
Add a X-API-Vers... |
from pyspark.sql import SparkSession
from pyspark.sql.functions import from_json, col, unbase64, split
from pyspark.sql.types import (
StructField,
StructType,
StringType,
BooleanType,
ArrayType
)
redisMessageSchema = StructType(
[
StructField("key", StringType()),
StructField(... |
import json
import os
from collections import defaultdict
from itertools import count
from tqdm import tqdm
from loader.Database import DBManager, DBTableMetadata
from pprint import pprint
EntryId = "EntryId"
def flatten_data(data, table, parent_keys=None):
if not data:
return {}
if isinstance(data,... |
"""
This file contains functions used in the main preprocessing script.
Created on 2019-01-23-14-50
Author: Stephan Rasp, raspstephan@gmail.com
tgb - 11/13/2019 - Adding RH and deviation from moist adiabat
"""
from ..imports import *
from ..cam_constants import *
# Set up logging, mainly to get timings easily.
loggi... |
#! Занятие по книге Python Crash Course, chapter 11, "Testing your
# Code". Занятие первое, тесты.
import unittest
from book11functions import get_formatted_name, city_functions
# Тест должен содержать функцию (или импортировать функцию без лишних
# прицепов.
# Тест должен бать наследованным от unittest.Test... |
# -*- coding: utf-8 -*-
html_theme = 'alabaster'
html_sidebars = {
'**': [
# 'about.html', 'navigation.html', 'searchbox.html', 'donate.html',
]
}
html_theme_options = {
'github_user': 'lavr',
'github_repo': 'python-emails',
'github_banner': True,
'travis_button': True,
'code_fon... |
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
"""
Stack Data Structure.
Source: https://www.youtube.com/watch?v=lVFnq4zbs-g&t=478s
Books example.
Input -> A B C D
Result as stack:
D
C
B
A
"""
class Stack(object):
def __init__(self):
""" Constructor."""
self.items = []
def push(self, item... |
# -*- coding: utf-8 -*-
""" init """
from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
modules = [ basename(f)[:-3] for f in modules if isfile(f)
and not f.endswith("__init__.py")
and not f.endswith("setup.py")
and not f.endswith("__main__.py"... |
import logging
from datetime import datetime
from typing import Dict, List, NamedTuple
import requests
from .helpers import response_logger
__all__ = [
'CommonApi',
'Alerts'
]
_format = "%Y-%m-%dT%H:%M:%S.%f%z"
class Alert(NamedTuple):
id: str
allowedActions: List[str]
category: str
descrip... |
class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
A = sorted([0] + cuts + [n])
dp = [[0] * len(A) for _ in range(len(A))]
for d in range(2, len(A)):
for i in range(len(A) - d):
j = i + d
dp[i][j] = math.inf
for k in range(i + 1, j):
dp[i][j] = min... |
import argparse
import os
import shutil
import time
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.datasets as datasets
import torchvision... |
from __future__ import print_function
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
import math
import os
import errno
import shutil
PLOT_DIR = './out/plots'
def get_grid_dim(x):
"""
Transforms x into product of two integers
:param x: int
:return: two ints
... |
#!/usr/bin/env python3
from genewrappers.biotools import accessoryfunctions
import os
# Jellyfish is a bit of a pain due to it needing uncompressed input - I'll do some figuring on how I want to
# get it implemented and come back to it.
def count(forward_in, reverse_in='NA', kmer_size=31, count_file='mer_counts.jf',... |
from sys import argv
indirs = argv[1].split(" ")
OUTDIR = argv[2]
def dict_to_csv(_dict, prefix, header):
for method in _dict:
for degree in _dict[method]:
filename = "{}/{}_{}_{}.csv".format(OUTDIR,prefix,method[0], degree)
outputs = _dict[method][degree]
print(outputs... |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: BSD-2-Clause
"""Access libntp funtions from Python."""
from __future__ import absolute_import
import ctypes
import ctypes.util
import errno
import os
import os.path
import sys
import ntp.poly
LIB = 'ntpc'
def _fmt():
"""Produce library naming scheme."""
if s... |
"""
Methods that can be shared by many array-like classes or subclasses:
Series
Index
ExtensionArray
"""
import operator
from pandas.core.ops import roperator
from pandas.core.ops.common import unpack_zerodim_and_defer
class OpsMixin:
# -------------------------------------------------------------
... |
#!/usr/bin/env python
import os, sys
import Tkinter as tk
import tkFileDialog
import bootloader
class bootloadergui:
class pic:
def __init__(self, name = None, lastpage = None):
self.name = name
self.lastpage = lastpage
def __str__(self):
return "(name = '{0:... |
from krux.types import Singleton
from .client import PotClient
from .session_pool import SessionPool
class ClientPool(Singleton):
clients = {}
def get(self, profile_id):
if profile_id not in self.clients:
self.clients[profile_id] = PotClient(profile=profile_id)
return self.clients... |
from comtypes.gen import _91493440_5A91_11CF_8700_00AA0060263B_0_2_12
globals().update(_91493440_5A91_11CF_8700_00AA0060263B_0_2_12.__dict__)
__name__ = 'comtypes.gen.PowerPoint' |
'''
' 빅데이터 분석' 단어가 포함된 회사 채용 리스트 100개 출력
'''
import requests
from bs4 import BeautifulSoup
def find_keyword(keyword):
url = 'http://www.saramin.co.kr/zf_user/search/recruit?search_area=main&search_done=y&search_optional_item=n&searchType=auto&recruitSort=relation&recruitPageCount=40&inner_com_type=&company_cd=0,1... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 18 11:43:30 2021
@author: Akshay Prakash
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
leagueWins = {'Team':['Manchester United','Blackburn Rovers','Arsenal',
'Chelsea','Manchester City','Leicester City'],
... |
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from random import choices
ALPHA = 'abcdef0123456789'
class SmtpClient:
def __init__(self, host, username, password):
... |
#!/usr/bin/env python
# coding: utf-8
#
from __future__ import print_function
import scipy
import os
import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import statsmodels.api as sm
from statsmodels.formula.api import ols
from... |
#!/usr/bin/env python
"""
Create and run an individual likelihood analysis.
"""
import os
import sys
from collections import OrderedDict as odict
import numpy
import numpy as np
import healpy
import fitsio
import ugali.utils.skymap
import ugali.analysis.loglike
from ugali.analysis.loglike import LogLikelihood, create... |
import tkinter as tk
from turtle import color
from quiet_config import Configurations
from quiet_loaders import ConfigLoader
class Menubar():
# initialising the menu bar of editor
def __init__(self, parent):
self._parent = parent
self.ptrn = r'[^\/]+$'
#TODO Control Textformat
... |
# Generated by Django 2.1.3 on 2018-11-23 15:23
from decimal import Decimal
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("algorithms", "0004_auto_20181108_1224")]
operations = [
migrations.AddField(
model_name="algorithm",
... |
''' '''
'''
ISC License
Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all c... |
# -*- coding: utf-8 -*-
"""
Tests
"""
import unittest
from fuzzymatcher import link_table
import pandas as pd
class ColNameCollisions(unittest.TestCase):
"""
Test what happens when the user provides input data with
some column names which are the same in each dataset
"""
def test_all_colnames_ma... |
# md5 : c440493abf8cf179ff3351357c1eb426
# sha1 : 6ea7af455512a6abcc6750df83bd39c8d564f2a4
# sha256 : a80952f0664e25d003bebc10f12b0400268a32a6a95dba5b5d1250aa1181c12a
ord_names = {
} |
import rulr.Nodes
import rulr.Utils
from rulr.Utils.AutoGroup import AutoGroup
import rulr.Utils.Parameters
import numpy as np
class Node(rulr.Nodes.Base):
"""Preview an axis in the scene"""
def __init__(self):
super().__init__()
self.parameters.Size = rulr.Utils.Parameters.Float(40) |
import unittest
class ControllerTest(unittest.TestCase):
pass # TODO: pygame makes testing hard
|
PLAYER_SPEED = 20000
ENEMY_SPEED = 15000
WORLD_DIMENSIONS = (3000, 1500)
COLLISION_TYPES = {
"obstacle": 0,
"player": 1,
"enemy": 2,
"player_bullet": 3
}
ENEMY_FREQUENCY = 3
ENEMY_SIZE_RANGE = (25, 100)
|
# 함수로 negative/zero/positive
def f(key):
if key > 0: # key가 양수일 경우
print("positive")
elif key == 0: # key가 0일 경우
print("zero")
else: # key가 음수일 경우
print("negative")
f(int(input())) |
import insightconnect_plugin_runtime
from .schema import ConnectionSchema
# Custom imports below
from insightconnect_plugin_runtime.exceptions import ConnectionTestException
import json
import requests
class Connection(insightconnect_plugin_runtime.Connection):
def __init__(self):
super(self.__class__, s... |
from seo_report import webpage
from seo_report.warnings import WARNINGS
from seo_report.warnings import BADGES
from bs4 import BeautifulSoup as Soup
import requests
from six.moves.urllib import parse
class Spider(object):
report = {"pages": []}
def __init__(self, site, sitemap=None, page=None):
pars... |
from pathlib import Path
import click
from click_didyoumean import DYMGroup # type: ignore
from hangar import Repository
from rich.progress import Progress
from stockroom import __version__, console, external
from stockroom.core import StockRoom
from stockroom.keeper import init_repo
from stockroom.utils import clean... |
# This file is a fix for this issue with django-compressor
# https://github.com/django-compressor/django-compressor/issues/226
# This is a less filter that explicitly calls CssAbsoluteFilter.
# After adding the relative-urls flag to the lessc command,
# it appears to be unnecessary but I'm leaving it here in case
# w... |
import datetime
import pytz
import os
import torch
# from our files
from models import RecurrentModel
def save_model(model,train_params):
"""
Save model and training params to .pt file
"""
# make outer path with date
date = (datetime.datetime.now(pytz.timezone('Asia/Tokyo')).strftime("%m_%d")... |
from django.shortcuts import render_to_response, render
from django.core.context_processors import csrf
from adminpanel.models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
def post(request... |
from gym_quickcheck.envs.alteration_env import AlternationEnv
from gym_quickcheck.envs.n_knob_env import NKnobEnv
from gym_quickcheck.envs.random_walk_env import RandomWalkEnv
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import zues.utils
class Migration(migrations.Migration):
dependencies = [
('zues', '0001_initial'),
]
operations = [
migrations.AlterModelManagers(
name='actuelepolitieke... |
from .Simple import Simple
from .. import helper
class SimpleWithInfo(Simple):
def decode_object(self, src_dir, file_name, dest_dir, dest_path, version, header_data):
super(Simple, self).decode_object(src_dir, file_name, dest_dir, dest_path, version, header_data)
try:
self.header['info... |
from Aggregate import Aggregate
from Book import Book
from BookShelfIterator import BookShelfIterator
class BookShelf(Aggregate):
last = 0
def __init__(self, maxsize):
self.books = [object for m in range(maxsize)]
def get_book_at(self, index):
return self.books[index]
def append_bo... |
# coding=utf-8
# Author: Rion B Correia
# Date: October 08, 2018
# Edited by Xuan Wang Oct 2020
#
# Description:
# Build Mention Tables (for network construction) on PubMed Abstracts
#
# Add package folder location
import os
import sys
py_include_path = os.path.abspath(os.path.join(os.path.dirname(__file__),os.pardi... |
#@<> Initialization
import os
user_path = testutil.get_user_config_path()
plugins_path = os.path.join(user_path, "plugins")
plugin_folder_path = os.path.join(plugins_path, "cli_tester")
plugin_path = os.path.join(plugin_folder_path, "init.py")
testutil.mkdir(plugin_folder_path, True)
def call_mysqlsh(command_line_ar... |
# -*- coding: utf-8 -*-
"""
This package implements several community detection.
Originally based on community aka python-louvain library from Thomas Aynaud
(https://github.com/taynaud/python-louvain)
"""
from __future__ import print_function
import array
import random
from math import exp, log, sqrt
from collections... |
import asyncio
from twitch_client import TwitchClient
from bot_detection import BotDetector
from colors import Col
from dataclasses import dataclass
from typing import List
import re
@dataclass
class Streamer:
name: str = None
uid: str = None
prof_img: str = None
caster_type: str = N... |
from unittest.mock import patch
import yarl
from aiomixcloud import MixcloudOAuthError
from aiomixcloud.auth import MixcloudOAuth
from tests.auth import TestMixcloudOAuthMixin, \
configure_mock_session, make_mock_mixcloud
from tests.synced import SyncedTestCase
class TestMixcloudOAuth(TestMi... |
import os, datetime
from unicodedata import category
from sqlalchemy.sql.sqltypes import DECIMAL, BigInteger
from constants import env
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.schema import Index, UniqueConstraint, ForeignKey
fr... |
from django.test import TestCase
class electionsTest(TestCase):
"""
Tests for django-elections
"""
def test_elections(self):
pass |
""" Cuckoo Filter data structures """
from .countingcuckoo import CountingCuckooFilter
from .cuckoo import CuckooFilter
__all__ = ["CuckooFilter", "CountingCuckooFilter"]
|
import pytest
from app_settings_dict.defaults_dict import DefaultsDict
def test_simple_items() -> None:
default_values = {"key1": "hello", "key2": "world"}
defaults_dict = DefaultsDict(data=default_values)
assert defaults_dict["key1"] == "hello"
assert defaults_dict["key2"] == "world"
def test_simpl... |
import os
import webapp2
import jinja2
from google.appengine.ext import ndb
from google.appengine.api import users
import logging
template_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.getcwd()))
from profiles import Activity
from loans import LoanApplicantDetails, AdvancedAmount
from database import Use... |
# Generated by Django 3.1 on 2020-08-05 12:07
import buyer.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_... |
import argparse
class Arguments:
def __init__(self):
parser = argparse.ArgumentParser(
description='Updates VoTT directory.')
parser.add_argument('-k', '--key_security_token', required=True)
parser.add_argument('-t', '--target_connection_path', required=True)
parser.add... |
"""
This file is part of the MaternGaBO library.
Authors: Noemie Jaquier and Leonel Rozo, 2021
License: MIT
Contact: noemie.jaquier@kit.edu, leonel.rozo@de.bosch.com
"""
import numpy as np
import torch
from pymanopt.manifolds import *
from BoManifolds.pymanopt_addons.manifolds import *
from BoManifolds.Riemannian_ut... |
from rlpyt.envs.base import EnvStep
from dreamer.envs.wrapper import EnvWrapper
from dreamer.envs.env import EnvInfo
class TimeLimit(EnvWrapper):
def __init__(self, env, duration):
super().__init__(env)
self._duration = duration
self._step = None
def step(self, action):
assert... |
# encoding: utf-8
"""
rtc.py
Created by Thomas Morin on 2014-06-10.
Copyright (c) 2014-2015 Orange. All rights reserved.
Copyright (c) 2014-2015 Exa Networks. All rights reserved.
"""
from struct import pack
from struct import unpack
from exabgp.bgp.message.open.asn import ASN
from exabgp.bgp.message.update.attribut... |
import numpy as np
import os
import sys
import re
import argparse
import glob
from tqdm import tqdm
parser = argparse.ArgumentParser(description='Compute unique minimizers for each chromosome.')
parser.add_argument('--chrompath',
metavar='<PATH>',
help="Chromosome directory",
... |
distancias = list()
while True:
try:
input()
distancia = float(input())
distancias.append(distancia)
except EOFError:
break
print(f'{sum(distancias) / len(distancias):.1f}') |
'''Warning: these tests modify os.environ global state.
Each test must be run in separate process.
Must use pytest --forked or similar technique.
'''
import httplib2
import mock
import os
import socket
import tests
def test_from_url():
pi = httplib2.proxy_info_from_url('http://myproxy.example.com')
assert pi.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.