text string | size int64 | token_count int64 |
|---|---|---|
from rkstiff.grids import construct_x_kx_rfft, construct_x_kx_fft
from rkstiff.grids import construct_x_Dx_cheb
from rkstiff.derivatives import dx_rfft, dx_fft
import numpy as np
def test_periodic_dx_rfft():
N = 100
a, b = 0, 2*np.pi
x,kx = construct_x_kx_rfft(N,a,b)
u = np.sin(x)
ux_exact = np.co... | 3,179 | 1,686 |
#!/usr/bin/env python
import os
from jinja2 import Environment, FileSystemLoader
PATH = os.path.dirname(os.path.abspath(__file__))
env = Environment(loader=FileSystemLoader(os.path.join(PATH, 'templates')))
mac_addr = "01:23:45:67:89:01"
PXE_ROOT_DIR = "/data/tftpboot"
pxe_options = {
'os_distribution': 'centos... | 2,511 | 903 |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from .models import Student, User
admin.site.site_header = 'BIA SCHOOL SYSTEM'
class UserAdmin(DjangoUserAdmin):
model = User
fieldsets = DjangoUserAdmin.fieldsets + ((None, {
'fields': ('role', 'midd... | 1,101 | 343 |
# coding: utf-8
"""Converter module."""
import util
THEME = 'theme'
BACKGROUND = 'background'
class ThemeConverter(object):
"""Object that converts themes using given map file."""
def __init__(self, theme_map, transp_map):
"""Constructor."""
self.theme_map = theme_map
self.transp_m... | 1,111 | 330 |
import pickle
import platform
import os
import pytest
import localpaths
from . import serve
from .serve import Config
@pytest.mark.skipif(platform.uname()[0] == "Windows",
reason="Expected contents are platform-dependent")
def test_make_hosts_file_nix():
c = Config(browser_host="foo.bar", al... | 3,109 | 1,291 |
# -*-coding: utf-8 -*-
import os
import re
from sklearn.feature_extraction.text import CountVectorizer
import sys
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfTransformer
import commands
import tflearn
import pickle
max_features=10000
max_docu... | 8,440 | 3,096 |
import numpy as np
from DREAM.Settings.Equations.EquationException import EquationException
from . import DistributionFunction as DistFunc
from . DistributionFunction import DistributionFunction
from .. TransportSettings import TransportSettings
INIT_FORWARD = 1
INIT_XI_NEGATIVE = 2
INIT_XI_POSITIVE = 3
INIT_ISOTROP... | 2,252 | 798 |
# Copyright (c) 2015 Adi Roiban.
# See LICENSE for details.
"""
Tests for the assertion helpers.
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
from chevah.compat.exceptions import CompatError
from chevah.compat.testing import ChevahTestCase, ... | 8,907 | 2,514 |
import unittest
import sys
sys.path.insert(0, '../src/')
from conformal_predictors.icp import ConformalPredictor
from conformal_predictors.nc_measures import *
import conformal_predictors.calibrutils as cu
from sklearn.datasets import *
import numpy as np
from sklearn.svm import SVC
from sklearn.ensemble import Ran... | 2,253 | 805 |
import os.path
import torchvision.transforms as transforms
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from PIL import Image
import PIL
from pdb import set_trace as st
import torch
import numpy as np
#from yolo.utils.datasets import pad
#import torchvision.trans... | 7,561 | 2,652 |
"""Interface to Primare amplifiers using Twisted SerialPort.
This module allows you to control your Primare I22 and I32 amplifier from the
command line using Primare's binary protocol via the RS232 port on the
amplifier.
"""
import logging
import click
from contextlib import closing
from primare_control import Prima... | 8,396 | 2,220 |
#!/usr/bin/env python3
import csv
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
with open(input_file, 'r', newline='') as csv_in_file:
with open(output_file, 'w', newline='') as csv_out_file:
filereader = csv.reader(csv_in_file, delimiter=',')
filewriter = csv.writer(csv_out_file, delimiter=',')
... | 382 | 149 |
class Dog:
"""
Creates dog object
"""
def __init__(self):
self.val = 'dog'
def __repr__(self):
return self.val
class Cat:
"""
Creates cat object
"""
def __init__(self):
self.val = 'cat'
def __repr__(self):
return self.val
| 298 | 101 |
import unittest
from provdbconnector.exceptions.database import InvalidOptionsException, AuthException
from provdbconnector import Neo4jAdapter, NEO4J_USER, NEO4J_PASS, NEO4J_HOST, NEO4J_BOLT_PORT
from provdbconnector.prov_db import ProvDb
from provdbconnector.tests import AdapterTestTemplate
from provdbconnector.test... | 2,980 | 895 |
# -*- coding: utf-8 -*-
import psutil
# CPU
print("CPU: ", psutil.cpu_count()) # CPU逻辑数量
print("CPU: ", psutil.cpu_count(logical=False)) # CPU物理核心
print("CPU: ", psutil.cpu_times()) # 统计CPU的用户/系统/空闲时间
# for x in range(3):
# print(psutil.cpu_percent(interval=1, percpu=True)) # 每秒刷新一次CPU使用率
# 内存
prin... | 1,956 | 1,013 |
import json
from NewDeclarationInQueue.formular_converter import FormularConverter
from NewDeclarationInQueue.preprocess_one_step import PreprocessOneStep
from NewDeclarationInQueue.preprocess_two_steps import PreProcessTwoSteps
from NewDeclarationInQueue.processfiles.customprocess.search_text_line_parameter import Se... | 1,971 | 616 |
"""Extend event column in account history
Revision ID: 18632a2d5fc
Revises: 3e19c50e864
Create Date: 2015-06-05 17:49:12.757269
"""
# revision identifiers, used by Alembic.
revision = '18632a2d5fc'
down_revision = '3e19c50e864'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
fr... | 1,187 | 431 |
import random
import datetime
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
from django.utils import timezone
SECURTYQUESTION = (
('1', "What city were you born in?"),
('2', "What is your mother's maiden name?"),
('3', "What street did you gro... | 8,018 | 2,470 |
from emoji import emojize
from data import all_emoji
from aiogram.types import InlineKeyboardMarkup
from aiogram.types import InlineKeyboardButton
from aiogram.utils.callback_data import CallbackData
cb_confirm_close = CallbackData('cb_cc', 'type_btn')
def create_kb_confirm_close():
emo_snail = all_emoji['back__... | 1,729 | 542 |
'''
This file contains utility of AStarSearch.
Thanks to Binyu Wang for providing the codes.
'''
from random import randint
import numpy as np
class SearchEntry():
def __init__(self, x, y, g_cost, f_cost=0, pre_entry=None):
self.x = x
self.y = y
# cost move form start entry to this entry
... | 9,076 | 2,899 |
import xlrd
from app.services.extension import task_server, sqlalchemy as db
from app.models.core.user import User
from app.application import initialize_app
try:
from app.config.production import ProductionConfig as config_object
except ImportError:
from app.config.local import LocalConfig as config_object
... | 1,270 | 385 |
from praw import Reddit
import random
class Savenger:
AVENGERS = ["Iron Man", "Doctor Strange", "Star-Lord", "Black Widow", "Thor",
"Spider-Man", "Captain America", "Wanda Maximoff", "Bucky Barnes",
"Loki", "Hulk", "Black Panther", "Vision", "Gamora", "Drax", "Nebula",
... | 3,444 | 1,000 |
from .utils.distance import distance
from .classification import MDM
import numpy
from sklearn.base import BaseEstimator, TransformerMixin
##########################################################
class ElectrodeSelection(BaseEstimator, TransformerMixin):
def __init__(self, nelec=16, metric='riemann'):
... | 1,493 | 460 |
from django.conf.urls import url, include
from django.contrib.auth import views as auth
from user.forms import NewAccountForm
from user import views
app_name = 'user'
urlpatterns = [
# auth
url(r'^create/$', views.UserCreate.as_view(), name='create'),
url(r'^login/$', auth.login,
{'template_name... | 1,897 | 622 |
#!/usr/bin/env python3
import subprocess
import re
import argparse
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--interface", dest="interface",
help="interface to change mac address")
parser.add_argument("-m", "--mac", dest="new_mac",
... | 1,728 | 521 |
import tensorflow as tf
import numpy as np
import time
import utils
path = r'data/'
x, y = utils.reload_data(path)
inp_shape = (x[0].shape[0],1)
x = np.array(x).reshape(-1, 1000, 1)# change 1000 to your sample lenght if you changed frame (= CHUNK ) or RESOLUTION
# prepared for testing and evaluating. try other comb... | 1,916 | 657 |
# Generated by Django 3.1.6 on 2021-02-12 07:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | 6,163 | 1,868 |
import logging
from common.api_handlers import handle_request
from common.packet import Packet
from common.response import Response
from common.transport.protocol import TCPProtocol
from game.models.world import WORLD
from game.session import GameSession
from game.states import Connected
LOG = logging.getLogger(f"l2p... | 1,306 | 351 |
import fileinput
# "day6.txt"
groups = [x.split() for x in ''.join(fileinput.input()).split('\n\n')]
# part 1
print(sum(len(set([j for sub in group for j in sub])) for group in groups))
# part 2
print(sum(len(set.intersection(*[set(list(j)) for j in group])) for group in groups))
| 292 | 113 |
'''Considere o problema de computar o valor absoluto de um número real.
O valor absoluto de um número real x é dado por f(x) = x se x >= 0 ou f(x) = -x se x < 0.
Projete e implemente um programa em Python que lei um número de ponto flutuante x, calcule e imprima o valor absoluto de x.'''
x = float(input())
y = (x**2)... | 370 | 144 |
import torch
import warnings
def newton_raphson(fn, x0, linsolver = "lu", rtol = 1e-6, atol = 1e-10,
miter = 100):
"""
Solve a nonlinear system with Newton's method. Return the
solution and the last Jacobian
Args:
fn: function that returns the residual and Jacobian
x0:... | 1,394 | 492 |
# Time: O(n)
# Space: O(1)
class Solution(object):
def numSub(self, s):
"""
:type s: str
:rtype: int
"""
MOD = 10**9+7
result, count = 0, 0
for c in s:
count = count+1 if c == '1' else 0
result = (result+count)%MOD
return resu... | 323 | 117 |
import logging
import datetime
import asyncio
from edgefarm_application.base.application_module import application_module_network_nats
from edgefarm_application.base.avro import schemaless_decode
from run_task import run_task
from state_tracker import StateTracker
from schema_loader import schema_load
_logger = logg... | 4,531 | 1,367 |
from termcolor import colored, cprint
import sys
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')
for i in range(10):
cprint(i, 'magenta', end=' ')
cprint("Attention!",'red', attrs=['bold'], file=sys.stdout)
| 302 | 113 |
import sys
from azureml.core import Workspace, Experiment, Environment, ScriptRunConfig
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
from shutil import copy
ws = Workspace.from_config()
# Choose a name for your CPU cluster
# cpu_cluster_name... | 1,597 | 476 |
import cpuinfo
def pytest_benchmark_update_json(config, benchmarks, output_json):
"""Calculate compression/decompression speed and add as extra_info"""
for benchmark in output_json["benchmarks"]:
if "data_size" in benchmark["extra_info"]:
rate = benchmark["extra_info"].get("data_size", 0.0... | 818 | 264 |
import time
import gcld3
detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0,
max_num_bytes=1000)
# text = "This text is written in English"
text = "薄雾"
while True:
result = detector.FindLanguage(text=text)
print(text, result.probability, result.language)
time.s... | 331 | 116 |
'''
实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
必须 原地 修改,只允许使用额外常数空间。
示例 1:
输入:nums = [1,2,3]
输出:[1,3,2]
示例 2:
输入:nums = [3,2,1]
输出:[1,2,3]
示例 3:
输入:nums = [1,1,5]
输出:[1,5,1]
示例 4:
输入:nums = [1]
输出:[1]
提示:
1 <= nums.length <= 100
0 <= nums[i] <= 100
'''
class Solution:
... | 1,593 | 819 |
# script to generate the overview and individual html report website.
import os
import numpy
def main(result_folder, name, header_comp):
menu_html_file_path = '/home/brain/qa/html/menu_html.html'
menu_html_file = open(menu_html_file_path, 'r')
menu_html = menu_html_file.readlines()
menu_html_file.close()
resul... | 7,906 | 3,561 |
class tabla_de_sesgos :
def __init__(self) :
self.sesgo = None #
self.clase_de_sesgo = None #
pass
class marcador (reproductor, tabla_de_sesgos, registro_de_tiempos, medio) :
def __init__(self) :
pass
def cargar_medio (self) :
# returns
pass
def marcar_tiempos (self) :
# returns
pass
def marcar... | 786 | 358 |
"""Generates the supported SOP Classes."""
from collections import namedtuple
import inspect
import logging
import sys
from pydicom.uid import UID
from pynetdicom3.service_class import (
VerificationServiceClass,
StorageServiceClass,
QueryRetrieveServiceClass,
BasicWorklistManagementServiceClass,
)
... | 12,226 | 6,520 |
import os
from datetime import datetime
import numpy as np
import tensorflow as tf
from tensorflow.python.training import moving_averages
TF_DTYPE = tf.float64
MOMENTUM = 0.99
EPSILON = 1e-6
DELTA_CLIP = 50.0
class FeedForwardModel():
"""
Abstract class for creating neural networks.
Offers functions to ... | 7,885 | 2,140 |
from .dataset import load_pr, load_1dof, load_mvc, load_ndof
__all__ = ["load_pr", "load_1dof", "load_mvc", "load_ndof"]
| 122 | 53 |
"""
Fibonacci sequence using python
generators
Written by: Ian Doarn
"""
def fib():
# Generator that yields fibonacci numbers
a, b = 0, 1
while True: # First iteration:
yield a # yield 0 to start with and then
a, b = b, a + b # a will now be 1, and b will also be 1,... | 619 | 218 |
glossary = {
'intger': 'is colloquially defined as a number that can be written without a fractional component.\n',
'iterate': 'is the repetition of a process in order to generate a sequence of outcomes.\n',
'indentation': 'is an empty space at the beginning of a line that groups particular blocks of code.\... | 974 | 264 |
import ast
import argparse
import json
import os
import pprint
import astor
import tqdm
import _jsonnet
from seq2struct import datasets
from seq2struct import grammars
from seq2struct.utils import registry
from third_party.spider import evaluation
def main():
parser = argparse.ArgumentParser()
parser.add_a... | 1,711 | 555 |
from tune.constants import TUNE_STOPPER_DEFAULT_CHECK_INTERVAL
from typing import Any, Callable, Optional
from tune._utils import run_monitored_process
from tune.concepts.flow import Trial, TrialReport
class NonIterativeObjectiveFunc:
def generate_sort_metric(self, value: float) -> float: # pragma: no cover
... | 1,632 | 511 |
a1 = 'mary'
b1 = 'army'
a2 = 'mary'
b2 = 'mark'
def is_anagram(a, b):
"""
Return True if words a and b are anagrams.
Return Flase if otherwise.
"""
a_list = list(a)
b_list = list(b)
a_list.sort()
b_list.sort()
if a_list == b_list:
return True
else:
return False
... | 371 | 157 |
from sqlalchemy import (
Column,
ForeignKey,
Integer,
Text,
)
from sqlalchemy.orm import relationship
from .meta import Base
class Notification(Base):
__tablename__ = 'notification'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey("user.id"), nullable=False)
... | 459 | 142 |
# -*- coding: utf-8 -*-
"""
model helper
~~~~~~~~~~~~
:Created: 2016-8-5
:Copyright: (c) 2016<smileboywtu@gmail.com>
"""
from customer_exceptions import OffsetOutOfRangeException
class ListModelHelper(object):
"""get the object list"""
@classmethod
def list(cls, index=0, limit=8, sor... | 1,340 | 405 |
from django import template
register = template.Library()
from .. import utils
@register.filter
def admin2_urlname(view, action):
"""
Converts the view and the specified action into a valid namespaced URLConf name.
"""
return utils.admin2_urlname(view, action)
@register.filter
def model_app_label(... | 2,603 | 719 |
"""
Tests for edges.py
"""
import unittest
import pandas as pd
from biothings_explorer.user_query_dispatcher import SingleEdgeQueryDispatcher
from biothings_explorer.filters.edges import filter_node_degree
class TestFilterEdges(unittest.TestCase):
# test for count values
def test_count_values(self):
... | 2,323 | 697 |
"""
Retrieves data as json files from fantasy.premierleague.com
"""
import json
import requests
LAST_SEASON_DATA_FILENAME = "data/player_data_20_21.json"
DATA_URL = "https://fantasy.premierleague.com/api/bootstrap-static/"
DATA_FILENAME = "data/player_data_21_22.json"
FIXTURES_URL = "https://fantasy.premierleague.c... | 974 | 370 |
from beamngpy import BeamNGpy, Vehicle, Scenario, ScenarioObject
from beamngpy import setup_logging, Config
from beamngpy.sensors import Camera, GForces, Lidar, Electrics, Damage, Timer
import beamngpy
import time, random
# globals
default_model = 'pickup'
default_scenario = 'west_coast_usa' #'cliff' # smallgrid
dt = ... | 5,587 | 2,127 |
#!/usr/bin/env python
from __future__ import print_function
import os, optparse, glob
import depotcache, acf
from ui import ui_tty as ui
import hashlib
import sys
g_indent = ' '
colours = {
False: 'back_red black',
True: ''
}
class UnknownLen(list): pass
def depot_summary_ok(mounted):
if len(mounted) > 0:
... | 17,827 | 6,722 |
from gpiozero import DistanceSensor
from time import sleep
sensor = DistanceSensor(echo=23, trigger=22)
while True:
print('Distance: ', sensor.distance * 100)
sleep(1)
| 178 | 63 |
import pickle
def remove_duplicate_from_list(data):
""" remove duplications from specific list
any data can be contained in the data.
if the data is hashable, you can implement this function easily like below.
data = list(set(data))
but if the data is unhashable, you have to im... | 1,070 | 341 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 NYU Libraries.
#
# ultraviolet-cli is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio module for custom UltraViolet commands."""
import click
import glob
import json
import os
imp... | 7,226 | 2,364 |
from __future__ import annotations
from enum import Enum, auto
class Paradigm(Enum):
NONE = auto()
KFULIM = auto()
KFULIM_2 = auto() # used only for HUFAL
NO_PREFIX = auto() # used for words like 'hUnDA!s', 'hU_wA!n', 'nI_sa!H', 'nI_qa!H'
PE_ALEF = auto() # used only for PAAL
PAAL_1 = auto(... | 1,320 | 551 |
class SettingsFactoryDoesNotExist(Exception):
pass
class InvalidSettingsFactory(Exception):
pass
class NoMatchingSettings(Exception):
"""Raised when a suitable settings class cannot be found."""
pass
class InvalidCondition(Exception):
pass
| 266 | 70 |
import gevent
import docker
import os
from function_info import parse
from port_controller import PortController
from function import Function
import random
repack_clean_interval = 5.000 # repack and clean every 5 seconds
dispatch_interval = 0.005 # 200 qps at most
# the class for scheduling functions' int... | 1,834 | 560 |
import sets
import scan_set
import os
path = 'ids/'
setlist = os.listdir(path)
def getall(set):
id = scan_set.scan_set(set)
scan_set.write_ids(set, id)
for set in sets.set_info:
s = set + '.txt'
if s not in setlist:
print "Getting " + set
getall(set)
print "\n\nCompletely Finis... | 333 | 128 |
# ------------------------------------------------------------------------------------------------
# Copyright (c) 2018 Microsoft Corporation
#
# 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 ... | 6,717 | 2,103 |
#!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2019, UFACTORY, Inc.
# All rights reserved.
#
# Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com>
"""
Example: Get GPIO Digital
"""
import os
import sys
import time
sys.path.append(os.path.join(os.path.dirname(__file__), ... | 1,172 | 455 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from . import _utilities
import typing
# Export this package's modules as members:
from .cached_image import *
from .container import *... | 2,429 | 1,005 |
class Solution:
def groupAnagrams(self, strs):
l = len(strs)
if l == 0:
return []
map = dict()
for i in range(l):
key = ''.join(sorted(strs[i]))
if key in map.keys():
map[key].append(i)
else:
map[key] = ... | 544 | 184 |
#!/usr/bin/env python3
import os
import time
import sys
gpio = None
try:
import RPi.GPIO
gpio = RPi.GPIO
except:
print('RPi library not found. We\'re probably on a dev machine. Moving on...')
import lvconfig
import litrpc
# This could be more efficient, we're making a lot more requests than we need to.
def che... | 2,429 | 1,002 |
#*** 文字列 ***
#Pythonで文字列を作るには, ' (シングルクォーテーション)もしくは, " (ダブルクォーテーション)で囲む.
print('some eggs')
print("some eggs")
print('some eggs\nsome eggs')
#a == b は aとb同値であればTrue, そうでなければFalseを返す演算子です
print('some eggs' == "some eggs") #True
#'...' の中で ' ,または "..." の中で " を使う場合には,
#各記号のまえに \ (バックスラッシュ) を入力する.
print("I don't Kno... | 3,070 | 2,467 |
import pytest
from fluentql import GenericSQLDialect, Q
from fluentql.types import Table
test_table = Table("test_table")
@pytest.fixture
def dialect_cls():
return GenericSQLDialect
@pytest.mark.parametrize(
["q", "expected"],
[
(Q.delete().from_(test_table), "delete from test_table;"),
... | 570 | 198 |
from nltk.grammar import CFG
from nltk.parse.chart import ChartParser, BU_LC_STRATEGY
grammar = CFG.fromstring("""
S -> T1 T4
T1 -> NNP VBZ
T2 -> DT NN
T3 -> IN NNP
T4 -> T3 | T2 T3
NNP -> 'Tajmahal' | 'Agra' | 'Bangalore' | 'Karnataka'
VBZ -> 'is'
IN -> 'in' | 'of'
DT -> 'the'
NN -> 'capital'
""")
cp = ChartParser(g... | 597 | 262 |
from sphinx import cmdline
import sys
cmdline.main(sys.argv)
| 62 | 23 |
import logging
from .store.user import User
from .errors import SlackInactiveDispatcher, SlackNoThread
logger = logging.getLogger(__name__)
class SlackWrapper:
"""
A class to compose all available functionality of the slack plugin.
An instance is offered to all incoming message of all the plugins to
... | 5,526 | 1,415 |
import warnings
warnings.filterwarnings('ignore') #ignore warnings to print values properly
import logging
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassif... | 4,321 | 1,371 |
from typing import Dict, List
mtbs_colormaps: Dict[str, Dict[int, List[int]]] = {
"mtbs-severity": {
0: [0, 0, 0, 0],
1: [0, 100, 0, 255],
2: [127, 255, 212, 255],
3: [255, 255, 0, 255],
4: [255, 0, 0, 255],
5: [127, 255, 0, 255],
6: [255, 255, 255, 255],
... | 326 | 199 |
import sys
from app import app, socketio
if __name__ == "__main__":
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port=5000
socketio.run(app, host="0.0.0.0", port=port) | 183 | 86 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import numpy as np
import pylab as pl
from txtTools import openIOFile
# =*=*=*=* FUNCTION DEFINITIONS *=*=*=*=*=*=*=*=*=*=*=*
def isolateValues( line , stripChars ):
v = []
sl = line.split()
for i in xrange(len(sl)):
for sc in stripChars:
sl[i]... | 1,004 | 487 |
import unittest
from fluentcheck import Is
from fluentcheck.exceptions import CheckError
# noinspection PyStatementEffect
class TestIsBasicChecks(unittest.TestCase):
def test_is_none_pass(self):
self.assertIsInstance(Is(None).none, Is)
def test_is_none_fail(self):
with self.assertRaises(Chec... | 580 | 189 |
# Generated by Django 2.0.2 on 2018-02-18 17:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('calculator', '0002_calculation_add_occurrences'),
]
operations = [
migrations.AddField(
model_name='calculation',
na... | 414 | 138 |
from django.db import models
from django.core.exceptions import ValidationError
from rest_framework.exceptions import ValidationError as DRFValidationError
from api.models import TimestampedModel
class Interest(TimestampedModel):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
... | 627 | 173 |
"""Box for specifying initial guess for the fitting algorithm."""
from typing import Callable, List, Optional
import numpy as np
import toga
from eddington import EddingtonException
from toga.style import Pack
from eddington_gui.boxes.line_box import LineBox
from eddington_gui.consts import SMALL_INPUT_WIDTH
class ... | 3,652 | 1,138 |
"""
examples.select
===============
An example that demonstrates the Select child class.
"""
from cues.cues import Select
def main():
name = 'programming_language'
message = 'Which of these is your favorite programming language?'
options = ['Python', 'JavaScript', 'C++', 'C#']
cue = Select(name, me... | 418 | 130 |
import json
import unittest
from functools import partial
import ckan.model as model
import responses
from ckanext.satreasury.plugin import SATreasuryDatasetPlugin
from mock import MagicMock, Mock, PropertyMock, patch
TRAVIS_ENDPOINT = "https://api.travis-ci.org/repo/vulekamali%2Fstatic-budget-portal"
TRAVIS_COMMIT_M... | 6,685 | 1,998 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Routines to evaluate the system.
"""
import logging
from collections import Counter
from . import db
logger = logging.getLogger(__name__)
def get_exhaustive_samples(corpus_tag):
"""
Use the document_sample table to get which documents have been exhaustively... | 2,011 | 656 |
#! /usr/bin/env python
import os
import sys
from .api import install as install_mmd
def model_data_dir(name, datarootdir=None):
"""Get a model's data dir.
Parameters
----------
name : str
The name of the model.
Returns
-------
str
The absolute path to the data directory ... | 2,212 | 656 |
#!/usr/bin/python3
import os
import subprocess
import re
import pymysql
from datetime import datetime
strPath = r"/etc/webmin/servers";# file dir
files = os.listdir(strPath)
lists = [];# file lists
host = [];
user = [];
pwd = [];
val = 0;# extractServer use
test = "";# grep host
test1 = "";# grep user
test2 = "";# gre... | 8,060 | 2,582 |
"""Tree level width module."""
from collections import deque
def tree_level_width(tree):
"""Return a list containing the width of each level of the specified tree."""
result = []
count = 0
queue = deque([tree.root, "s"])
while len(queue) > 0:
node = queue.popleft()
if node == "s":
... | 579 | 159 |
import os
import unittest
import clib
from clib.utils import Box
class BboxTest(unittest.TestCase):
def setUp(self):
self.bbox = Box(50, 50, 40, 60)
def test_vi_bbox(self):
self.assertEqual(self.bbox.int_left_top(), (30, 20))
self.assertEqual(self.bbox.int_right_bottom(), (70, 80))
... | 592 | 250 |
# coding: utf-8
"""
IriusRisk API
Products API # noqa: E501
OpenAPI spec version: 1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from iriusrisk_py... | 67,167 | 19,031 |
# This file is placed in the Public Domain.
import queue
import threading
from .dpt import Dispatcher
from .obj import Object
from .thr import launch
from .utl import get_exception
class Restart(Exception):
pass
class Stop(Exception):
pass
class Loop(Object):
def __init__(self):
super().__... | 1,246 | 368 |
import json
import logging
from io import BytesIO
from typing import List
from typing import Optional
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from telegram import InputMediaPhoto
def __convert_plot_to_telegram_photo(plot) -> InputMediaPhoto:
with BytesIO() as buffer:
plo... | 3,619 | 1,187 |
# coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, Mathijs Dumon
# All rights reserved.
# Complete license can be found in the LICENSE file.
from io import StringIO
from scipy.optimize import fmin_l_bfgs_b
from .exceptions import wrap_exceptions
def setup_project(projectf):
from pyxrd.file_parsers.json_... | 2,215 | 670 |
import functools
def enforceType(func):
@functools.wraps(func)
def wrapper(*args):
wrapper.has_been_called = True
x = func.__annotations__
t = [x[i] for i in x if i != 'return']
if len(args) != len(t):
raise TypeError("Missing required positional arguments and/or annotations.")
for i in range(... | 931 | 371 |
# encoding: UTF-8
from __future__ import print_function
import sys
try:
reload(sys) # Python 2
sys.setdefaultencoding('utf8')
except NameError:
pass # Python 3
import multiprocessing
from time import sleep
from datetime import datetime, time
from cyvn.trader.vtEvent import EVENT_LOG, EVENT_REC... | 3,239 | 1,298 |
# Python3
a, b = [int(i) for i in input().split()]
def euclid_gcd(a, b):
if b == 0:
return a
c = a%b
return euclid_gcd(b, c)
if a>b:
gcd = euclid_gcd(a, b)
else:
gcd = euclid_gcd(b, a)
print(a*b//gcd) | 232 | 123 |
import os
current_dir = os.path.dirname(os.path.realpath(__file__))
import gym
from gym.envs.registration import registry, make, spec
def register(id, *args, **kvargs):
if id in registry.env_specs:
return
else:
return gym.envs.registration.register(id, *args, **kvargs)
register(id="RandomW... | 711 | 264 |
import datetime
from django.test import TestCase
from libya_elections.utils import at_noon
class ScheduleTest(TestCase):
def test_at_noon(self):
# at_noon returns a datetime with the right values
dt = datetime.datetime(1970, 2, 3, 4, 5, 6, 7)
result = at_noon(dt)
self.assertEqual(... | 471 | 163 |
from django.conf.urls import url
from website.apps.statistics.views import statistics
urlpatterns = [
url(r'^$', statistics, name="statistics"),
]
| 153 | 48 |
from skimage import measure
import pydicom
from pydicom.dataset import Dataset, FileDataset
from pydicom.sequence import Sequence
import os
import numpy as np
import SimpleITK as sITK
import time
import glob
import sitk_ct_io as imio
from skimage.draw import polygon
# for debugging
# import matplotlib.p... | 12,779 | 4,394 |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 20 14:03:18 2020
@author: Nicolai
"""
import sys
sys.path.append("../differential_evolution")
from JADE import JADE
import numpy as np
import scipy as sc
import testFunctions as tf
def downhillsimplex(population, function, minError, maxFeval):
'''
implementatio... | 2,364 | 781 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import random
import pandas as pd
import os
class InstagramBot:
def __init__(self, username, password, function, url, num_people=1):
'''
Bot that comment on photos on Instagram
Args:
usern... | 7,030 | 1,850 |