text string | size int64 | token_count int64 |
|---|---|---|
from marshmallow_sqlalchemy import TableSchema
from .marshmallow import marshmallow as ma
from .user import User, UserLocation
from .alerts import AlertSubscription, AlertType
class UserSchema(TableSchema):
class Meta:
table = User.__table__
exclude = ("deleted", "created", "updated")
stri... | 1,612 | 494 |
#!/usr/bin/env python3
import numpy as np
import tensorflow as tf
from tensorflow_tts.flows.utils.flow_step import build_flow_step, _Model
class FlowStepTest(tf.test.TestCase):
def setUp(self):
super().setUp()
self.model = _Model()
x = tf.random.normal([128, 32, 64])
cond = tf.ran... | 1,034 | 408 |
"""
********************************************************************************
datastructures
********************************************************************************
.. currentmodule:: compas.datastructures
Mesh
====
The mesh is implemented as a half-edge datastructure.
It is meant for the representa... | 3,189 | 1,017 |
import bpy
from gpu_extras.batch import batch_for_shader
from bpy.types import Operator, GizmoGroup, Gizmo
import bmesh
import bgl
import gpu
from math import sin, cos, pi
from gpu.types import (
GPUBatch,
GPUVertBuf,
GPUVertFormat,
)
from mathutils import Matrix, Vector
import mat... | 10,850 | 3,696 |
import numpy as np
import torch
import random
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision as vision
import sys
from scipy.misc import imresize
from torchvision import transforms, utils
import models.modules as modules
import sc... | 8,465 | 2,785 |
"""ws-sanity-check script.
Execute a sanity check on the configuration.
"""
# Standard Library
import sys
import typing as t
# Websauna
from websauna.system import SanityCheckFailed
from websauna.system.devop.cmdline import init_websauna
from websauna.system.devop.scripts import FAIL_MSG
from websauna.system.devop.sc... | 1,223 | 413 |
#### Write a File ####
with open('somefile.txt', 'w') as file:
file.write('tomato\npasta\ngarlic')
#### Read a File ####
with open('somefile.txt', 'r') as file:
# Read the whole content into one string.
content = file.read()
# Make a list where each line of the file is an element in the list.
print... | 1,410 | 451 |
#!/usr/bin/env python
from nodes import Node
import lang_ast
class NodeSingle(Node):
args = 0
results = 1
ignore = True
def __init__(self, value):
self.value = value
def func(self):
return self.value
def __repr__(self):
return "%s: %s"%(self.__class__.__name_... | 601 | 188 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by "HYOUG"
from argparse import ArgumentParser
def xorbytes(target:bytes, key:bytes) -> bytes:
output = []
index = 0
for byte in target:
output.append(byte ^ key[index % (len(key)-1)])
return bytes(output)
def main() -> None:
parse... | 1,007 | 369 |
import torch
import numpy as np
import timeit
start = timeit.default_timer()
import misc as ms
import ann_utils as au
def main(main_dict, train_only=False):
ms.print_welcome(main_dict)
# EXTRACT VARIABLES
reset = main_dict["reset"]
epochs = main_dict["epochs"]
batch_size = main_dict["batch_size"]
sam... | 4,257 | 1,381 |
import numpy as np
brain_offsets = {
"10-01": [69445.19581378, 12917.40798423, 30199.63896704],
"8-01": [70093.27584462, 15071.5958194, 29306.73645404],
}
vol_offsets = {
"10-01": {
1: [3944.427317, 1689.489974, 2904.058044],
2: [7562.41721, 2517.659516, 6720.099583],
3: [6440.34456... | 3,021 | 2,448 |
import click
from strava import api
from strava.decorators import output_option, login_required, format_result, OutputType
_PROFILE_COLUMNS = ("key", "value")
@click.command("profile")
@output_option()
@login_required
@format_result(table_columns=_PROFILE_COLUMNS)
def get_profile(output):
result = api.get_athle... | 777 | 257 |
"""
Workflows for operating on images
"""
from .image_rsexecute import *
| 80 | 29 |
from __future__ import absolute_import
import os
import json
from datetime import datetime, timedelta
from nose.tools import assert_equal, assert_in
from app import create_app, db
from app.models import Service, Supplier, ContactInformation, Framework, Lot, User, FrameworkLot, Brief, Order
TEST_SUPPLIERS_COUNT = 3
... | 11,419 | 3,412 |
__all__ = ['PEBox','PEPlane','PEMesh','BoxGoal','PEHingeJoint']
from objects import PEBox, PEPlane
from meshobjs import PEMesh
from goals import BoxGoal
from joints import PEHingeJoint | 185 | 67 |
# Generated by Django 3.0.8 on 2020-09-16 18:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('journeys', '0020_auto_20200916_1810'),
('journeys', '0020_auto_20200916_1651'),
]
operations = [
]
| 275 | 131 |
"""
File:
version.py
Description:
pySPEDAS version number.
Returns:
The version number for the current installation.
"""
def version():
import pkg_resources
ver = pkg_resources.get_distribution("pyspedas").version
print("pyspedas version: " + ver)
| 277 | 91 |
from todb.main import todb
from todb.params import InputParams
| 63 | 19 |
from django.conf import settings
from django.contrib import admin, auth
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from django.utils.html import format_html
from django.urls import reverse
from olympia.accounts.utils import redirect_for_login
from . import models
def r... | 2,221 | 647 |
import os, csv, time
def beep(f,d):
os.system('beep -f %s -l %s' % (f,d))
with open('musica.txt') as csvfile:
dataOrig = list(csv.reader(csvfile))
data=[]
for k in dataOrig:
data=data+k[:-1]
for j in range(len(data)):
data[j]=int(data[j])
duration=200
n=1
data=data[:50]
for i in r... | 686 | 316 |
import pygame
import tydev
from tydev.gui.template import Template
class List(Template):
def __init__(self, location, size):
Template.__init__(self, location=location, size=size)
self.background_color = (255, 255, 255)
self.highlight_color = (130, 145, 255)
self.objects = []
... | 4,558 | 1,379 |
import csv
import numpy as np
import torch
import matplotlib.pyplot as plt
def TrainHistoryPlot(his, his_label, save_name, title, axis_name, save = True):
#history must be input as list[0]: iter or epoch
#and otehr of history list is the acc or loss of different model
plt.figure(figsize = (10, 6))
for... | 1,525 | 536 |
import datetime
import os
# =================================================
# Background Information
# -------------------------------------------------
mip = "cmip5"
exp = "historical"
frequency = "mo"
realm = "atm"
# =================================================
# Analysis Options
# --------------------------... | 2,254 | 853 |
from setuptools import setup, find_packages
setup(
name = 'spline-pokedex',
version = '0.1',
packages = find_packages(),
install_requires = [
'spline',
'pokedex',
'SQLAlchemy>=0.6',
],
include_package_data = True,
package_data={'splinext': ['*/i18n/*/LC_MESSAGES/*.m... | 769 | 287 |
import argparse
from collections import Counter
import hashlib
import random
from joblib import Parallel, delayed
import matplotlib.pyplot as plt
import multiprocessing
import networkx as nx
import numpy as np
from tqdm import tqdm
def get_degrees(graph):
return {node:str(degree) for node, degree in graph.degree}... | 6,915 | 2,366 |
import click
from rino import config
def set(path):
if path.startswith('/'):
path = path[1:]
if config.set('remote', path):
click.echo('remote path set to %s' % path)
def unset():
if config.set('remote', None):
click.echo('remote path is unset')
def list():
if config.get('rem... | 441 | 139 |
# This file contains the WSGI configuration required to serve up your
# web application at http://Moosky.pythonanywhere.com/
# It works by setting the variable 'application' to a WSGI handler of some
# description.
#
# +++++++++++ GENERAL DEBUGGING TIPS +++++++++++
# getting imports and sys.path right can be fiddly!
#... | 982 | 324 |
from hashlib import sha256
from tkinter import *
import time
import sys
import webbrowser
global LastHash;LastHash=""
try:
open('HASH.dat','x').write('')
except:
pass
#global difficulty
difficulty=1
#global index
index=[]
class block:
def __init__(self,data):
self.tim... | 2,999 | 1,148 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import json
from transformers import BertModel
from tools.accuracy_tool import multi_label_accuracy, single_label_top1_accuracy
class DenoiseBert(nn.Module):
def __init__(self, config, gpu_list, *args, **params):
super(Denois... | 2,310 | 836 |
import tensorflow as tf
import random
from tensorflow.keras.layers import Flatten, Dense, Dropout, Conv2D, MaxPooling2D
from tensorflow.keras.constraints import MaxNorm
class CNN(tf.keras.Model):
def __init__(self, shape, number_of_classes, min_hidden_layer_cnn=3, max_hidden_layer_cnn=10,
min_nod... | 1,571 | 574 |
from file_utilities import readCSVFile
from PlotterLine import PlotterLine
def plotDataSets(data_sets, data_names):
for var in data_names:
desc, symbol = data_names[var]
plotter = PlotterLine("$x$", desc + ", $" + symbol + "$")
for i, data_set in enumerate(data_sets):
set_name, data = data_set
... | 612 | 234 |
import faker
import unittest
from scrubadub.filth import SocialSecurityNumberFilth
from base import BaseTestCase
class SSNTestCase(unittest.TestCase, BaseTestCase):
def test_example(self):
"""
BEFORE: My social security number is 726-60-2033
AFTER: My social security number is {{SOCIAL_... | 1,257 | 418 |
#!/usr/bin/env python
import argparse
import django
import os
import sys
from django.conf import settings
from django.test.utils import get_runner
'''
Reference: https://docs.djangoproject.com/en/3.0/topics/testing/advanced/#defining-a-test-runner
Command line arguments:
--integration This optional... | 2,633 | 904 |
# Generated by Django 2.0.9 on 2019-11-16 03:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0005_auto_20191018_1819'),
]
operations = [
migrations.AddField(
model_name='profile',
name='notification_t... | 672 | 216 |
from django.contrib.auth.models import User
from django.shortcuts import resolve_url
from django.test import TestCase
class TestGetLogout(TestCase):
def setUp(self):
User.objects.create_user('olivia', password='password')
self.client.login(username='olivia', password='password')
self.resp... | 452 | 137 |
from invoke import task
DOCKER_COMPOSE = 'docker-compose.yml'
DOCKER_COMPOSE_SEARCH = 'docker-compose-search.yml'
DOCKER_COMPOSE_COMMAND = f'docker-compose -f {DOCKER_COMPOSE} -f {DOCKER_COMPOSE_SEARCH}'
@task
def build(c):
"""Build docker image for servers."""
c.run(f'{DOCKER_COMPOSE_COMMAND} build --no-cach... | 2,535 | 951 |
from argparse import ArgumentParser
def add_data_args(parent_parser):
parser = ArgumentParser(parents=[parent_parser], add_help=False)
# data args
parser.add_argument("--batch_size", type=int, default=128)
return parser
| 238 | 74 |
# Generic build script that builds, tests, and creates nuget packages.
#
# INSTRUCTIONS:
# Update the following project paths:
# proj Path to the project file (.csproj)
# test Path to the test project (.csproj)
# nuspec Path to the package definition for NuGet.
#
# delete any of the lines if not appli... | 7,196 | 3,071 |
#
# Copyright (c) 2010-2017 Fabric Software Inc. All rights reserved.
#
from PySide import QtCore, QtGui
from FabricEngine.Canvas.Utils import *
class HotkeyStyledItemDelegate(QtGui.QStyledItemDelegate):
keyPressed = QtCore.Signal(QtGui.QKeySequence)
def __init__(self, parent=None):
super(HotkeyStyl... | 1,664 | 478 |
#!/usr/bin/env python2.7
#
# Copyright (C) 2013-2014 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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 Licens... | 7,133 | 2,032 |
"""Removes unmodified GenericLogicalFiles found in composite resources. This functionality is
to remove unused GenericLogicalFiles that were created by an earlier iteration of CompositeResource
that created an aggregation for every file added to a resource.
"""
from django.core.management.base import BaseCommand
fr... | 1,423 | 392 |
# Generated by Django 3.0.6 on 2020-09-06 20:21
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(au... | 1,287 | 371 |
import matplotlib.pyplot as plt
import numpy as np
def feval(funcName, *args):
return eval(funcName)(*args)
def backwardEuler(func, yinit, x_range, h):
m = len(yinit)
n = int((x_range[-1] - x_range[0])/h)
x = x_range[0]
y = yinit
xsol = np.empty(0)
xsol = np.append(xsol, x)
ysol = ... | 1,385 | 629 |
import os
import glob
import ruamel.yaml
from setup_app import paths
from setup_app.static import AppType, InstallOption
from setup_app.utils import base
from setup_app.config import Config
from setup_app.utils.setup_utils import SetupUtils
from setup_app.installers.base import BaseInstaller
class OxdInstaller(SetupU... | 7,531 | 2,629 |
import numpy as np
import scipy.sparse as sp
import torch
import torch.nn as nn
from tqdm import tqdm
import networkx as nx
import random
import math, os
from collections import defaultdict
import argparse
from models import DGI, LogReg
from utils import process
from attacker.attacker import Attacker
from estim... | 7,303 | 2,782 |
from wiki.models import Page
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
class PageList(ListView):
'''
Renders a list of all Pages.
==CHALLENGES==
1. GET: Have a homepage showing all Pages in your wiki.
2. Add a descriptiv... | 2,248 | 766 |
from dash import Dash
from rubicon_ml.viz import ExperimentsTable
def test_experiments_table(viz_experiments):
experiments_table = ExperimentsTable(experiments=viz_experiments, is_selectable=True)
expected_experiment_ids = [e.id for e in viz_experiments]
for experiment in experiments_table.experiments:... | 2,895 | 880 |
from GrStat import GroundStation, Reception
from sat import Satellite
from pathos.pools import ParallelPool
from scipy import interpolate
import pandas as pd
import numpy as np
import pickle
import tqdm
import datetime
import sys, os
# this file contains the functions used to estimate antenna sizes and di... | 7,274 | 2,554 |
import clr
import sys
clr.AddReference('ZyGames.Framework.Common')
clr.AddReference('ZyGames.Framework')
clr.AddReference('ZyGames.Framework.Game')
clr.AddReference('ZyGames.Tianjiexing.Model')
clr.AddReference('ZyGames.Tianjiexing.BLL')
clr.AddReference('ZyGames.Tianjiexing.Lang')
from System import *
from... | 3,054 | 1,039 |
# -*- coding: utf-8 -*-
import time
from .. import Metrics
from ..Exceptions import StoryscriptRuntimeError
from ..Story import Story
from ..constants.LineSentinels import LineSentinels
from ..processing import Lexicon
class Stories:
@staticmethod
def story(app, logger, story_name):
return Story(app... | 2,596 | 693 |
"""Version 0.66.001
Revision ID: f33e544af3e0
Revises: 836595368d1e
Create Date: 2020-09-25 05:52:02.580943
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from sqlalchemy import Enum
# revision identifiers, used by Alembic.
revision = 'f33e544af3e0'
down_revision = '83659536... | 8,327 | 2,675 |
# exercise 8.1.2
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from toolbox_02450 import rocplot, confmatplot
font_size = 15
plt.rcParams.update({'font.size': font_size})
# Load... | 3,028 | 1,193 |
from . import data_generators | 29 | 8 |
from model import MyAwesomeModel
import numpy as np
import torch
from make_dataset import mnist
from torch import nn, optim
import matplotlib.pyplot as plt
def test_Model():
model = MyAwesomeModel()
train_set, _ = mnist()
trainloader = torch.utils.data.DataLoader(
train_set, batch_size=... | 645 | 198 |
import datetime
import random
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtMultimedia import QSound
import sys
from .resources import *
class Ui_main_window(object):
def setupUi(self, main_window):
self.running_applet = False
self.counter = 0
self.app_no = 0
... | 49,037 | 17,627 |
import os
import sys
import uuid
from app.configuration import Files, Configuration
from app.command_parser import get_parsers
from app.formatted_argparse import FormattedParser
from app.help_functions import *
from app.parser_args import ParserArgs
from app.printer import Printer
from app.user_wrapper import (
Us... | 25,056 | 7,646 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 5 21:46:50 2020
@author: pengning
"""
import numpy as np
import scipy.special as sp
import matplotlib.pyplot as plt
from .shell_domain import shell_rho_M, shell_rho_N
import mpmath
from mpmath import mp
from .dipole_field import mp_spherical_jn, m... | 14,647 | 6,145 |
import logging
import threading
import typing
if typing.TYPE_CHECKING:
from .receiver import Receiver
log = logging.getLogger("sqlalchemy_collectd")
def _receive(receiver: "Receiver"):
while True:
try:
receiver.receive()
except Exception:
log.error("message receiver ... | 745 | 207 |
"""
Fast API application
ref: https://fastapi.tiangolo.com/
"""
import os
from socket import gethostname
from datetime import datetime
from uuid import uuid4
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def runtime_info() -> dict:
return {
"hostname": gethostname(),
"timestamp"... | 661 | 254 |
# coding:utf-8
"""
@author: smartgang
@contact: zhangxingang92@qq.com
@file: QSCrawl.py
@time: 2017/12/11 14:12
"""
# !/usr/bin/python
# -*-coding:utf-8-*-
"""
@author: smartgang
@contact: zhangxingang92@qq.com
@file: qs_crawl.py
@time: 2017/11/30 17:29
"""
import urllib
import urllib2
import re
import hashlib
imp... | 5,541 | 1,980 |
"""
View type object, wraps around existing dict/mapping (likely nested),
and provides convenient history/path access.
"""
| 123 | 31 |
import time
import os
import logging.config
from typing import Union, List
import tensorflow as tf
import skein
from tf_yarn.event import broadcast
from tf_yarn.tensorflow import experiment, keras_experiment
from tf_yarn import mlflow
from tf_yarn._task_commons import n_try, is_chief, get_task
logger = logging.getL... | 5,028 | 1,602 |
# -*- coding: utf-8 -*-
from __future__ import print_function
from utils import get_config, pytorch03_to_pytorch04
from trainer import IPMNet_Trainer
from torch.autograd import Variable
import argparse
import torchvision.utils as vutils
import sys
import torch
import os
import random
from torchvision import transforms... | 6,417 | 2,183 |
import numpy as np
from pgmpy.models import BayesianModel
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference.EliminationOrder import WeightedMinFill, MinWeight, MinNeighbors, MinFill
model = BayesianModel([('c', 'd'), ('d', 'g'), ('i', 'g'), ('i', 's'), ('s', 'j'), ('g', 'l'), ('l', 'j'), ('j', 'h'), ('... | 1,424 | 680 |
import numpy as np
from edutorch.nn import RNN
from tests.gradient_check import estimate_gradients, rel_error
def test_rnn_forward() -> None:
N, T, D, H = 2, 3, 4, 5
x = np.linspace(-0.1, 0.3, num=N * T * D).reshape(N, T, D)
model = RNN(D, H, N)
model.h0 = np.linspace(-0.3, 0.1, num=N * H).reshape(N,... | 2,111 | 1,133 |
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def dfs(node, lower, upper):
if not node:
ret... | 699 | 197 |
import framework, datetime, secret
from framework import discord
############################################################################################
# It's VERY IMPORTANT that you use @framework.data_function!
############################################################################################
@fra... | 2,035 | 471 |
import numpy as np
from .utils import expand_array
import os
import json
from pkg_resources import resource_stream, Requirement
DEFAULT_START_YEAR = 2013
class Parameters(object):
CUR_PATH = os.path.abspath(os.path.dirname(__file__))
PARAM_FILENAME = "params.json"
params_path = os.path.join(CUR_PATH, PA... | 8,036 | 2,458 |
# Copyright 2015 Mirantis 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... | 1,704 | 532 |
# Generated by Django 2.0.3 on 2018-09-05 05:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Campus', '0002_category_category_icon'),
]
operations = [
migrations.RenameField(
model_name='category',
old_name='category_... | 382 | 130 |
# Question: https://projecteuler.net/problem=40
def get_ith_digit_of(n, i):
return int(str(n)[i])
N = [10**i for i in range(7)]
i = 0
k = 1
prod = 1
lower = 1 # position of the first digit of [10**(k-1), 10**k)
upper = 9 # position of the last digit of [10**(k-1), 10**k)
for n in N:
while not (n >= lower an... | 564 | 249 |
from typing import Generator
from argparse import Namespace as Arguments
from os import path
from pathlib import Path
from .utils import ask_yes_no
from . import EXECUTION_CONTEXT, register_parser
from .argparse import ArgumentSubParser
# prefix components:
space = ' '
branch = '│ '
# pointers:
tee = '├── '
last... | 5,312 | 1,649 |
from .ParameterRules import ParameterRules
class TypeCheck(ParameterRules):
"""
TypeCheck
Implements a type checking.
Attribute
---------
allowedTypes : tuple(any type, ...)
A tuple of types to check. Check will be done by
isinstance(params, self.types)
Methods
-----... | 1,052 | 275 |
__author__ = 'tbeltramelli'
from AHomography import *
class PersonTracker(AHomography):
_input = None
_data = None
_map = None
_counter = 0
_tracking_output_path = ""
def __init__(self, video_path, map_path, tracking_data_path, tracking_output_path, homography_output_path):
self._dat... | 2,086 | 768 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Company(models.Model):
_inherit = 'res.company'
po_lead = fields.Float(string='Purchase Lead Time', required=True, default=0.0)
po_lock = fields.Selection([('edit', 'Al... | 784 | 238 |
marks=int(input("Enter your marks out of 100 = "))
if marks >=80:
print("A")
elif marks>=60:
print("B")
elif marks>=40:
print("C")
else:
print("BETTER LUCK NEXT TIME")
print("THANKS") | 199 | 83 |
from inspect import isclass
from .attrdict import AttrDict
class DefaultDict(AttrDict):
"""
DefaultDict help cover your dict with (keys, values) that was defined before.
Implement from dpsutil.attrdict.AttrDict
Example:
your_dict = DefaultDict(a=1, b=2)
your_dict.a # return: 1
... | 10,159 | 3,017 |
# Released under the MIT License. See LICENSE for details.
#
"""Music playback using OS functionality exposed through the C++ layer."""
from __future__ import annotations
import os
import random
import threading
from typing import TYPE_CHECKING
import _ba
from ba._music import MusicPlayer
if TYPE_CHECKING:
from ... | 5,196 | 1,461 |
#!/hosts/linuxhome/scarab/eva2/Programs/miniconda3/bin/python
#python3
import sys
import random
import pandas as pd
import numpy as np
from sklearn.metrics import roc_curve, roc_auc_score, auc
from multiprocessing import Process
from ROC_statistics import *
#Get ROC statistics with permutations and bootstrapping
#There... | 2,710 | 874 |
import pymorph
import numpy as np
def test_seline_len():
for angle in (0, 45, -45, 90, -90, 180):
for w in range(1,7):
assert pymorph.seline(w, angle).sum() == w
| 187 | 79 |
# -*- coding: utf-8 -*-
import pandas as pd
import re
from exchange import Exchange
class Zaif(Exchange):
"""docstring for Zaif"""
def __init__(self, f_trades, jpy):
self.trades = pd.read_csv(f_trades, parse_dates=['日時'])
self.trades['日時'] = self.trades['日時'].dt.normalize()
self.trades... | 1,494 | 478 |
import sys
import requests
from django.core.files.base import ContentFile
from django.core.management.base import BaseCommand
from pretix.base.models import Event
class Command(BaseCommand):
help = "Import data from appsmart"
def add_arguments(self, parser):
parser.add_argument('event_id', type=int... | 3,543 | 1,038 |
from sympy.core import *
def test_rational():
a = Rational(1, 5)
assert a**Rational(1, 2) == a**Rational(1, 2)
assert 2 * a**Rational(1, 2) == 2 * a**Rational(1, 2)
assert a**Rational(3, 2) == a * a**Rational(1, 2)
assert 2 * a**Rational(3, 2) == 2*a * a**Rational(1, 2)
assert a**Rational(17... | 1,302 | 604 |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 4,710 | 1,453 |
# Generated by Django 3.1.7 on 2022-03-08 15:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('experiments', '0013_auto_20211119_2336'),
]
operations = [
migrations.AddField(
model_name='exp... | 503 | 179 |
from cast.analysers import log, external_link, filter, create_link
import cast.analysers.dotnet
def link_to_table(type_, table_name):
# search all tables or views with table_name as name
tables = external_link.find_objects(table_name, filter.tables_or_views)
# the position of the link will be the po... | 1,580 | 404 |
from distutils.core import setup
setup(
name='emp-ext',
version='1.14',
py_modules=['emp_wifi', 'emp_webide', 'emp_ide', 'emp_utils'],
author='singein',
author_email='singein@outlook.com',
url='http://emp.1zlab.com',
description='EMP(Easy MicroPython) is a upy module to make things Easy on ... | 336 | 121 |
import uuid
from django.db import models
from app.util.models import BaseModel, OptionalImage
class Badge(BaseModel, OptionalImage):
id = models.UUIDField(
auto_created=True, primary_key=True, default=uuid.uuid4, serialize=False,
)
title = models.CharField(max_length=200)
description = model... | 480 | 154 |
from .hessian import FullHessian, LayerHessian
| 47 | 18 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from operator import or_ , and_
from django.core.paginator import Paginator
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.db.models import Q
from django.http import HttpResponse,... | 7,416 | 2,194 |
#---------------------------------------------------------------------------
# Name: wx/gizmos.py
# Author: Robin Dunn
#
# Created: 27-Oct-2017
# Copyright: (c) 2017-2020 by Total Control Software
# License: wxWindows License
#-----------------------------------------------------------------------... | 648 | 183 |
import spacy
class linker():
def __init__(self, text="", language="en"):
nlp = spacy.blank(language)
ruler = nlp.add_pipe("entity_ruler")
patterns = [{'label': 'ORG', 'pattern': 'BERD@NFDI', 'id': 'Q108542181'},
{"label": "ORG", "pattern": "BERD-NFDI", "id": "Q108542181... | 6,230 | 2,118 |
import fault
import aetherling.helpers.fault_helpers as fault_helpers
from aetherling.space_time import *
from aetherling.space_time.reshape_st import DefineReshape_ST
import magma as m
import json
@cache_definition
def Module_0() -> DefineCircuitKind:
class _Module_0(Circuit):
name = "top"
IO = ... | 2,197 | 893 |
import pytest
from django.test import RequestFactory
from osf_tests.factories import (
AuthUserFactory,
RegistrationProviderFactory,
)
from osf.models import RegistrationProvider
from admin_tests.utilities import setup_view, setup_form_view
from admin.registration_providers import views
from admin.registratio... | 2,893 | 834 |
# -*- coding: utf-8 -*-
"""Top-level package for real-robots."""
__author__ = """S.P. Mohanty"""
__email__ = 'mohanty@aicrowd.com'
__version__ = '0.1.13'
import os
from gym.envs.registration import register
from .evaluate import evaluate # noqa F401
register(
id='REALRobot-v0',
entry_point='real_robots.en... | 1,546 | 509 |
from ..parallel import parallel
def identity(item, input_set=None, remove=False):
if input_set is not None:
assert item in input_set
if remove:
input_set.remove(item)
return item
class TestParallel(object):
def test_basic(self):
in_set = set(range(10))
with pa... | 762 | 228 |
import tensorflow as tf
from tensorflow import keras
from tensorflow.python.keras.layers.ops import core as core_ops
from tensorflow.python.ops import nn
class EWBase(keras.layers.Layer):
"""
t is called the temperature in the paper. The higher t is, the more the weights are squeezed
when exponential weig... | 3,311 | 1,011 |
import hashlib
def part_one(door_id):
print('Starting part one...')
password = ['_'] * 8
index = 0
for i in range(len(password)):
print(' [%7d] Password so far: %s' % (index, ''.join(password)))
h = hashlib.md5((door_id + str(index)).encode('utf-8')).hexdigest()
index += 1
... | 1,274 | 483 |
import subprocess
import os
def Diff(li1, li2):
#Returns the files that are not contained in both lists (the symmetric difference of the lists)
li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]
return li_dif
def pcv(overwrite,src,dest):
print("Shading files")
print("")
... | 2,027 | 626 |
import os
import random
import numpy as np
import pandas as pd
import scanpy as sc
from tqdm import tqdm
from multiprocessing import Pool, RLock
class Sampling:
def sample(self, ncells=10000, pop_fp=None, sim_fp=None, cache=True, return_data=False):
print (f"Simulation: {self.network_name} Sampling Ce... | 7,914 | 2,683 |