text string | size int64 | token_count int64 |
|---|---|---|
# confit/urls.py
# Django modules
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
# Django locals
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('shop.urls')),
path('', include('blog.urls... | 1,371 | 442 |
from typing import Any, Dict
import pytest
from transformer.transformers.add_key import AddKeyValues, AddKeyValuesConfig
@pytest.fixture()
def target_data(data):
t = data.copy()
t.update(
{
"a_a-value": True,
"b_b-value": "a-value_b-value",
}
)
return t
def ... | 1,327 | 461 |
from django import forms
class LoginForm(forms.Form):
usr = forms.CharField(label="Usuario")
pwd = forms.CharField(label="Contraseña", widget=forms.PasswordInput)
| 173 | 55 |
from django.test import TestCase
from django.urls import resolve, reverse
from .views import signup
class SignUpTests(TestCase):
def test_signup_status_code(self):
url = reverse('signup')
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
def test_singup_url_... | 427 | 133 |
# *-* coding: utf-8 *-*
from django.contrib.auth import get_user_model
from .base import AuthAPIViewSet
from utils.perm import HasPerm
from sys_app.serializers.user import UserSerializer
User = get_user_model()
class userViewSet(AuthAPIViewSet):
"""
用户视图集
"""
queryset = User.objects.all()
serial... | 2,048 | 709 |
from output.models.nist_data.list_pkg.date.schema_instance.nistschema_sv_iv_list_date_max_length_3_xsd.nistschema_sv_iv_list_date_max_length_3 import NistschemaSvIvListDateMaxLength3
__all__ = [
"NistschemaSvIvListDateMaxLength3",
]
| 238 | 97 |
# @Time : 2020/11/22
# @Author : Kun Zhou
# @Email : francis_kun_zhou@163.com
# UPDATE:
# @Time : 2020/11/24, 2020/12/18
# @Author : Kun Zhou, Xiaolei Wang
# @Email : francis_kun_zhou@163.com, wxl1999@foxmail.com
import torch
def compute_grad_norm(parameters, norm_type=2.0):
"""
Compute norm over grad... | 1,602 | 562 |
#!/usr/bin/env python
# encoding: utf-8
#========================================================================================================
# [解释下seek()函数的用法]
# file.seek(off, whence=0)
# 从文件中移动off个操作标记(文件指针),正数往结束方向移动,负数往开始方向移动。
# 如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。
#===================... | 1,465 | 497 |
# Leave Empty # | 15 | 7 |
from distutils.version import LooseVersion
import pytest
import numpy as np
from .. import Model, ModelOutput
from .test_helpers import random_id, get_test_dust
from ...grid import AMRGrid
try:
import yt
except:
YT_VERSION = None
else:
if LooseVersion(yt.__version__) >= LooseVersion('3'):
YT_VERS... | 7,430 | 3,028 |
#!/usr/bin/env python
from datetime import datetime, timedelta, time
from day import Day
from window import Window
__author__ = "Aditya Pahuja"
__copyright__ = "Copyright (c) 2020"
__maintainer__ = "Aditya Pahuja"
__email__ = "aditya.s.pahuja@gmail.com"
__status__ = "Production"
class TimeWindowGenerator:
def... | 2,149 | 677 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : test_numeric_batchnorm_v2.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 11/01/2018
#
# Distributed under terms of the MIT license.
"""
Test the numerical implementation of batch normalization.
Author: acgtyrant.
See also: https://github... | 1,976 | 703 |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from py_utils.refactor import snippet
from six.m... | 1,245 | 389 |
import pygame
import sys
import random
# TODO: Create a Ball class.
# TODO: Member variables: screen, color, x, y, radius, speed_x, speed_y
# TODO: Methods __init__, draw, move
class Ball:
def __init__(self, screen, color, x, y, radius, speed_x, speed_y):
self.screen = screen
self.color = color
... | 2,081 | 748 |
import os
import json
import numpy as np
import argh
import boto3
from argh import arg
from tqdm import tqdm
from scipy.spatial import distance
from plotting_funcs import *
s3 = boto3.client('s3')
def compute_dist(img_embeds, dist_func=distance.euclidean, obj='Vehicle:1'):
dists = []
inds = []
for i in im... | 6,628 | 2,166 |
"""
Get Cannabis Data for Connecticut | Cannlytics
Author: Keegan Skeate <keegan@cannlytics.com>
Created: 9/14//2021
Updated: 9/15/2021
License: MIT License <https://opensource.org/licenses/MIT>
"""
# External imports
import pandas as pd
from dotenv import dotenv_values
from fredapi import Fred
state_data = {
'p... | 935 | 315 |
"""Test wechat payment module."""
from unittest import TestCase
from unittest.mock import patch
from wechatkit.exceptions import WechatKitException
from wechatkit.payment import WechatPay
class WechatPayTest(TestCase):
"""WechatPayTest test case."""
def setUp(self):
"""Init setup."""
self.a... | 3,483 | 1,149 |
class ArticleCollection:
def __init__(self):
self._articles = []
def add(self, article):
self._articles.append(article)
def __len__(self):
return len(self._articles)
def __iter__(self):
return ArticleCollectionIterator(self)
def get_all_articles_tups(... | 1,177 | 330 |
from itertools import accumulate,chain,combinations,groupby,permutations,product
from collections import deque,Counter
from bisect import bisect_left,bisect_right
from math import gcd,sqrt,sin,cos,tan,degrees,radians
from fractions import Fraction
from decimal import Decimal
import sys
input = lambda: sys.stdin.readlin... | 1,555 | 580 |
import numpy as np
import time
#https://stackoverflow.com/questions/8956832/python-out-of-memory-on-large-csv-file-numpy?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
def iter_loadtxt(filename, delimiter=' ', skiprows=0, skipcols=0, dtype=float):
def iter_func():
with open(filena... | 1,131 | 401 |
import astroid
import pylint.testutils
from pylint_exception_var_name_plugin import checker
class TestUniqueReturnChecker(pylint.testutils.CheckerTestCase):
CHECKER_CLASS = checker.ExceptionVarNameChecker
def test_finds_bad_name(self):
node = astroid.extract_node(
"""
try... | 1,263 | 363 |
from poly_hgraph.mol_graph import MolGraph
from poly_hgraph.encoder import HierMPNEncoder
from poly_hgraph.decoder import HierMPNDecoder
from poly_hgraph.vocab import Vocab, PairVocab, common_atom_vocab
from poly_hgraph.hgnn import HierVAE, HierVGNN, HierCondVGNN
from poly_hgraph.dataset import (
MoleculeDataset,
... | 439 | 159 |
#!/usr/bin/env python3
PROJECT = 'sshame'
VERSION = '0.11'
from setuptools import setup, find_packages
try:
long_description = open('README.md', 'rt').read()
except IOError:
long_description = ''
setup(
name=PROJECT,
version=VERSION,
description='SSH public key brute force tool',
long_desc... | 2,043 | 657 |
import math
from typing import Union, Any
class LTurtle:
"""A class to implement a simple Logo-style turtle for drawing l-systems"""
def __init__(self,
px: Union[int, float],
py: Union[int, float],
rx: Union[int, float],
ry: Union[int, float... | 3,525 | 1,071 |
from flask import redirect, url_for, session
from functools import wraps
from NationalEducationRadio.models.db.User import AccessLevel
def permission_required(permissions):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
"""
使用and判斷權限
"""
... | 1,120 | 434 |
from data_structures.priority_queue import PriorityQueue
def test_priority_queue_init():
pq = PriorityQueue(lambda x: x[1])
assert isinstance(pq, PriorityQueue)
def test_priority_queue_init_from_list():
lst = [5, 2, 1, 4, 0]
pq = PriorityQueue(items=lst)
assert pq.pop() == 0
assert pq.pop() ... | 1,013 | 444 |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from data_ocean.models import DataOceanModel
from location_register.models.koatuu_models import KoatuuCategory
class RatuRegion(DataOceanModel):
name = models.CharField(_('name'), max_length=30, unique=True, help_text='Name of t... | 4,295 | 1,174 |
import json
import uuid
import os
from socket import getfqdn
from aiohttp import web
from aiohttp_jinja2 import template
from app.service.auth_svc import check_authorization
# import of own modules
from plugins.reporter.app.detectionreport import create_detection
from plugins.reporter.app.CSVreport import create_csv... | 2,334 | 694 |
# -*- coding: utf-8 -*-
"""
# === 思路 ===
# 核心:每次落稳之后截图,根据截图算出棋子的坐标和下一个块顶面的中点坐标,
# 根据两个点的距离乘以一个时间系数获得长按的时间
# 识别棋子:靠棋子的颜色来识别位置,通过截图发现最下面一行大概是一条
直线,就从上往下一行一行遍历,比较颜色(颜色用了一个区间来比较)
找到最下面的那一行的所有点,然后求个中点,求好之后再让 Y 轴坐标
减小棋子底盘的一半高度从而得到中心点的坐标
# 识别棋盘:靠底色和方块的色差来做,从分数之下的位置开始,一行一行扫描,
由... | 11,537 | 5,055 |
from neutronv2.common import send
from neutronv2.arg_converter import get_by_name_or_uuid_multiple
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
@get_by_name_or_uuid_multiple([('subnetpool', 'subnetpool_id')])
@send('get')
def subnetpool_get_details(subnetpool_id, *... | 1,165 | 422 |
startData = [
[1,2,3],
[2,1,3,4],
[3,1,2,4],
[4,3,2]
]
import random
import time
from copy import deepcopy
def getRandomRowAndColumn(data):
rowIndex = random.randint(0, len(data) - 1)
row = data[rowIndex]
columnIndex = random.randint(1, len(row) - 1) # Ignore first value - Node label
r... | 1,727 | 577 |
# Create a class called Animal that accepts two numbers as inputs and assigns
# them respectively to two instance variables: arms and legs. Create an instance
# method called limbs that, when called, returns the total number of limbs the animal has.
# To the variable name spider, assign an instance of Animal that ha... | 863 | 245 |
import tkinter
from tkinter import *
from PIL import Image, ImageTk
from tkinter.filedialog import askopenfilename
import cv2
from keras.models import load_model
import numpy as np
import keras
import tensorflow
import os
from mtcnn import MTCNN
ventana = tkinter.Tk()
ventana.geometry("768x687")
ventana.... | 4,084 | 1,479 |
__strict__ = True
import httpx
from core.config import Config
async def client_fetch(endpoint: str, payload: dict = None) -> dict:
payload.update({"key": Config.STEAM_API_KEY})
async with httpx.AsyncClient() as client:
result = await client.get("https://api.steampowered.com" + endpoint, params=paylo... | 399 | 124 |
# Run this script to create 'userdata' table in DynamoDB
import boto3
def create_userdata_table(dynamodb=None):
if not dynamodb:
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.create_table(
TableName='userdata',
KeySchema=[
{
... | 13,224 | 3,129 |
import os
import sys
import tempfile
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
# On Windows platform, the torch.distributed package only
# supports Gloo backend, FileSt... | 943 | 317 |
"""
DESAFIO 069: Análise de Dados do Grupo
Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada,
o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre:
A) Quantas pessoas têm mais de 18 anos.
B) Quantos homens foram cadastrados.
C) Quantas mulheres têm meno... | 1,925 | 795 |
#!/usr/bin/env python3
import sys
import os
import time
import requests
from rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics
# Configuration for the matrix
options = RGBMatrixOptions()
options.scan_mode = 0
options.pwm_lsb_nanoseconds = 130
options.pwm_bits = 11
options.show_refresh_rate = 0
options.gpio_slowd... | 1,941 | 655 |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def graphs(file,fps,sc,ff,d,center):
df = pd.read_csv(file, index_col=False)
df = pd.DataFrame(df, columns= ['cx','cy','n','v'])
nn = []
mnvl = []
sdd = []
#to get number of repeats
for i in range(int(min(df["... | 2,332 | 990 |
# Generated by Django 3.2 on 2021-11-15 07:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('django_amis_render', '0002_auto_20211115_1543'),
]
operations = [
migrations.RemoveField(
model_name='amisrenderlist',
name='t... | 357 | 135 |
# coding=utf-8
# Copyright (C) 2020 ATHENA AUTHORS; Chunhui Wang
#
# 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 app... | 3,623 | 1,051 |
"""Database initialization settings and logic."""
from flask_sqlalchemy import SQLAlchemy
def connect_db(**kwargs):
"""Link the app database to a postgres db with the supplied info."""
db_uri = 'postgresql://{0}:{1}@{2}:{3}/{4}'.format(kwargs.get('username'),
... | 696 | 180 |
import os
import time
from winsound import Beep
r"""
string = r'''
_,.-------.,_
,;~' '~;,
,; ;,
... | 9,178 | 4,788 |
import idc
import idaapi
import idautils
def rename_sub_functions(fva, prefix):
sub_funcs = set([])
for f in idautils.Functions():
for xref in idautils.XrefsTo(f):
subf = idaapi.get_func(xref.frm)
if not subf:
continue
if subf.startEA == fva:
... | 678 | 227 |
import json
import copy
def get_dku_key_values(endpoint_query_string):
return {key_value.get("from"): key_value.get("to") for key_value in endpoint_query_string if key_value.get("from")}
def get_endpoint_parameters(configuration):
endpoint_parameters = [
"endpoint_url",
"http_method",
... | 1,785 | 510 |
'''Tool to see how well this agent performs on training data'''
import os
import sys
import json
from glob import glob
from keys import keys
sys.path.extend([
# for loading main backend stuff
os.path.join(sys.path[0], '../../gui/backend'),
os.path.join(sys.path[0], '../..') # for loading agents, apis
])
... | 3,673 | 1,068 |
__version__ = "0.2021.12.14"
from .IDCounter import IDCounter
from .createLogMsgTypeStrMap import createLogMsgTypeStrMap
from .JSONDict import JSONDict
from .ReadOnlyDict import ReadOnlyDict
| 198 | 70 |
"""
Base Vector class (wrapper around np).
"""
from __future__ import annotations
from typing import Sequence, TypeVar
import numpy as np
from ..base import Frequency
T = TypeVar("T")
usize = int
class Vector(Sequence, np.ndarray):
def __init__(self, arraylike: Sequence[T]):
super(Vector, self).__init... | 334 | 105 |
import tkinter as tk
from tkinter import END
from tkinter import ttk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg,
)
from gnt import *
from matplotlib.ticker import MaxNLocator
import threading
class MainWindow:
def __init__(self, root, color):
sel... | 28,290 | 9,781 |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 14:59:45 2021
@author: ASUS
"""
# Word Embedding Techniques using Embedding Layer in Keras
from tensorflow.keras.preprocessing.text import one_hot
sent=[ 'the glass of milk',
'the glass of juice',
'the cup of tea',
'I am a good boy',
'I am a good... | 1,027 | 376 |
"""
Gregory Way 2017
Variational Autoencoder - Pan Cancer
scripts/adage_pancancer.py
Comparing a VAE learned features to ADAGE features. Use this script within
the context of a parameter sweep to compare performance across a grid of
hyper parameters.
Usage:
Run in command line with required command arguments:
... | 6,262 | 1,918 |
# 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
# "License"); you may not u... | 6,770 | 2,101 |
import discord
from discord.ext import commands
import random
import subprocess
import asyncio
from discord import Permissions
import os
import threading # run code concurrently
from pyperclip import copy
# we want to use multiprocessing instead of threading since processes are more efficient
import multipro... | 13,469 | 4,939 |
# -*- coding: utf-8 -*-
import re
from . import strings
from .. import ValidationError
_regexes = {
'email_address': re.compile(r'^[a-z0-9\._\+%-]+@[a-z0-9\.-]+(\.[A-Z]{2,4})+$', re.IGNORECASE),
'ipv4': re.compile(r'^([0-9]{1,3}\.){3}[0-9]{1,3}$'),
'url': re.compile(r'')
}
# debating breaking ALL inter-module de... | 1,362 | 504 |
"""
Implements a family of separable Hamiltonian symplectic integrators, where the family is parameterized by the
coefficients which define the weights for each update step. A separable Hamiltonian has the form
H(q,p) = K(p) + V(q)
where K and V are prototypically the kinetic and potential energy functions, resp... | 7,323 | 2,296 |
from ozekilibsrest import Configuration, MessageApi
configuration = Configuration(
username="http_user",
password="qwe123",
api_url="http://127.0.0.1:9509/api"
)
api = MessageApi(configuration)
results = api.download_incoming()
print(results)
for result in results.messages:
print(result)
| 310 | 105 |
from python_freeipa import ClientMeta
CommonTestPassword = 'Secret123'
client = ClientMeta('ipa.demo1.freeipa.org')
client.login('admin', CommonTestPassword)
Userlist = ['alice', 'bob', 'dave', 'frank']
# Reset, Add Users, and Set Manager
for user in UserList:
client.user_del(user, o_continue=True)
client.u... | 882 | 318 |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------
# Filename: konnoohmachismoothing.py
# Purpose: Small module to smooth spectra with the so called Konno & Ohmachi
# method.
# Author: Lion Krischer
# Email: krischer@geophysik.uni-muenchen.de
# License: GPLv2
#... | 11,270 | 3,274 |
"""
Specialist plots.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .general import Plot
from matplotlib.transforms import Affine2D
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist.grid_finder import MaxNLocator
from m... | 2,515 | 851 |
# -*- coding: utf-8 -*-
#
# Author: Dave Hill
# This code will trigger a SNS notification
import boto3
# CONSTANTS
TARGET_ARN = "arn:aws:sns:eu-west-1:924169754118:chaosMonkey-notifications"
def sendSNSNotification(deliverableMessage):
snsClient = boto3.client('sns')
response = snsClient.publish(
Tar... | 431 | 165 |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from yepes.contrib.datamigrations.fields import *
from yepes.contrib.datamigrations.data_migrations import (
DataMigration,
BaseModelMigration,
ModelMigration,
QuerySetExportation,
)
default_app_config = 'yepes.contrib.datamigrations.apps... | 343 | 118 |
import numpy as np
from ..contracts import TradableAsset, AssetCollateral, Repo, Other
class HFLeverageConstraint(object):
r"""
Hedge fund's leverage constraint is calculated just like bank's except that
the params differ for each hedge fund. Additionally, an effective minimum
leverage is used to cal... | 2,564 | 871 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2021 Alibaba Group Holding Limited.
#
# 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/LI... | 23,977 | 7,152 |
from einops import rearrange
from torch import nn
from .switchnorm import SwitchNorm3d
class AttentionBlock(nn.Module):
"""
3D Caps Attention Block w/ optional Normalization.
For normalization, it supports:
- `b` for `BatchNorm3d`,
- `s` for `SwitchNorm3d`.
`using_bn` controls SwitchNorm... | 2,482 | 846 |
# -*- coding: utf-8 -*-
"""
Created on 2017-12-25
@author: cheng.li
"""
from typing import Dict
from typing import Iterable
from alphamind.data.dbmodel.models import Categories
from alphamind.data.dbmodel.models import Market
from alphamind.data.dbmodel.models import RiskCovDay
from alphamind.data.dbmodel.models imp... | 2,199 | 765 |
###############################################################################
# #
# Parse Tree visualizer #
# #
... | 5,307 | 1,549 |
import selenium
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDri... | 1,229 | 387 |
## importing
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import argparse
import os
## parsing arguments
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--infile", help="Input file containing SNV data")
parser.add_argument("-s", "--sample", help="The name o... | 2,228 | 869 |
import os
import sys
from dotenv import load_dotenv
# TODO : 리눅스, win32 타겟별 세팅.
# TODO : 파이썬 버전별 세팅 3.5 ~ 3.8?
def load_env():
load_dotenv() # load bot environment
bot_env = BotEnv.instance()
bot_env.env_initialize('BOT_TOKEN')
bot_env.env_initialize('PREFIX')
bot_env.env_initialize('OWNER_ID'... | 3,877 | 2,009 |
from unittest import TestCase
from tests.assertions import CustomAssertions
import numpy as np
import floq
class TestIsUnitary(TestCase):
def test_true_if_unitary(self):
u = np.array([[-0.288822 - 0.154483j, 0.20768 - 0.22441j, 0.0949032 - 0.0560178j, -0.385994 + 0.210021j, 0.423002 - 0.605778j, 0.135684 ... | 5,973 | 3,679 |
#!python
import os.path
import numpy as NP
import yaml, argparse, warnings
from astroquery.skyview import SkyView
from astropy.coordinates import SkyCoord
from astropy import units as U
from astropy.io import ascii, fits
from astropy.table import Table
import astroutils
astroutils_path = astroutils.__path__[0]+'/'
i... | 9,455 | 2,774 |
import numpy as np
np.random.seed(0)
from wsi.model.resnet import (resnet18, resnet34, resnet50, resnet101,
resnet152)
MODELS = {'resnet18': resnet18,
'resnet34': resnet34,
'resnet50': resnet50,
'resnet101': resnet101,
'resnet152': resnet152}
| 317 | 131 |
from __future__ import absolute_import
import torch
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def reset(self):
self.val = 0
self.avg = 0
... | 2,147 | 670 |
#!/usr/bin/env python
"""
Author: Patrick Hansen
Project: FixyNN
Defines Graph and Layer classes used for intermediate representation
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import json
DEPTHWISE_SEPA... | 12,940 | 5,605 |
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
def simulate(a=0.4,gamma=0.1,phi=0.9,delta=0.8,omega=0.15,sigma_x=1,sigma_c=0.2,T=100):
widgets.interact(simulate_,
a=widgets.fixed(a),
gamma=widgets.fixed(gamma),
phi=widgets.fixed(phi),
delta=widget... | 2,059 | 956 |
from random import choice, shuffle
from itertools import cycle
import pymorphy2
from telegram.ext import Updater, MessageHandler, Filters, CallbackQueryHandler, CommandHandler, ConversationHandler
from telegram import ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup
from geocoder import search, get_ll_... | 10,769 | 3,646 |
# Generated by Django 3.0 on 2020-11-12 10:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('marketing', '0015_auto_20200912_0301'),
]
operations = [
migrations.RenameField(
model_name='contact',
old_name='contry',
... | 511 | 172 |
from src.thumbnail_maker import thumbnail_image, simple_filename, make_author_string
import pandas as pd
import click
import datetime
import os
import tqdm
import re
import time
from multiwrapper import multiprocessing_utils as mu
TITLE_COLUMN = "title"
ABSTRACT_COLUMN = "abstract"
AUTHOR_COLUMN_CONTAINS = "author"
TW... | 4,804 | 1,571 |
from regcore.index import *
from mock import patch
from pyelasticsearch.exceptions import IndexAlreadyExistsError
from unittest import TestCase
class IndexTest(TestCase):
@patch('regcore.index.ElasticSearch')
def test_init_schema(self, es):
init_schema()
self.assertTrue(es.called)
sel... | 681 | 209 |
from typing import Callable, Type, TypeVar
from returns.interfaces.specific.result import ResultLikeN
from returns.methods.cond import internal_cond
from returns.primitives.hkt import Kind2, Kinded, kinded
_ValueType = TypeVar('_ValueType')
_ErrorType = TypeVar('_ErrorType')
_ResultKind = TypeVar('_ResultKind', boun... | 1,145 | 340 |
"""
Example tests: make sure all examples work.
NOTE: This must be run from project root!
"""
from scripttest import TestFileEnvironment # type: ignore
import unittest
import os
import sys
import os.path
env = TestFileEnvironment('./test-output', cwd='.')
example_dir = './concat/examples'
examples = [
os.path.j... | 2,111 | 552 |
# Generated by Django 2.0 on 2018-01-18 22:49
from django.db import migrations, models
import localflavor.us.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
... | 2,820 | 742 |
#!/usr/bin/env python2
# The Notices and Disclaimers for Ocean Worlds Autonomy Testbed for Exploration
# Research and Simulation can be found in README.md in the root directory of
# this repository.
import rospy
import actionlib
import ow_lander.msg
import sys
import copy
import moveit_commander
import moveit_msgs.ms... | 3,988 | 1,206 |
"""a docstring"""
| 23 | 12 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('misc', '0001_initial'),
('locations', '0001_initial'),
('collections_ccdb', '0001_initial'),
('species', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | 9,558 | 2,662 |
"""Entrypoint for the `sgsl` command used to invoke the superGSL compiler."""
import argparse
from supergsl.core.config import load_settings
from supergsl.core.pipeline import CompilerPipeline
from supergsl.core.exception import SuperGSLError
from supergsl.repl import SuperGSLShell
from supergsl.grpc.server import Supe... | 2,023 | 589 |
#!/usr/bin/env python
from usher.tcp_server import MessageParser
from struct import pack, unpack
import socket
import gevent.event
import gevent
import time
class UsherSocket(socket.socket):
'''
A socket wrapper that can be used in a context-manager
'''
def __init__(self, host, port):
socket.... | 4,592 | 1,307 |
# importing necessary libraries and functions
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__) #Initialize the flask App
model = pickle.load(open('Logistic.pickle', 'rb')) # loading the trained model
@app.route('/') # Homepage
def home():
return r... | 860 | 248 |
import bpy
from math import radians
from bpy.app.handlers import persistent
from . import armature_rename
from .armature_creation import armature
class Prefixes: #Container for other prefixes
helper = 'hlp_'
helper2 = 'ValveBiped.hlp_'
attachment = 'ValveBiped.attachment_'
attachment2 = 'ValveBiped.Ani... | 130,823 | 34,992 |
# Generated by Django 3.0.5 on 2021-06-24 22:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='title',
name='genre',
field=m... | 438 | 153 |
from typing import Optional
from pyexlatex.models.item import SimpleItem
class FrameTitle(SimpleItem):
name = 'frametitle'
def __init__(self, title: str, modifiers: Optional[str] = None):
self.title = title
super().__init__(self.name, title, modifiers) | 279 | 82 |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='botbot_plugins',
version='1.0',
description="Plugins and service integrations for BotBot.me",
author="Lincoln Loop",
author_email='info@lincolnloop.com',
url='https://github.com/lincolnloop/botbot_plugins',
packa... | 541 | 195 |
import os
import re
import unittest
from models import Rex
base_dir = os.path.dirname(__file__)
data_dir = os.path.join(base_dir, "data")
########################################################################################################################
class RexAssertions(unittest.TestCase):
############... | 9,550 | 2,617 |
from django.core.management.base import BaseCommand
from bs4 import BeautifulSoup
import requests
from apps.products.models import ShopDepartment, Brand
class Command(BaseCommand):
def handle(self, *args, **options):
Brand.objects.all().delete()
url_base = 'https://www.gearbest.com'
shop... | 751 | 229 |
import pytest
from flask_jwt_extended import create_access_token
@pytest.fixture(scope='session')
def test_client(flask_app):
with flask_app.app_context():
token = create_access_token(identity='testclient')
client = flask_app.test_client()
client.environ_base['HTTP_AUTHORIZATION'] = 'Beare... | 354 | 111 |
__author__ = 'mFoxRU'
from time import sleep
from win32gui import (FindWindow, EnumChildWindows, GetClassName,
GetWindowText, IsWindow)
class Hook(object):
def __init__(
self,
window='MediaPlayerClassicW',
class_name='#32770',
fields=('Title... | 2,106 | 620 |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: tflite
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class OperatorCode(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsOperatorCode(cls, buf, offset):
n = flatbuffers.e... | 3,781 | 1,212 |
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import threading
import urlparse
from endpoint import Endpoint
from config import Parser
CONFIG_PATH = '../config/config.yaml'
class Server(object):
def __init__(self):
parser = Parser(CONFIG_P... | 2,307 | 892 |
from __future__ import with_statement
from pypy.rpython.lltypesystem import rffi, lltype
from pypy.interpreter.error import OperationError
from pypy.interpreter.baseobjspace import Wrappable
from pypy.interpreter.typedef import TypeDef
from pypy.interpreter.gateway import interp2app, unwrap_spec
from pypy.rlib.rarithm... | 35,006 | 11,906 |
#
# Copyright 2016 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | 9,108 | 2,311 |