id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11575868 | import os
import json
from graviteeio_cli.lint.rulesets.gio_apim.functions.gioApimDocumentSchema import gio_apim_Document_Schema
dir_name = os.path.abspath(".") + "/test"
oas_file = "{}/resources/gio_oas/openapi.json".format(dir_name)
def read_api_def(file_name):
with open("{}/lint/gio_oas/{}".format(dir_name, ... |
11575889 | import logging
from flask_jsonpify import jsonify
SERVER_OVERLOADED = 503
NOT_FOUND = 404
TIMEOUT = 504
TOO_MANY_REQUESTS = 429
logger = logging.getLogger(__name__)
def no_content():
return "", 204
def error(status, code, message):
return jsonify({'error': {'code': code, 'message': message}}), status
de... |
11575894 | from msl.loadlib import Client64
class Client(Client64):
def __init__(self, module32):
super(Client, self).__init__(module32, timeout=2)
|
11575899 | import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag.annotation import Type
from ztag.annotation import Manufacturer
from ztag import protocols
import ztag.test
class FtpXerox(Annotation):
protocol = protocols.FTP
subprotocol = protocols.FTP.BANNER
port = ... |
11575919 | import asyncio
import unittest
from aiter import map_aiter, push_aiter
from .helpers import run, get_n
class test_aitertools(unittest.TestCase):
def test_asyncmap(self):
def make_async_transformation_f(results):
async def async_transformation_f(item):
results.append(item)... |
11575921 | def gen_prime(num):
res = set()
for val in range(1, num + 1):
if val > 1:
for i in range(2, val):
if val % i == 0:
break
else:
res.add(val)
print(sorted(list(res)))
def gen2(num):
res = []
for i in range(2, num + 1... |
11575971 | from data_importers.ems_importers import BaseDemocracyCountsCsvImporter
class Command(BaseDemocracyCountsCsvImporter):
council_id = "EAY"
addresses_name = "2021-03-02T10:33:59.623219/Democracy Club - Polling Districts.csv"
stations_name = "2021-03-02T10:33:59.623219/Democracy Club - Polling Stations.csv"
... |
11575993 | def extractWorkNwongNet(item):
'''
Parser for 'work.nwong.net'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Poison-Wielding Fugitive', 'Poison-Wielding Fugitive', ... |
11575995 | import torch.nn as nn
import torch.nn.functional as F
import timm
import torch
from collections import OrderedDict
from .backbone import create_custom_backbone # 导入自定义网络
def create_backbone(model_name, num_classes, metric=False):
"""
主干网络入口
优先顺序: 自定义>timm
model_name: 网络名称
num_classes: 网络输出
... |
11576004 | from flask_restly.decorator import resource, get, rate
from flask_restly import FlaskRestly
from flask import Flask
from time import time
def test_should_return_429_code_if_too_much_requests():
app = Flask(__name__)
FlaskRestly(app)
requests_limit = 2
_data = dict()
@rate.resolver
def view_r... |
11576044 | import os
import pyodbc
from decouple import config
server = config('server')
database = config('database')
username = config('username')
password = config('password')
driver= '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';P... |
11576080 | class FilterModule(object):
def filters(self):
return {
'parse_re_response':
self.parse_re_response
}
# end filters
# sample response: {"route-engine-information": {"route-engine":[]}}
@staticmethod
def parse_re_response(device_response):
"""
... |
11576108 | from unittest_reinvent.running_modes.lib_invent_tests.learning_strategy_tests.test_learning_strategy_sdap_strategy \
import TestLearningStrategySdapStrategy
from unittest_reinvent.running_modes.lib_invent_tests.learning_strategy_tests.test_learning_strategy_dap_strategy \
import TestLearningStrategyDapStrategy
... |
11576135 | import datetime
import logging
import decimal
from django.core.management.base import BaseCommand, CommandError
from pyExcelerator import parse_xls
from market.models import MarketPlace, MarketCategory, MarketSubCategory
from django.template.defaultfilters import slugify
def clean_subcategory(subcategory):
... |
11576141 | import pygame
from pygame.sprite import Sprite
# This class represents the bar at the bottom that the player controls
class Player(pygame.sprite.Sprite):
# Set speed vector
change_x=0
change_y=0
# Constructor function
def __init__(self,x,y, filename):
# Call the parent's constructor
... |
11576173 | from gensim.models.keyedvectors import KeyedVectors
import psycopg2
from psycopg2.extensions import register_adapter
from psycopg2.extras import Json, execute_values
import bz2
import numpy as np
def adapt_numpy_ndarray(numpy_ndarray):
"""
Transform NumPy Array to bjson
"""
return Json(numpy_ndarray.... |
11576177 | def comb(*sequences):
'''
combinations of multiple sequences so you don't have
to write nested for loops
>>> from pprint import pprint as pp
>>> pp(comb(['Guido','Larry'], ['knows','loves'], ['Phyton','Purl']))
[['Guido', 'knows', 'Phyton'],
['Guido', 'knows', 'Purl'],
['Guido', '... |
11576251 | from fastai.basic_train import LearnerCallback
import fastai.tabular.data
from fastai.torch_core import *
from fast_rl.agents.ddpg_models import DDPGModule
from fast_rl.core.agent_core import ExperienceReplay, ExplorationStrategy, Experience
from fast_rl.core.basic_train import AgentLearner
from fast_rl.core.data_bloc... |
11576282 | import numpy as np
import os
import matplotlib.pyplot as plt
from matplotlib import gridspec
import seaborn as sns
import colorsys
from sis import coeff_determination_metric, find_sub_list, retokenize_annotation
ASPECT_TO_COLOR = { 0: 'red',
1: 'blue',
2: 'green' }
def rgb_... |
11576344 | import ubjson
data = {
"name": "python-ubjson",
"versions": ["1", "2"],
"group": {
"is_a_package": True,
"value": 42
}
}
serialized = ubjson.dumpb(data)
print(serialized)
with open("/tmp/data.json", "wb") as f:
f.write(serialized)
|
11576352 | from pybullet_utils.logger import Logger
logger = Logger()
logger.configure_output_file("e:/mylog.txt")
for i in range (10):
logger.log_tabular("Iteration", 1)
Logger.print2("hello world")
logger.print_tabular()
logger.dump_tabular() |
11576381 | import merge
import unittest
from cs.CsDatabag import CsDataBag
class TestCsDatabag(unittest.TestCase):
def setUp(self):
merge.DataBag.DPATH = "."
def test_init(self):
csdatabag = CsDataBag("koffie")
self.assertTrue(csdatabag is not None)
if __name__ == '__main__':
unittest.main... |
11576384 | import requests
url = 'http://photon.bits-goa.ac.in/lms/login/index.php'
values = {'username': '31120150591',
'password': <PASSWORD>'}
r = requests.post(url, data=values)
print (r.content)
|
11576406 | from typing import Optional
from sqlalchemy.exc import IntegrityError
from db.models import session_creator, Team, Members
class TeamService:
@staticmethod
def edit_team(name, project) -> bool:
"""Takes a name, and a project description"""
# TODO: does this need a try/catch??
session... |
11576409 | from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from typing import Union
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import List
class Client(BaseClient):
def associate_certificate(self, Arn: str) -> Dict:
pass
def ... |
11576433 | from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_blog.settings')
app = Celery('django_blog')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscov... |
11576454 | from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-i","--intxt",nargs="+",required=True)
parser.add_argument("-o","--outtxt",required=True)
args = parser.parse_args()
outf = open(args.outtxt,"w")
for f in args.intxt :
with open(f) as txt :
outf.write(txt.read()+"\n")
outf... |
11576563 | from __future__ import absolute_import, print_function, unicode_literals
# NOTE : No fix provided for "Admin actions are no longer collected from base ModelAdmin classes" for now, since it seems no one really relied on this behaviour?
|
11576572 | import asyncio
from io import BytesIO
from twisted.web.http import CACHED, NOT_MODIFIED, PRECONDITION_FAILED
from twisted.web.test.requesthelper import DummyRequest as TwistedDummyRequest
class DummyApplication:
finished = False
fail_to_create = False
def create_application_instance(self, protocol, scop... |
11576595 | import math
import torch
import encoding
import torch.nn as nn
import torch.nn.functional as F
from modules import RFBlock, ContextEncodeDropInplaceABN
from modules import InPlaceABN, InPlaceABNWrapper
from modules.misc import InvertedResidual, conv_bn
from collections import OrderedDict
from functools import partial... |
11576596 | import sys
import networkzero as nw0
try:
# Python 2.7 compat
input = raw_input
except NameError:
pass
print("Looking for chat hub")
hub = nw0.discover("chat-hub")
if not hub:
print("Unable to find chat hub after 60s")
raise SystemExit
print("Chat hub found at", hub)
def main(name=None):
nam... |
11576657 | import pandas as pd
import sys
from collections import defaultdict
from Representation.rnn import DKTnet
import numpy as np
class DKT:
def __init__(self, input_data, repr_type="rnn", dkt_type="rnn"):
self.repr_type = repr_type
self.dkt_type = dkt_type
data = input_data
... |
11576674 | from acpc_python_client.data.base_data_object import BaseDataObject
from acpc_python_client.data.state import State
class MatchState(BaseDataObject):
"""State of the match as perceived by agent."""
def __init__(self, wrapper, game):
super().__init__(wrapper)
self._state = State(self._data_hol... |
11576680 | from typing import Any, Dict, List, Optional
from asyncpg.exceptions import UniqueViolationError
from fastapi import APIRouter, HTTPException
from orm.exceptions import NoMatch
from starlette.status import (
HTTP_200_OK,
HTTP_201_CREATED,
HTTP_400_BAD_REQUEST,
HTTP_404_NOT_FOUND,
)
from app.models imp... |
11576715 | from moshmosh.extension import Extension
from moshmosh.ast_compat import ast
# https://github.com/python/cpython/blob/master/Parser/Python.asdl#L102
opname_map = {
"+": 'Add',
'-': 'Sub',
'*': 'Mult',
'/': 'Div',
'%': 'Mod',
'**': 'Pow',
'<<': 'LShift',
'>>': 'RShift',
'|': 'BitOr',... |
11576716 | import sys
from psutil import virtual_memory
mem = virtual_memory()
mem.total # total physical virtual_memory
GB = float(1024**3) # float need if we run with python 2
if mem.total / GB < 3.8:
print("Warning: building native modules may fail due to not enough physical memory.")
print("You have {:.1f} GB av... |
11576725 | import os
import sys
try:
nbconvert = sys.argv[1]
notebook = sys.argv[2]
except:
print "usage: python convert_notebook.py /path/to/nbconvert.py /path/to/notebook_file.ipynb"
sys.exit(-1)
# convert notebook
os.system('%s -f blogger-html %s' % (nbconvert, notebook))
# get out filenames
outfile_root =... |
11576768 | import cv2
import numpy as np
import math
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", required=True, help="path to input video")
ap.add_argument("-d", "--dir", required=True, help="path to output frames")
ap.add_argument("-n", "--name", required=True, help="nameing convention")
ap.a... |
11576790 | import transformers
from packaging import version
from kobert_transformers import get_tokenizer
tokenizer = get_tokenizer()
def test_transformers_version():
assert version.parse("3.0") <= version.parse(transformers.__version__) < version.parse("5.0")
def test_tokenization():
sample_text = "[CLS] 한국어 모델을 공... |
11576802 | import torch
import typing
#NOTE: code from https://github.com/vchoutas/smplify-x
__all__ = ["InitTranslation"]
class InitTranslation(torch.nn.Module):
def __init__(self,
torso_edge_indices: typing.Sequence[typing.Tuple[int, int]]=[(5, 12), (2, 9)],
focal_length: float=5000.0,
):
... |
11576841 | from overrides import overrides
from collections import Counter
from allennlp.training.metrics.metric import Metric
from dygie.training.f1 import compute_f1
def _invert_arguments(arguments, triggers):
"""
For scoring the argument, we don't need the trigger spans to match exactly. We just need the
trigge... |
11576861 | class Dynamic(object):
kws = {'passing': ['arg=None'],
'failing': ['message'],
'logging': ['message', 'level=INFO'],
'returning': None,
'kwargs': ['expected', '**kws']}
def get_keyword_names(self):
return list(self.kws)
def run_keyword(self, name, args, ... |
11576869 | import os.path
from flask import Flask, redirect, request, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.storage import get_default_storage_class
from flask.ext.uploads import delete, init, save, Upload
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.conf... |
11576892 | from PyPDF2 import PdfFileReader, PdfFileWriter
import pathlib
from pathlib import Path
from reportlab.pdfgen import canvas
import io
import os
import csv
import numpy as np
def getPDF(lngths, perimeters, CSA, APW, MLW):
"""
creates a PDF file containing information about the limb in correct
locations on t... |
11576977 | import os
import hashlib
import csv
import json
from bs4 import BeautifulSoup
from constants import *
import shsJsonApi
import shsHtmlApi
def writeLine(file, *messages):
n = "\n"
file.write(n.join(messages) + n)
def hashString(toBeHashed):
return hashlib.md5(bytes(toBeHashed, "utf-8")).hexdigest()
stringNone... |
11577031 | from bitmovin_api_sdk.encoding.configurations.audio.vorbis.customdata.customdata_api import CustomdataApi
|
11577032 | import numpy as np
import pytransform3d.rotations as pr
from ._base import DMPBase
from ._forcing_term import ForcingTerm
from ._canonical_system import canonical_system_alpha
from ._dmp import (dmp_open_loop, dmp_imitate, ridge_regression,
DMP_STEP_FUNCTIONS, DEFAULT_DMP_STEP_FUNCTION)
def dmp_ste... |
11577089 | import os
import pytest
from oanda_bot import Bot
import time
@pytest.fixture(scope="module", autouse=True)
def scope_module():
class MyBot(Bot):
def strategy(self):
rsi = self.rsi(period=10)
ema = self.ema(period=20)
self.buy_entry = (rsi < 30) & (self.df.C < ema)
... |
11577149 | import base64
import os
import time
import logging
from datetime import datetime
import unittest
from tonclient.client import TonClient
from tonclient.errors import TonException
from tonclient.test.helpers import async_core_client, sync_core_client, \
SAMPLES_DIR, send_grams, GIVER_ADDRESS, tonos_punch
from toncl... |
11577151 | import geopandas as gdp
import cartoframes
import pandas as pd
APIKEY = "<KEY>"
cc = cartoframes.CartoContext(base_url='https://lokiintelligent.carto.com/',
api_key=APIKEY)
from shapely.geometry import Point
from shapely.wkb import loads
arenas_df = cc.read('arenas_nba')
shp = r"C:\Data\US_States\US_States.sh... |
11577161 | import setuptools
INSTALL_REQUIREMENTS = ["termcolor", "opencv-python"]
setuptools.setup(
name="cpu",
url="https://github.com/serend1p1ty/core-pytorch-utils.git",
description="Core APIs for deep learning.",
version="1.0.0",
author="serend1p1ty",
author_email="<EMAIL>",
packages=setuptools.... |
11577201 | import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler, FileSystemEventHandler
from blinker import signal
class WatchEventHandler(FileSystemEventHandler):
def on_any_event(self, event):
if not event.is_directory:
sig = sign... |
11577219 | import logging
from logging.handlers import SysLogHandler
import os.path
import sys
import traceback
import platform
import os
DEBUG = logging.DEBUG
INFO = logging.INFO
WARNING = logging.WARNING
ERROR = logging.ERROR
CRITICAL = logging.CRITICAL
_pid = os.getpid()
syslog_socket_paths = {
'Darwin': '/var/run/syslo... |
11577223 | import pytest
def test_get_int():
from util import get_int
assert 567 == get_int("BFFFBBFRRR")
assert 119 == get_int("FFFBBBFRRR")
assert 820 == get_int("BBFFBBFRLL") |
11577231 | from __future__ import annotations
import time
import typing
from typing_extensions import TypedDict
if typing.TYPE_CHECKING:
import asyncio
from ctc import binary
from ctc import rpc
from ctc import spec
async def async_get_block(
block: spec.BlockReference,
include_full_transactions: bool = False,
... |
11577239 | import copy
import os
import numpy as np
from ppqm import chembridge, constants, linesio, shell
from ppqm.calculator import BaseCalculator
MNDO_CMD = "mndo"
MNDO_ATOMLINE = "{atom:2s} {x} {opt_flag} {y} {opt_flag} {z} {opt_flag}"
class MndoCalculator(BaseCalculator):
def __init__(self, cmd=MNDO_CMD, scr=consta... |
11577250 | from .command import Command
class Placeholder(Command):
"""
An command that holds an overwritable reference to another command.
It is used for most UI navigation, in order to rebind navigation keys to
other values.
"""
def __init__(self, parent, hook):
Command.__init__(self, parent,... |
11577286 | from __future__ import print_function
import sys
import os
import unittest
import logging
from itertools import product
os.environ['ENABLE_CNNL_TRYCATCH'] = 'OFF' # pylint: disable=C0413
import torch
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(cur_dir + "/../../")
from common_utils import te... |
11577336 | import os
import numpy as np
from Bio.Alphabet import IUPAC, Gapped
from BConverters.Converters import convert_alignment, convert_tree
from RouToolPa.Parsers.R import get_indices_from_names
def generate_partition_finder_control_file(alignment_file_name,
genes_file,
... |
11577361 | import editor
from markdown2 import markdown
import ui
TEMPLATE = '''
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Preview</title>
<style type="text/css">
body {
font-family: helvetica;
font-size: 15px;
margin: 10px;
}
</style>
... |
11577364 | import io
from drawille import Canvas
from PIL import Image
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.backends.backend_agg import RendererAgg, FigureCanvasAgg
class RendererDrawille(RendererAgg):
... |
11577421 | from ecdsa.curves import SECP256k1
import threshold_library as threshold
from unittest import TestCase
class ThresholdTestCase(TestCase):
def setUp(self):
self.message = 55555
self.t = 10
self.n = 25
def test_encryption_decryption(self):
""" Tests that a message can be encypte... |
11577425 | from unittest import TestCase
import six
from sdb import telnet
class TestTelnet(TestCase):
def setUp(self):
self.stdin = six.StringIO()
self.stdout = six.StringIO()
class t(telnet):
sent = six.StringIO()
def _send(self, line):
self.sent.write(l... |
11577444 | from django.contrib import admin
from django_use_email_as_username.admin import BaseUserAdmin
from .models import User
admin.site.register(User, BaseUserAdmin)
|
11577477 | import os
import unittest
import torch
from meddlr.config.config import get_cfg
from meddlr.engine.defaults import init_reproducible_mode
from meddlr.utils import env
class TestDefaultSetup(unittest.TestCase):
"""Test that default setup and initialization works as expected."""
_env = None
@classmethod... |
11577494 | import numpy as np
import chainer
import chainer.links as L
import argparse
import time
def main():
parser = argparse.ArgumentParser(
description='generate 2d proessing operator output')
parser.add_argument('--with-ideep', action='store_true', help='enable ideep')
parser.add_argument('--input', ty... |
11577523 | from eval.cap_eval_utils import calc_pr_ovr_noref
import numpy as np
def compute_map(all_logits, all_labels):
num_classes = all_logits.shape[1]
APs = []
for cid in range(num_classes):
this_logits = all_logits[:, cid]
this_labels = (all_labels == cid).astype('float32')
if np.sum(this_labels) == 0:
... |
11577527 | import pandas as pd
import numpy as np
from scipy import sparse
import matplotlib.pylab as plt
import scipy as sp
resume_text = pd.read_csv("data/cleaned_resume.csv", index_col=0)
job_text = pd.read_csv("~/data/full_requisition_data_tokenized.csv").fillna('')
resume_text['Last Recruiting Stage'].value_counts... |
11577536 | import os
import pickle
from types import SimpleNamespace
import numpy.testing as npt
import pandas as pd
from pandas._testing import assert_frame_equal
# from fluxpart import flux_partition
from fluxpart import fvs_partition, fpread
TESTDIR = os.path.dirname(os.path.realpath(__file__))
def test_flux_partition():
... |
11577548 | import os
import sys
import argparse
import struct
import tensorflow as tf
from tensorflow.core.example import example_pb2
END_TOKENS = frozenset(['.', '!', '?', '...', "'", "`", '"', ")"]) # acceptable ways to end a sentence
def fix_missing_period(line):
"""Adds a period to a line that is missing a period"""
if... |
11577556 | import tensorflow as tf
from ..settings import ztypes
def generate_1d_grid(data, num_grid_points, absolute_boundary=0.0, relative_boundary=0.05):
minimum = tf.math.reduce_min(data)
maximum = tf.math.reduce_max(data)
space_width = maximum - minimum
outside_borders = tf.maximum(relative_boundary * spac... |
11577566 | from pypy.rpython.lltypesystem.rffi import CConstant, CExternVariable, INT
from pypy.rpython.lltypesystem import lltype, ll2ctypes
from pypy.translator.tool.cbuild import ExternalCompilationInfo
from pypy.rlib.rarithmetic import intmask
class CConstantErrno(CConstant):
# these accessors are used when calling get_e... |
11577609 | from tests import TestCase
class TestWifidog(TestCase):
def test_login_without_gw_id(self):
response = self.client.get('/wifidog/login/')
self.assertEqual(404, response.status_code)
def test_login_with_invalid_gw_id(self):
response = self.client.get('/wifidog/login/?gw_id=foobar')
... |
11577614 | import re
import json
import socket
import requests
import threading
from decorators import validate_payload, parse_results
from sseclient import SSEClient
class FirebaseEvents(object):
CHILD_CHANGED = 0
CHILD_ADDED = 2
CHILD_DELETED = 1
@staticmethod
def id(event_name):
ev = None
... |
11577615 | import discord
import textgenrnn
import kaizen85modules
class Module(kaizen85modules.ModuleHandler.Module):
name = "KaizenAI"
desc = "Пожилой киберсыч нового поколения!"
async def run(self, bot: kaizen85modules.KaizenBot):
class AICommand(kaizen85modules.ModuleHandler.Command):
title... |
11577637 | from qcircuits.state import qubit, zeros, ones, bitstring
from qcircuits.state import positive_superposition, bell_state
from qcircuits.state import State
from qcircuits.operators import Identity, PauliX, PauliY, PauliZ
from qcircuits.operators import Hadamard, Phase, PiBy8, SqrtNot
from qcircuits.operators import Rota... |
11577642 | from setuptools import setup
def readme():
with open("README.md") as f:
return f.read()
setup(
name="pyzorsocket",
version="0.1",
license="MIT",
author="<NAME>",
author_email="<EMAIL>",
url = "https://github.com/cgt/rspamd-plugins/tree/master/pyzor/pyzorsocket",
description="... |
11577650 | from django.conf import settings
from django.urls import path
from . import views
app_name = "beanstalk_worker"
urlpatterns = [path("task/", views.task, name="task"), path("cron/", views.cron, name="cron")]
if settings.DEBUG:
urlpatterns.append(path("run_all/", views.run_all, name="run_all"))
|
11577673 | import unittest
from os.path import join
from praatio import audio
from praatio.utilities import utils
from test.praatio_test_case import PraatioTestCase
class AudioTests(PraatioTestCase):
def test_get_audio_duration(self):
"""Tests that the two audio duration methods output the same value."""
w... |
11577693 | import requests
from allauth.socialaccount.adapter import get_adapter
from allauth.socialaccount.models import SocialAccount, SocialLogin
from allauth.socialaccount.providers.oauth2.views import OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView
from django.conf import settings
from .provider import ChaHubProvider
BA... |
11577704 | import asyncio
from datetime import datetime
from decimal import Decimal
import logging
import os
from hexbytes import HexBytes
import pytz
from tenacity import retry, stop_after_attempt, wait_fixed, wait_random
from web3 import Web3
from web3.exceptions import BlockNotFound
import beneath
LATEST_COUNT = 24
STABLE_A... |
11577716 | import datetime
import pytz
import flask
import flask.json
from flaskext.csrf import csrf_exempt
import sqlalchemy
import common.time
from common import utils
from common.config import config
from www import server
from www import login
MILESTONES = [
("Multi-Gift Subscriptions", config["timezone"].localize(datetim... |
11577756 | import os
import re
import logging
from django.core.management.base import BaseCommand
from django.core import exceptions
from search.read_csv_data_from_file import read_csv_data_from_file
from search.models import TaskServiceSimilarityScore
from human_services.services.models import Service
LOGGER = logging.getLogger... |
11577757 | ALERT_RESP = {
"primary_id": 3232,
"alert_type": {
"id": 1793,
"created_at": "2019-05-25T19:40:09.132456Z",
"updated_at": "2019-08-12T18:40:12.132456Z",
"type_id": "8916-1b5d68c0519f",
"category": "Host",
"detail_fields": [
"username"
],
... |
11577759 | from .instance.config import *
import requests
import json
import time
import redis
def get_whats_new(country):
if country in supported_countries:
url = netflix_url
querystring = {"q": "get:new7:{}".format(
country), "p": "1", "t": "ns", "st": "adv"}
headers = netflix_headers
... |
11577775 | from itertools import islice, permutations
import re
def circular_window(seq, n=2):
it = iter(seq + seq[:n - 1])
result = tuple(islice(it, n))
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def calculate_happiness_change(graph, order):
return sum(graph[m]... |
11577781 | import logging
from typing import Any, List, Union
from sacrerouge.data import EvalInstance
from sacrerouge.data.dataset_readers import DatasetReader
from sacrerouge.data.fields import DocumentsField, Fields, SummaryField
from sacrerouge.io import JsonlReader
logger = logging.getLogger(__name__)
def flatten_documen... |
11577891 | plt.scatter(range(1,11),np.cumsum(pca_10_transformer.explained_variance_ratio_))
plt.xlabel("PCA Dimension")
plt.ylabel("Total Variance Captured")
plt.title("Variance Explained by PCA"); |
11577948 | from collections import OrderedDict
import theano
from numpy.testing import assert_allclose
from theano import tensor
from blocks.algorithms import BasicMomentum
from blocks_extras.algorithms import BasicNesterovMomentum, NesterovMomentum
from blocks.utils import shared_floatx
def test_basic_nesterov_momentum():
... |
11577964 | import re
from typing import Tuple, List
import dynet_config
dynet_config.set(autobatch=1, mem="2048")
from itertools import chain
import dynet as dy
import numpy as np
from data.reader import DataReader
from eval.bleu.eval import BLEU
from planner.planner import Planner
from scorer.scorer import get_relations
fr... |
11577993 | import os
from uuid import uuid4
import itertools
from contextlib import contextmanager
from .code_element import CodeElement
from .fixture import Fixture
from .generator_fixture import GeneratorFixture
from .nonmethod_test import NonMethodTest
from .test_class import Class
from .test_container import SuiteWriterTestC... |
11578000 | import logging
import queue
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from typing import Dict
import time
from analysis.tools.aws_ec2_instance import EC2Instance
from analysis.tools.experiment import Experiment
from analysis.tools.stats import Stats
from analysis.tools.test... |
11578023 | from anago.tagger import Tagger
from anago.trainer import Trainer
from anago.wrapper import Sequence
|
11578060 | from tests.policies.commenting import CommentingPolicy
class Comment:
__policy_class__ = CommentingPolicy
def __init__(self, id):
self.id = id
|
11578068 | import pytest
from ldap_filter import Filter
class TestFilterAttributes:
def test_present(self):
filt = Filter.attribute('attr').present()
string = filt.to_string()
assert string == '(attr=*)'
def test_equal_to(self):
filt = Filter.attribute('attr').equal_to('value')
s... |
11578085 | from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from navigation import Link
link_api = Link(
icon='fa fa-plug', tags='new_window', text=_('REST API'),
view='rest_api:api_root'
)
link_api_documentation = Link(
icon='fa fa-book', tags='new_window', text=_('AP... |
11578143 | from __future__ import annotations
from django_rq import job
from jcasts.podcasts.models import Podcast, Recommendation
from jcasts.shared.typedefs import User
from jcasts.users.emails import send_user_notification_email
@job("mail")
def send_recommendations_email(user: User) -> None:
"""Sends email with 2 or 3... |
11578182 | import copy
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import entmax
"""
Currently it contains three encoder layer: EncoderLayer, RATEncoderLayer, EncoderLayerWithLatentRelations
"""
# Adapted from
# https://github.com/tensorflow/tensor2tensor/blob/0b156ac533ab53f65f44966381f6e14... |
11578214 | import transform as tr
import numpy as np
import matplotlib.pyplot as plt
def main():
n = 64
arguments = np.arange(0, n) * np.pi / 6
function_values = list(map(lambda x: np.sin(x) + np.cos(4 * x), arguments))
dwt_result = tr.dwt(function_values, 1)
dwht_result = tr.dwht(function_values, 1)
fw... |
11578231 | import math
import torch
from torch import nn
from torch.nn import init
class InvertibleNetwork(nn.Module):
"""Invertible neural network. Implements differentiable inverse for use in flows."""
def __init__(self, latent_size, negative_slope):
super().__init__()
self.f = nn.LeakyReLU(negative_slope=negative... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.