code stringlengths 1 199k |
|---|
from brief_expander import *
from graphic_expander import *
from game_structures import *
from win_init import *
line = [0]*(30)
blank = []
for i in range(0, x):
blank.append(line)
blankimg = Frame(Img(blank, (0, 128)))
class Frame:
def __init__(self, image, x, y):
self.image = image
self.x = x
self.y = y
class... |
import os
from glob import glob
from mysite.version import get_git_version
from fabric.api import env
version = env.get('tag', 'latest')
if version == 'latest':
version = get_git_version()
def get_build_files():
return glob('dist/*-%s*' % version)
environment = env.get('environment', 'vagrant')
if environment =... |
"""Test block processing."""
import copy
import struct
import time
from test_framework.blocktools import (
create_block,
create_coinbase,
create_tx_with_script,
get_legacy_sigopcount_block,
MAX_BLOCK_SIGOPS,
)
from test_framework.key import ECKey
from test_framework.messages import (
CBlock,
... |
DB_NAME = 'boots'
DB_USER = 'root'
DB_PASSWORD = 'root'
DB_MASTER = 'localhost'
DB_SLAVE = 'localhost'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': DB_NAME,
'USER': DB_USER,
'PASSWORD': DB_PASSWORD,
'HOST': DB_MASTER,
'PORT': '3306',
... |
from revscoring.languages import greek
from . import enwiki, mediawiki, wikipedia, wikitext
badwords = [
greek.badwords.revision.diff.match_delta_sum,
greek.badwords.revision.diff.match_delta_increase,
greek.badwords.revision.diff.match_delta_decrease,
greek.badwords.revision.diff.match_prop_delta_sum,
... |
try:
from ._models_py3 import ARecord
from ._models_py3 import AaaaRecord
from ._models_py3 import CloudErrorBody
from ._models_py3 import CnameRecord
from ._models_py3 import MxRecord
from ._models_py3 import PrivateZone
from ._models_py3 import PrivateZoneListResult
from ._models_py3 i... |
import datetime
from pymongo import MongoClient, ReadPreference
from pymongo.errors import BulkWriteError
from bson.objectid import ObjectId
from bson.code import Code
class MongoCollectionError(Exception):
"Exceptions for MongoCollection class"
def __init__(self, msg):
"""
Initializes excep... |
"""
Created on Wed Jan 13 23:24:38 2016
Defines a trip object for the a specific trip
@author: Rupak Chakraborty
"""
class Trip():
gift_list = list([])
def __init__(self,gift_list,trip_cost):
self.gift_list = gift_list
self.trip_cost = trip_cost; |
import subprocess
from parameters.type_checks import is_file_o
from parameters.parameters import Parameters
from commons.types import *
import os
class Job:
"""
Object Job stores information about a tool and implement methods to
work with a tool.
"""
def __init__(self, tool, module, parameters=None,... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Band',
fields=[
('id', m... |
import math
from components import swervemodule
from robotpy_ext.common_drivers import navx
from magicbot.magic_tunable import tunable
class PositionTracker:
fl_module = swervemodule.SwerveModule
fr_module = swervemodule.SwerveModule
rl_module = swervemodule.SwerveModule
rr_module = swervemodule.SwerveM... |
import codecs
from django.contrib import messages
from django.urls import reverse_lazy
from django.views.generic import FormView
import json
from matches.forms import ImportForm
from matches.models import Squad
from matches.tasks import import_squad
class ImportView(FormView):
template_name = 'import.html'
form... |
"""
barrister
~~~~~~~~~
A RPC toolkit for building lightweight reliable services. Ideal for
both static and dynamic languages.
:copyright: (c) 2012 by James Cooper.
:license: MIT, see LICENSE for more details.
"""
import unittest
from .runtime_test import RuntimeTest
from .parser_test import Pa... |
__all__ = ['filter_mutants']
from typing import Tuple, List, Tuple, Set, Type
import argparse
import logging
import json
import os
import sys
import numpy as np
import concurrent.futures
from ruamel.yaml import YAML
from ground_truth import DatabaseEntry
from compare_traces import load_file, obtain_var_names,\
simp... |
def TIncr_beh(mode, inc_out, rdy_en, rdy_buff, DELAY_BITS):
'''|
| Specify the behavior, describe data processing; there is no notion
| of clock. Access the in/out interfaces via get() and append()
| methods. The "TIncr_beh" function does not return values.
|________'''
print "Warning: Behavior ... |
from bs4 import BeautifulSoup
import re
import requests
from hmc_urllib import getHTML
from urllib.request import http
import scraping_functions as sf
def scrape_tournament(filename, url_list):
"""Scrape all the urls in a file and write the corresponding tournament's matches to a text file."""
for url in url_li... |
'''
Copyright (c) 2007 Ian Bicking and Contributors
Copyright (c) 2009 Ian Bicking, The Open Planning Project
Copyright (c) 2011-2015 The virtualenv developers
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 th... |
"""
Allows access to the bot account's watchlist.
The watchlist can be updated manually by running this script.
Syntax:
python pwb.py watchlist [-all | -new]
Command line options:
-all - Reloads watchlists for all wikis where a watchlist is already
present
-new - Load watchlists for all wik... |
import numpy as np
from shap.utils import MaskedModel
from shap import links
from shap.models import Model
from .._explainer import Explainer
class Random(Explainer):
""" Simply returns random (normally distributed) feature attributions.
This is only for benchmark comparisons. It supports both fully random attr... |
import logging
import unittest
from core.Database import Database
from core.PluginManager import PluginManager
from core.entities.Scenario import Scenario
logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] [%(asctime)s] (%(threadName)-10s) %(message)s', filename='debug.log', filemode='w')
cfg = Database(... |
"""
This script checks if a web page has changed since the last check. If the web page does not support the header
Last-Modified then it uses an MD5 hash to track changes.
"""
import hashlib
import logging
from datetime import datetime
import requests
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s -... |
from glad.lang.common.loader import BaseLoader
from glad.lang.c.loader import LOAD_OPENGL_DLL, LOAD_OPENGL_DLL_H, LOAD_OPENGL_GLAPI_H
_GLX_LOADER = \
LOAD_OPENGL_DLL % {'pre':'static', 'init':'open_gl',
'proc':'get_proc', 'terminate':'close_gl'} + '''
int gladLoadGLX(Display *dpy, int screen)... |
import lya
import os
__author__ = 'kyle.walker@zefr.com'
def get_connection_string(settings, psycopg2_format=False):
"""
Given a dictionary of current settings, form the database connection
string.
"""
engine = settings.get('engine', 'mysql')
user = settings['user']
password = settings['pass... |
from collections import namedtuple
from contextlib import contextmanager
from conans.client.loader import parse_conanfile
from conans.client.recorder.action_recorder import ActionRecorder
from conans.model.ref import ConanFileReference
from conans.model.requires import Requirement
from conans.errors import ConanExcepti... |
from test_url import * |
"""
MADDPG solution to solve MA
Based on Morvan's DDPG v1 (A/C is seperate so that MADDPG is easier to implement):
https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow/blob/master/contents/9_Deep_Deterministic_Policy_Gradient_DDPG/DDPG.py
Actually v1 has a bug where Morvan-DDPG-v2 has solve:
This al... |
"""
Pi-Dom is module to make domotic with RPi and.
With use emit from `<http://www.noopy.fr/raspberry-pi/domotique/>`_
``emit`` can communicate with Chacon 54795
"""
import time
import subprocess
import pickle
from pathlib import Path
__all__ = ['PiDom', 'event']
__version__ = "0.3.2"
__author__ = "Oprax"
__license__ =... |
from flask import Flask
from flask import jsonify
from flask import request
from flask import redirect
from flask import url_for
from flask import render_template
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient('localhost', 27017,socketKeepAlive=True)
dbwekey = client.get_database('wekeypedia... |
"""
entities.py
--------------
Basic geometric primitives which only store references to
vertex indices rather than vertices themselves.
"""
import numpy as np
from copy import deepcopy
from .arc import discretize_arc, arc_center
from .curve import discretize_bezier, discretize_bspline
from .. import util
from ..util i... |
import _plotly_utils.basevalidators
class CminValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="cmin", parent_name="surface", **kwargs):
super(CminValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type... |
from django.db import models
from django.contrib.auth import models as auth_model
from documentaries.models import Documentary
class Comment(models.Model):
user = models.ForeignKey(auth_model.User, on_delete=models.CASCADE)#required
documentary = models.ForeignKey(Documentary, on_delete=models.CASCADE)#required... |
import pandas as pd
import numpy as np
import hungarian
import math
import argparse
from multiprocessing import Pool
from scipy.stats import ks_2samp
from scipy.stats import ttest_ind
from scipy.stats import chisquare
from sklearn import linear_model
import sys
df_full = None
df_columns = None
column_parameters = {}
co... |
import numpy as np
from .constants import MASS_MAX, MASS_MIN, TIME_MAX
def rate_traj(m_f, tof, m_i=MASS_MAX, m_f_min=MASS_MIN, tof_max=TIME_MAX,
ret_criteria=False, **kwargs):
"""
Calculate the "resource savings rating" (a.k.a.: "soft min" aggregation).
Determines the extent to which the mass and time ... |
from twilio.rest import TwilioRestClient
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)
numbers = client.phone_numbers.search(
country="US", contains="510555****", type="local"
)
if numbers:
numbers[0].purchase() |
'''
Created on Apr 10, 2014
Tests for the misc_utils
@author: theoklitos
'''
import unittest
from util import misc_utils
import datetime
class TestMiscUtils(unittest.TestCase):
def test_is_within_distance(self):
assert(misc_utils.is_within_distance(10, 15, 6))
assert(misc_utils.is_within_distance(1,... |
"""
Project Euler Problem 4
=======================
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def largest_palindrome(start , end):
"""
Takes s... |
from setuptools import setup, find_packages
import unittest
import codecs
def test_suite():
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('subword_nmt/tests', pattern='test_*.py')
return test_suite
setup(
name='subword_nmt',
version='0.3.8',
description='Unsupervised Word... |
'''
Copyright 2013 Cosnita Radu Viorel
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 without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute,... |
import os
class TicTacToeBoard:
"""
Since the value for X and O is arbitrary. It behooves us to make an
effort to never hardcode these values.
"""
X = True
O = False
_ = None
_d8 = [
lambda x: TicTacToeBoard._rotation(x, 0),
lambda x: TicTacToeBoard._rotation(x, 1),
... |
import random
__author__ = 'Mushahid Khan'
from django.core.management.base import BaseCommand, CommandError
from feedback_survey.models import Course, Student, University
class Command(BaseCommand):
help = "Creating Student based on the courses"
def handle(self, *args, **options):
course_one = Course.o... |
"""
Django settings for piroute project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
BASE_D... |
import sys
from numpy import Inf
sys.path.append("../Inference")
import numpy as np
import scipy.stats
import random
import heapq
from math import exp as e
from math import pow as pow
import copy
global score, variance, worker_quality, number_of_worker
global nodes, edges, Matrix, number_of_questions, Asked_Pairs
globa... |
import ocnn
import torch
from solver import Solver, Dataset, parse_args
class ClsSolver(Solver):
def get_model(self, flags):
if flags.name.lower() == 'lenet':
model = ocnn.LeNet(flags.depth, flags.channel, flags.nout)
elif flags.name.lower() == 'resnet':
model = ocnn.ResNet(flags.depth, flags.chan... |
"""
Variable que contiene pares IP:Puerto, separados por comas.
"""
HOSTS = "192.168.56.1:27017,192.168.56.1:27018,192.168.56.1:27019" |
"""Test the zapwallettxes functionality.
- start two turbocoind nodes
- create two transactions on node 0 - one is confirmed and one is unconfirmed.
- restart node 0 and verify that both the confirmed and the unconfirmed
transactions are still available.
- restart node 0 with zapwallettxes and persistmempool, and ver... |
"""Define AirVisual constants."""
import logging
DOMAIN = "airvisual"
LOGGER = logging.getLogger(__package__)
INTEGRATION_TYPE_GEOGRAPHY_COORDS = "Geographical Location by Latitude/Longitude"
INTEGRATION_TYPE_GEOGRAPHY_NAME = "Geographical Location by Name"
INTEGRATION_TYPE_NODE_PRO = "AirVisual Node/Pro"
CONF_CITY = "... |
import os
import unittest
from flask import Flask
from tests import TEST_DIR
from flask_avro import FlaskAvroEndpoint
from flask_avro import AvroMessageNotDefined
from flask_avro.utils.test_client import FlaskAvroTestClient
AVRO_FILE = os.path.join(TEST_DIR, "avro_schema", "test_avro_schema.avpr")
class TestAvroAPIEndp... |
import sys
import datetime
import pytz
import openpyxl
from icalendar import Calendar, Event, Alarm
import jieba
def handler(file):
tz = pytz.timezone('Asia/Shanghai')
# filename = file.name
# filename = sys.argv[1]
wb = openpyxl.load_workbook(file)
ws = wb.active
title = ws['A1'].value
prin... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0007_auto_20150321_1735'),
]
operations = [
migrations.RemoveField(
model_name='author',
name='user',
),
... |
def prod(M, M2):
mat3 = [[0, 0], [0, 0]]
for i in (0, 1):
for j in (0, 1):
for k in (0, 1):
mat3[i][j] = mat3[i][j] + M[i][k] * M2[k][j]
for i in (0, 1):
for j in (0, 1):
M[i][j] = mat3[i][j] % 1000000007
def matpow(n, M):
if n > 1:
matpow(... |
from nac.common import (is_data_in_hdf5, retrieve_hdf5_data)
from nac.workflows.input_validation import process_input
from nac.workflows.workflow_coupling import workflow_derivative_couplings
from os.path import join
import numpy as np
import pkg_resources as pkg
import os
import shutil
import sys
file_path = pkg.resou... |
"""manage your dropbox configuration."""
import cmd
import keychain
import sys
from stashutils import dbutils
_stash = globals()["_stash"]
class DropboxSetupCmd(cmd.Cmd):
"""The command loop for managing the dropbox"""
intro = _stash.text_color("Welcome to the Dropbox Setup. Type 'help' for help.", "yellow")
... |
"""
Address to line converasion tool
Includes:
- Memory usage summary
- CrossScope allocation/deallocation report
- MemLeak report (Experimental)
"""
import os
import sys
import time
import getopt
import pprint
import subprocess
KNOWN_REGIONS = ["[heap]", "[stack]", "[vvar]", "[vdso]", "[vsyscall]"]
PROTOCOL_ALLOC ... |
from __future__ import with_statement
from StringIO import StringIO
import unittest
import os
import posixpath
import sys
from uuid import UUID
from dropbox import session, client, rest
import datetime
from dropbox.rest import ErrorResponse
class BaseClientTests(object):
@classmethod
def setUpClass(cls):
... |
from compiler import *
banner_scale = 0.3
avatar_scale = 0.15
map_icons = [
("player",0,"player", avatar_scale, snd.footstep_grass, 0.15, 0.173, 0),
("player_horseman",0,"player_horseman", avatar_scale, snd.gallop, 0.15, 0.173, 0),
("gray_knight",0,"knight_a", avatar_scale, snd.gallop, 0.15, 0.173, 0),
("vaegir... |
import sys
'''
The below is only needed for Bayesian Optimization on Luis' Machine.
Ignore and comment out if it causes problems.
'''
path = "/home/luis/Documents/Harvard_School_Work/Spring_2015/cs181/assignments/practicals/prac4/practical4-code/"
if path not in sys.path:
sys.path.append(path)
'''
End Bayesian
'''
... |
""" Running this script will scrape data from a radio attena database website.
The raw HTML will be stored and parsed later.
"""
import urllib2 as url
import subprocess
CURL_COMMAND = """\
curl \
-H "Host: www.fmlist.org" \
-H "Connection: keep-alive" \
-H "Accept: text/html,application/xhtml+xml,applic... |
import sys
import django
from django.apps import apps
from django.apps.config import AppConfig
from django.conf import settings
from django.db import connections, models, DEFAULT_DB_ALIAS
from django.db.models.base import ModelBase
from mock import patch
NAME = 'udjango'
def main():
setup()
class City(models.Mo... |
class MatchError(Exception):
def __init__(self, sport, teams):
self.sport = sport
self.teams = teams
def __str__(self):
return '{} match not found for {}'.format(self.sport.capitalize(), ', '.join(self.teams))
class SportError(Exception):
def __init__(self, sport):
self.sport... |
print('main.py was successfully called')
import os
print('imported os')
print('this dir is', os.path.abspath(os.curdir))
print('contents of this dir', os.listdir('./'))
import sys
print('pythonpath is', sys.path)
import kivy
print('imported kivy')
print('file is', kivy.__file__)
from kivy.app import App
from kivy.lang ... |
"""
Optional Settings:
TEST_EXCLUDE: A list of apps to exclude by default from testing
RUN_ALL_TESTS: Overrides exclude and runs all tests (default: False - which uses the TEST_EXCLUDE)
TEST_FIXTURES: A list of fixtures to load when testing.
"""
import unittest
from django.core.management import call_comman... |
from tgext.ecommerce.lib.cart import CartManager
from tgext.ecommerce.lib.category import CategoryManager
from tgext.ecommerce.lib.order import OrderManager
from tgext.ecommerce.lib.payments import paypal, null_payment
from tgext.ecommerce.lib.product import ProductManager
class ShopManager(object):
cart = CartMana... |
import ast
import sys
import os
UP = 'U'
DOWN = 'D'
LEFT = 'L'
RIGHT = 'R'
TEAM_NAME = "Improved closest v2"
allMoves = [RIGHT, RIGHT, UP, RIGHT, RIGHT, RIGHT, RIGHT, UP, UP, UP, UP, UP, RIGHT, RIGHT, UP, UP]
def debug (text) :
# Writes to the stderr channel
sys.stderr.write(str(text) + "\n")
sys.stderr.flu... |
import logging
import psycopg2
import pgpm.lib.utils
import pgpm.lib.utils.db
import pgpm.lib.version
import pgpm.lib.utils.config
import pgpm.lib.utils.vcs
class AbstractDeploymentManager(object):
"""
"Abstract" class (not intended to be called directly) that sets basic configuration and interface for classes
... |
"""
Base_Map.py
Created by amounra on 2014-7-26.
This file allows the reassignment of the controls from their default arrangement. The order is from left to right;
Buttons are Note #'s and Faders/Rotaries are Controller #'s
"""
USER_OFFSET = 10
OSC_TRANSMIT = False
OSC_OUTPORT = 7400
SHIFT_LATCHING = False
CAP_BUTTON_... |
import numpy as np
from midi import MidiSequence
from fuel.streams import DataStream
from fuel.schemes import SequentialScheme
from fuel.transformers import Padding, Mapping
def test_jsb():
jsb = MidiSequence('jsb')
print jsb.num_examples
dataset = DataStream(
jsb,
iteration... |
"""The CleverHans adversarial example library"""
from cleverhans.devtools.version import append_dev_version
__version__ = append_dev_version("3.0.1") |
from __future__ import absolute_import, unicode_literals
import numpy as np
import pickle
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout
from keras.regularizers import l1, l2, l1l2
from keras.utils.np_utils import to_categorical
from scipy.sparse import issparse
class KerasMulti... |
from collections import OrderedDict
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_countries.fields import CountryField... |
import pygame,sys
from pygame.locals import *
class MySprite(pygame.sprite.Sprite):
def __init__(self, target):
pygame.sprite.Sprite.__init__(self)
self.target_surface = target
self.image = None
self.master_image = None
self.rect = None
self.topleft = 0,0
self.frame = 0
self.old_frame = -1
self.frame... |
'''
Compute square root using gradient descent.
'''
n = 50
def J(x):
return (x * x - n)**2
def Jd(x):
return 4 * x * (x * x - n)
# e = 10**-8
# return (J(x + e) - J(x - e)) / (2 * e)
def gradient_descent(x, alpha=10**-3, iters=10**6, error=10**-4, debug=False):
if debug:
print(x, J(x))
f... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('projects.views',
#url(r'^$', 'listar'),
url(r'^login/$', 'login'),
url(r'^save/$', 'salvar'),
url(r'^new/$', 'novo'),
url(r'^ranking/$', 'ranking'),
#url(r'^search/$', 'pesquisar'),
#url(r'^view/(?P<numero>\d+)/$', '... |
from dataclasses import dataclass
from simple_parsing import ArgumentParser, field
@dataclass
class RunSettings:
"""Parameters for a run."""
# wether or not to execute in debug mode.
debug: bool = field(alias=["-d"], default=False)
# wether or not to add a lot of logging information.
verbose: bool =... |
from setuptools import setup
setup(name='tyrion',
version='0.1',
description='Word Embedding based on paper by Lebret, Collobert, 2015',
url= 'https://github.com/shashankg7/WordEmbeddingAutoencoder',
packages=['tyrion'],
install_requires=['numpy','theano'],
author=('Muktabh Mayank, S... |
import pytest
from src.search_rotated_list import find_num_rotated, search
TEST1 = [
([1, 2, 3, 4, 5], 0),
([4, 5, 1, 2, 3], 2),
([1], 0),
([4, 5, 6, 7, 1], 4),
([], 0),
([2, 1], 1)
]
TEST2 = [
([1, 2, 3, 4, 5], 3, True),
([4, 5, 1, 2, 3], 1, True),
([1], 1, True),
([4, 5, 6, 7, ... |
import config
import network
import segments as Segments
import template_generator as Templates
import deploy as Deployment
import delete as DeleteStack
def testpypi():
return "This is packaged correctly"
def configure():
return config.getconfigfile()
def get(filepath, config, segment, stage):
print Segment... |
import numpy
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
data = numpy.random.normal(size=100)
print [x for x in data]
hist, bin_edges = numpy.histogram(data, density=True)
print hist
print bin_edges
bin_centres = (bin_edges[:-1] + bin_edges[1:])/2
def gauss(x, *p):
A, mu, sigma = p
retu... |
def is_displayed(self, log=True):
"""
Return True if page object is displayed, False otherwise.
:param bool log: whether to log or not (default is True)
:returns: whether page object is displayed
:rtype: bool
"""
if log:
self.logger.info('determining whether page object {} is display... |
"""empty message
Revision ID: 36532a52722f
Revises: None
Create Date: 2015-03-13 10:32:54.566392
"""
revision = '36532a52722f'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('news',
sa.Column('id'... |
from optics import *
from quantum import *
from constants import *
__all__ = filter(lambda s:not s.startswith('_'),dir()) |
import os
import sys
from setuptools import find_packages # @UnresolvedImport
from distutils.core import setup
package_name = 'pype9'
package_dir = os.path.join(os.path.dirname(__file__), package_name)
package_data = []
prefix_len = len(package_dir) + 1
for path, dirs, files in os.walk(package_dir, topdown=True):
... |
__all__ = ['newaxis', 'ndarray', 'flatiter', 'ufunc',
'arange', 'array', 'zeros', 'empty', 'broadcast', 'dtype',
'fromstring', 'fromfile', 'frombuffer','newbuffer',
'getbuffer', 'int_asbuffer', 'where', 'argwhere',
'concatenate', 'fastCopyAndTranspose', 'lexsort',
... |
""" Exercise the random number generator functions. """
import math
import time
import unittest
from rnglib import SimpleRNG
class TestRandomFunc(unittest.TestCase):
"""
Exercise the random number generator functions.
This is not a test in the usual sense. It exercises random.Random
functions through a... |
from pycipher import Bifid
import unittest
class TestBifid(unittest.TestCase):
def test_encipher(self):
keys = (('tgcmpfyxuiewdhbzrvalknqso',5),
('ezrxdkuatgvncmiwhsqpyfblo',6))
plaintext = ('abcdefghiiklmnopqrstuvwxyzabcdefghiiklmnopqrstuvwxyz',
'abcdefghiiklmno... |
'''
Determine whether an integer is a palindrome. Do this without extra space.
'''
'''
不可以使用转换str的方法。
将自然对比转换为每次对比最左边和最右边,然后掐头去尾,就是数字除以100,
'''
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
a = x
... |
import json
from flask import Blueprint, request, session
from jsonschema import ValidationError
from sqlalchemy.exc import IntegrityError
from app.api.models import User
from app.api.utlis.auth import authenticate
from app.api.utlis.http import json_response
from app.api.utlis.validators import validate_dict_with_sche... |
"""
Try out different partition assignment algorithms on a simulation trace, and
evaluate their performance.
"""
import argparse
import cvxpy
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
from assign_partitions import AssignmentAlgorithm
def ParseArguments():
parser = argpar... |
import random
import time
import base64
import binascii
import urllib
import hashlib
import hmac
class CosAuth(object):
def __init__(self, config):
self.config = config
def app_sign(self, bucket, cos_path, expired, upload_sign=True):
appid = self.config.app_id
bucket = bucket
sec... |
from base import Event
from .ichatserver import IChatServer
class ChatServer(IChatServer):
def __init__(self, chatService):
super(ChatServer, self).__init__()
self._chatService = chatService
self._messageReceived = Event("messageReceived")
def __str__(self):
return self.__class__.__name__ + " " + str(self.id)... |
from flask_wtf import Form
from wtforms import StringField, PasswordField
from wtforms.validators import url, DataRequired
from wtforms.fields import SelectField
from wtforms.fields.html5 import URLField
class AdminLogin(Form):
login_name = StringField("User", validators=[DataRequired()])
password = PasswordFie... |
from scrapy.contrib.spiders.init import InitSpider
from scrapy.http import Request, FormRequest
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.xlib.pydispatch import dispatcher
from scrapy import signals
from scrapy.spider import Spider
... |
import numpy as np
import GPy
from GPy import kern
from GPy.core.model import Model
from GPy.core.mapping import Mapping
from GPy import likelihoods
import logging
import warnings
def my_predictive_gradient(Xnew, GPmodel, test_point, kern=None):
"""
Returns gradients of predictive mean, variance, and co... |
import mesa_reader as ms
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.ndimage
import os
__all__ = ['hrd', 'abun_plot', 'get_mat_mcenter', 'print_data']
def hrd(folder, title=' ', save=False, name=None):
'''
Function to plot the Hertzsprung-Russel diagram
Parameter
... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pip... |
"""Test serializer."""
from marshmallow import fields
from invenio_files_rest.serializer import BaseSchema, json_serializer, \
serializer_mapping
def test_serialize_pretty(app):
"""Test pretty JSON."""
class TestSchema(BaseSchema):
title = fields.Str(attribute='title')
data = {'title': 'test'}
... |
import os, sys, requests_html, json, scrapy, threading, urllib;
import xml.etree.ElementTree as ett;
class IndeedEntry:
title=None;location=None;company=None;details=None;
def __init__(self, raw):
try:
obj = ett.fromstring(raw);
self.title = obj.find('.//h2/span[@title]').text;
self.company = obj.find('.//... |
from py_524 import utils |
"""Ways to store objects."""
import pickle
import string
import os.path
from parsimony.configuration import parsimony_directory,context_name
from . import Store
class PickleStore(Store):
"""Store that uses the local file system and pickle as the underlying mechanism.
"""
def __init__(self, key, base_directo... |
import _plotly_utils.basevalidators
class IdssrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="idssrc", parent_name="waterfall", **kwargs):
super(IdssrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit... |
from django.apps import AppConfig
class PartnersConfig(AppConfig):
name = 'partners' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.