code stringlengths 1 199k |
|---|
import unittest
import numpy
import echidna.core.spectra as spectra
import echidna.limit.limit_setting as limit_setting
import echidna.limit.limit_config as limit_config
import echidna.limit.chi_squared as chi_squared
from echidna.errors.custom_errors import CompatibilityError
class TestLimitSetting(unittest.TestCase):... |
import time
import numpy as np
from pycqed.measurement import detector_functions as det
from pycqed.measurement import sweep_functions as swf
from pycqed.analysis import analysis_toolbox as atools
from pycqed.analysis import analysis_toolbox as a_tools # FIXME
from pycqed.instrument_drivers.pq_parameters import Instru... |
from .models import Category, System, App, Version, Patch
from rest_framework import viewsets, permissions, status as HTTPStatus
from .serializers import CategorySerializer, SystemSerializer, AppSerializer
from .serializers import VersionSerializer, PatchSerializer
from rest_framework import filters
from django.http im... |
import pytest
from storage.structures import Tree
@pytest.fixture
def sample_tree():
return Tree(
name="Mladá fronta",
sub_trees=[
Tree(
name="2015",
sub_trees=[],
sub_publications=[
"first",
"second"... |
"""Test intersperse."""
import WrightTools as wt
def test_abcd():
lis = ["a", "b", "c", "d"]
assert wt.kit.intersperse(lis, "blaise") == ["a", "blaise", "b", "blaise", "c", "blaise", "d"]
def test_empty():
assert wt.kit.intersperse([], "blaise") == []
def test_1():
assert wt.kit.intersperse(["sprout"], ... |
import sys
import socket
import threading, queue
import ssl
clients = {}
lock = threading.Lock()
def parse_recvd_data(data):
""" Break up raw received data into messages, delimited
by null byte """
parts = data.split(b'\0')
msgs = parts[:-1]
rest = parts[-1]
return (msgs, rest)
def recv_msg(sock, data=byt... |
import gc
import os
import random
import shutil
import numpy as np
import torch
import tqdm
from examples.textless_nlp.gslm.speech2unit.pretrained.cpc_feature_reader import (
CpcFeatureReader,
)
from examples.textless_nlp.gslm.speech2unit.pretrained.hubert_feature_reader import (
HubertFeatureReader,
)
from exa... |
import paver
from paver.easy import *
import paver.setuputils
paver.setuputils.install_distutils_tasks()
import os, sys
import datetime
from sphinxcontrib import paverutils
sys.path.append(os.getcwd())
project_name = 'cs42'
master_url = 'http://42cs.github.io'
master_app = 'book'
options(
sphinx = Bunch(docroot="."... |
from __future__ import print_function
import serial
import argparse
import logging
def remove_crud(string):
"""Return string without useless information.
Return string with trailing zeros after a decimal place, trailing
decimal points, and leading and trailing spaces removed.
"""
if "." in string... |
from .pelican_image_optimizer import * |
"""Chapter 7 Practice Question 1
Encrypt the following with the transposition cipher (with paper and pencil, *cough*).
Note:
Contains spoilers for Chapter 9 (importing transpositionEncrypt)
"""
from pythontutorials.books.CrackingCodes.Ch07.transpositionEncrypt import encryptMessage
def main():
key = 9
messa... |
'''
Plots a histogram showing the durations of the sound sampled.
This script was written to verify that the vast majority of sound samples
was exactly 4s of length (>95%).
@date 2017-05-19
'''
import wave
import contextlib
import sys
import os
from os import listdir
from os.path import isfile, isdir, join
import matpl... |
'''
Function: find_item_in_list
Input: item_to_find (variable), item_list (list)
Output: Index of item in list, or -1 if the item is not in the list
'''
def find_item_in_list(item_to_find, item_list):
#Iterate through list
for i in range(len(item_list)):
#Check if current item is what we are looking for
if ... |
'''
The kana constants are defined here. This includes all hiragana and katakana
characters (as defined in several sets based on their processing needs),
as well as punctuation and other special characters, and their rōmaji
equivalents.
Additionally, read the comments in this file for information on what these
characte... |
"""
try.py
author: erich@emfeld.com
========================
This file acts as the test server.
WARNING!
This server is not for production usage it is only intended
as a testing server. Please use gunicorn or tornado webserver.
Please refer to yard help for more info.
"""
from app import app
from config import SERVER_P... |
from cStringIO import StringIO
try:
from PIL import Image, ImageFile, ImageDraw
except ImportError:
import Image, ImageFile, ImageDraw
from sorl.thumbnail.engines.pil_engine import Engine
def my_get_raw_data(self, image, format_, quality, progressive=False):
ImageFile.MAXBLOCK = 1024 * 1024 * 10
buf = S... |
"""
Created on Thu Oct 16 13:13:31 2014
Author: Oren Freifeld
Email: freifeld@csail.mit.edu
"""
import numpy as np
from of.utils import *
from numpy.random import multivariate_normal as draw_from_mvnormal
AND = np.logical_and
OR = np.logical_or
class Proposal(object):
def __init__(self,ms,msp,level,scale=0.01,use_l... |
import common
import stream
import decoding
import encoding
def load(fd, transform=(lambda tag, ident, contents: (tag, ident, contents))):
rd = stream.ReadStream(fd, transform)
return decoding.file(rd)
def dump(contents, fd, transform=(lambda x: x)):
wr = stream.WriteStream(fd, transform)
encoding.file(... |
import os, sys, re, setuptools
from setuptools import setup, find_packages
if sys.hexversion < 0x02070000:
raise RuntimeError('This package requires python 2.7 or better')
heredir = os.path.abspath(os.path.dirname(__file__))
def read(*parts, **kw):
try: return open(os.path.join(heredir, *parts)).read()
except:... |
import os
try:
from UserDict import IterableUserDict as UserDict
except ImportError:
from collections import UserDict
def isenvvar(name):
root, name = os.path.split(name)
return "=" not in name
class _EmptyFile(Exception):
pass
try:
FileNotFoundError
except NameError: # <python3
FileNotFoun... |
__copyright__ = "Copyright (C) 2007,2010 Andreas Kloeckner"
__license__ = """
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, co... |
from datetime import datetime
import sys
import util
from util import profiler, print_error
import ecdsa
import hashlib
ALGO_RSA_SHA1 = '1.2.840.113549.1.1.5'
ALGO_RSA_SHA256 = '1.2.840.113549.1.1.11'
ALGO_RSA_SHA384 = '1.2.840.113549.1.1.12'
ALGO_RSA_SHA512 = '1.2.840.113549.1.1.13'
ALGO_ECDSA_SHA256 = '1.2.840.1004... |
from pynode import Bridge
class EchoWorker(Bridge):
def __init__(self):
super(EchoWorker, self).__init__()
# Register for the echo event
self.on('echo', self.handleEcho)
def handleEcho(self, data):
print "[python] Got:", repr(data)
self.emit('echo', data)
worker = EchoWor... |
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in")) |
from gurobipy import *
import math, sys, os, copy
import readFiles, globalVAR
import time
def print_actions():
print "\n*** ACTION DESCRIPTIONS ***"
for action in globalVAR.listOfActions_robot:
print "\nAction Name: " + action[0]
print "preconditions: " + str(action[1])
print "add effect... |
from enum import Enum
class Gender(Enum):
Unexpressed = 0
Feminine = 1
Masculine = 2
Neuter = 3 |
from django import template
from ..search import search_registry
register = template.Library()
@register.inclusion_tag('helper/search/search_list.html', takes_context=True)
def render_search_list(context, current, num_results=None, query=''):
searches = search_registry.get_searches(context['request'])
return {
... |
from django import template
from django.conf import settings
from urllib.parse import urlparse
register = template.Library()
@register.simple_tag()
def YATSServer():
if hasattr(settings, 'SSO_SERVER'):
parts = list(urlparse.urlsplit(settings.SSO_SERVER))
parts[2] = ''
return urlparse.urlunsp... |
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.models import Permission, Group
def add_permissions(apps, schema_editor, with_create_permissions=True):
teachers = Group.objects.get(name='teachers')
students = Group.objects.get(name='students')
try:
c... |
import acechat.server
import websockets
import asyncio
import logging
logging.basicConfig(level=logging.INFO)
wslogger = logging.getLogger('websockets.server')
wslogger.setLevel(logging.INFO)
wslogger.addHandler(logging.StreamHandler())
addr = "localhost"
port = 9090
if __name__ == "__main__":
serv = acechat.Server... |
from re import compile as re
def topic_partition_metric(match):
return {
'name': match.group(3),
'labels': {
'topic': match.group(1),
'partition': match.group(2)
}
}
def store_metric(match):
return {
'name': match.group(2),
'labels': {
... |
import tornado
import tornadis
@tornado.gen.coroutine
def ping_redis(num):
with (yield pool.connected_client()) as client:
if not isinstance(client, tornadis.TornadisException):
# client is a connected tornadis.Client instance
# it will be automatically released to the pool thanks to... |
from __future__ import print_function
from logging import getLogger, ERROR
from textwrap import dedent
from unittest import TestCase
from warnings import catch_warnings
from testfixtures.shouldraise import ShouldAssert
from testfixtures.mock import Mock
from testfixtures import Replacer, LogCapture, compare, Replace
ro... |
"""
Train overcomplete ICA on van Hateren image patches.
"""
import sys
sys.path.append('./code')
from models import ISA, MoGaussian, StackedModel, ConcatModel, Distribution
from tools import preprocess, Experiment, mapp, imsave, imformat, stitch
from transforms import LinearTransform, WhiteningTransform
from numpy imp... |
from neo.Utils.WalletFixtureTestCase import WalletFixtureTestCase
from neo.Implementations.Wallets.peewee.UserWallet import UserWallet
from neo.Core.Blockchain import Blockchain
from neocore.UInt160 import UInt160
from neo.Prompt.Commands.Send import construct_and_send
from neo.Prompt.Commands.Wallet import ImportToken... |
import _plotly_utils.basevalidators
class HovertemplateValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="hovertemplate", parent_name="surface", **kwargs):
super(HovertemplateValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_... |
import threading
from amp_tools.settings import settings
__version__ = '0.2.2'
_local = threading.local()
def set_amp_detect(is_amp_detect=False, request=None):
request = request or getattr(_local, 'request', None)
if request:
request.is_amp_detect = is_amp_detect
_local.is_amp_detect = is_amp_detec... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.IN)
start = time.time()
stop = time.time()
gateState = False
mid = 0
try:
while True:
# gateState is True if sensor is tripped
if (GPIO.input(4) != gateState):
gateState = not gat... |
from __future__ import unicode_literals
import os
import py
import shutil
import task
files_dir = py.path.local(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'Test', 'files'))
def test_input_empty(tmpdir):
input_dir = tmpdir.join('0')
os.makedirs('%s' % input_dir)
output_dir = tmpdir.join('1... |
from django.db import models
class Lawmaker(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
party = models.CharField(max_length=1)
position = models.CharField(max_length=20)
member_id = models.IntegerField(default=0, help_text='ID assigned by ncleg.net.')
headshot = mo... |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HContractUnitR02_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HContractUnitR02_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_compile... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
import logging
import mimetypes
import rarfile
from ..filesystem import Item
from ..plugin import ProcessorBase
logger = logging.getLogger(__name__)
POTENTIAL_RAR_ENDARC_SIZE = 20
class RarProcessor(ProcessorBase, dict):
plugin_name = 'rar'
def __init__(self, filesystem, entry_item, lazy=False):
self.fi... |
from setuptools import setup, find_packages
version = '0.0.1'
setup(
name='StockAdvisor',
version=version,
description='This application is used to get latest Stock price from the RealTime APIs',
author='Tushar Niras, ',
author_email='tnniras@gmail.com',
url='https://github.com/tnniras/StockAdvi... |
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="family", parent_name="treemap.hoverlabel.font", **kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_nam... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0002_auto_20170119_1605'),
]
operations = [
migrations.AddField(
model_name='product',
name='current_supply',
... |
import pytest
from decouple import strtobool
@pytest.mark.parametrize("value", ("Y", "YES", "T", "TRUE", "ON", "1"))
def test_true_values(value):
assert strtobool(value)
@pytest.mark.parametrize("value", ("N", "NO", "F", "FALSE", "OFF", "0"))
def test_false_values(value):
assert strtobool(value) is False
def te... |
"""
问题描述:给定一个整型数组arr,其中只有一个数出现了奇数次,其它的数都出现了偶数次,
打印这个数。
进阶:有两个数出现了奇数次,其他的数都出现了偶数次,打印这两个数。
要求:
时间复杂度为O(N),额外空间复杂度为O(1).
"""
class OddFinder:
@classmethod
def find_one_odd(cls, arr):
flag = 0
for i in arr:
flag ^= i
return flag
@classmethod
def find_two_odd(cls, arr):
... |
import socket
HOST, PORT = '', 8888
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print('Serving HTTP on port {} ...'.format(PORT))
while True:
client_connection, client_a... |
import bpy
from bpy.types import NodeSocket, Node
from ...util import asUpdate
from ..materials import AppleseedMatLayerProps
from . import AppleseedNode, AppleseedSocket
class AppleseedSpecBRDFReflectanceSocket(NodeSocket, AppleseedSocket):
bl_idname = "AppleseedSpecBRDFReflectance"
bl_label = "Reflectance"
... |
class OutputPanel:
def __init__(self, window, name, *, clear=True, show=True):
self.window = window
self.name = name
self.view = (
self.window.find_output_panel(self.name) or
self.window.create_output_panel(self.name)
)
if clear: self.clear()
... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0026_auto_20170305_1504'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='height',
),
... |
from django.contrib import admin
from django.db.models.base import ModelBase
from django.core.urlresolvers import resolve
class AppLabelRenamer(object):
"""
Rename app label and app breadcrumbs in admin
"""
def __init__(self, native_app_label, app_label):
self.native_app_label = native_app_label... |
import sys
import os
from subprocess import *
if len(sys.argv) <= 1:
print('Usage: {0} training_file [testing_file]'.format(sys.argv[0]))
raise SystemExit
libsvm_path="libsvm-3.17"
is_win32 = (sys.platform == 'win32')
if not is_win32:
svmscale_exe = libsvm_path + "/svm-scale"
svmtrain_exe = libsvm_path + "/sv... |
from django.apps import AppConfig
class SessionConfig(AppConfig):
name = 'Session' |
"""
helloworld.py
Author: Anoushka Alavilli
Credit: Sarah Dunbar, Mr. Dennison
Assignment:
Write and submit a Python program that prints the following:
Hello, world!
"""
print ("Hello, world!") |
import datetime
from dateutil.relativedelta import relativedelta
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.db import transaction, DatabaseError
from django.db.models import Sum, Q
from djang... |
from pisces.spkilib import spki, sexp
class SecurityError(RuntimeError):
pass
class Verifier:
VERBOSE = 0
def __init__(self, acl, keys, verbose=None):
self.acl = acl
self.keys = keys
if verbose:
self.VERBOSE = 1
def verify(self, prin, perm, delegate=0):
"""Find a valid certificate chain from AC... |
"""
Wrappers for Member objects (Users with guilds).
.. currentmodule:: curious.dataclasses.member
"""
import collections
import datetime
from typing import List
from curious.dataclasses import guild as dt_guild, role as dt_role, user as dt_user, \
voice_state as dt_vs
from curious.dataclasses.bases import Dataclas... |
""" A workflow that contains cyclic graphs. Note that a special solver is
required to converge this workflow in order to execute it. """
import networkx as nx
from networkx.algorithms.components import strongly_connected_components
from numpy import ndarray, hstack, array, empty, arange, ones
from openmdao.main.array_h... |
"""@ package BasePhysics
All Physics setups and builders
"""
import logging as log
from panda3d.bullet import BulletCharacterControllerNode
from panda3d.bullet import BulletCapsuleShape
from panda3d.bullet import BulletPlaneShape
from panda3d.bullet import BulletRigidBodyNode
from panda3d.bullet import BulletTriangleMe... |
import unittest
from proj_1.bool_re.parser import CommandParser
from proj_1.bool_re.token import TokenParser
from proj_1.iitable.iitable import fetch_iitable
from collections import deque
from proj_1.bool_re.errors import CommandSyntaxError
class TestParser(unittest.TestCase):
'''Test the CommandParser class.
'... |
'''
Author: Bu Kun
E-mail: bukun@osgeo.cn
CopyRight: http://www.yunsuan.org
'''
from torlite.core import tools
from torlite.model.core_tab import CabPostHist
class MPostHist():
def __init__(self):
try:
CabPostHist.create_table()
except:
pass
def insert_data(self, raw_data... |
import unittest
import numpy
from molml.atom import Shell, LocalEncodedBond, LocalCoulombMatrix
from molml.atom import LocalEncodedAngle
from molml.atom import BehlerParrinello
from molml.constants import UNKNOWN
from .constants import METHANE, BIG, MID, ALL_DATA
BASE_SHELL = numpy.array([
[[1, 0, 0, 0], [0, 1, 0, ... |
import argparse
from astropy.io import fits
import numpy as np
import astropy.table
parser = argparse.ArgumentParser(description="An astropy snippet")
parser.add_argument("filearg", nargs=1, metavar="FILE", help="the output FITS file")
args = parser.parse_args()
file_path = args.filearg[0]
table = astropy.table.Table(n... |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future_builtins import *
import functools
import random
from PyQt4.QtCore import (QByteArray, QDataStream, QFile, QFileInfo,
QIODevice, QPoint, QPointF, QRectF, QString, Qt, SIGNAL, QEvent)
from Py... |
from elasticsearch.exceptions import NotFoundError
from tests import TestElasticmock, INDEX_NAME, DOC_TYPE, BODY
class TestDelete(TestElasticmock):
def test_should_raise_exception_when_delete_nonindexed_document(self):
with self.assertRaises(NotFoundError):
self.es.delete(index=INDEX_NAME, doc_t... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.utils.translation import ugettext_lazy... |
from setuptools import setup
import birthday
setup(
name='birthday',
version=birthday.__version__,
description='Base code for Birthday Greetings kata',
author_email='kevin@bigkevmcd.com',
author='Kevin McDermott',
classifiers=[],
license='MIT',
tests_require=['mock'],
packages=['birt... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('job', '0002_auto_20150307_1805'),
]
operations = [
migrations.AlterUniqueTogether(
name='job',
unique_together=set([('project', '... |
from django.urls import include, path
from django.contrib.auth.decorators import login_required
from .views import mage_login, get_events, get_all_users, get_observations, get_icon, get_attachment, get_event_users
urlpatterns = [
path('api/events/', get_events, name='get-events'),
path('api/users/', get_all_use... |
from PyCIP.ENIPModule.ENIP import ENIP_Originator, parse_list_identity
import PyCIP.ENIPModule.ENIPDataStructures |
from setuptools import setup, find_packages
setup(
name='poie',
version='0.1a',
description='Poisson Image Editing',
author='Απόλλων',
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended A... |
from libs.auth.auth import *
from core.union import route, reg_tpl_global
route( 'GET' , '/oauth_vk', oauth_vk, 'oauth_vk' )
route( 'GET' , '/oauth_fb', oauth_fb, 'oauth_fb' )
route( 'GET' , '/oauth_ok', oauth_ok, 'oauth_ok' )
route( 'GET' , '/oauth_tw', oauth_tw, 'oauth_... |
"""Define dictionary with auxiliary variables.
"""
from collections import OrderedDict
aux_dict = OrderedDict()
aux_dict['data_aux_geo_interpolated.nc'] = [
'orog',
'station_alt',
'station_lat',
'station_lon',
]
aux_dict['data_aux_pl500_interpolated_00UTC.nc'] = [
'u_pl500_fc',
'v_pl500_fc',
... |
from __future__ import print_function
import re
from subprocess import check_output, CalledProcessError
import sys
import os.path
import sqlite3
class Flyover:
TRANSLATIONS = {
"JB": "JBU",
}
flight_number_re = re.compile("^([A-Z]+)?(\d+)$")
@classmethod
def where(self, options, flight_number, delta_altit... |
from spotdl.authorize.authorize_base import AuthorizeBase
from spotdl.authorize.exceptions import AuthorizationError
from spotdl.authorize.exceptions import SpotifyAuthorizationError
from spotdl.authorize.exceptions import YouTubeAuthorizationError |
import Point
import random
n = 10
A = [Point.Point(random.randint(0,10), random.randint(0,10)) for f in range(n)]
def Closest(A):
minDistance = float("inf")
closestPair = None
for i in range(0, len(A)-1):
for j in range(i+1, len(A)):
p = A[i]
q = A[j]
if p.distanc... |
from django.db import models
from django.urls import reverse
class Tag(models.Model):
tag = models.SlugField(unique=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.tag
def get_absolute_url(self):
return reverse("tags:related", kwargs={"slug": self.tag}) |
import time, re, six, threading, logging, sys, json
from six.moves import _thread
from websocket._exceptions import WebSocketConnectionClosedException, WebSocketTimeoutException
from mattermost_bot.bot import Bot, PluginsManager
from mattermost_bot.mattermost import MattermostClient
from mattermost_bot.dispatcher impor... |
from uuid import uuid4
from django.db.models import CharField, UUIDField, DateTimeField, Model
class BaseModel(Model):
id = UUIDField(primary_key=True, default=uuid4, editable=False)
created_at = DateTimeField(auto_now_add=True, editable=False)
updated_at = DateTimeField(auto_now=True, editable=False)
s... |
import argparse
import os
import sys
import numpy as np
from PIL import Image
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import Variable
from chainer import serializers
from chainer import training
from chainer.training import extensions
from net import Generator, Discriminator
... |
import requests
class slack_instance():
SLACK_API_LOCATION = "https://slack.com/api/"
SLACK_API_MESSAGE = "chat.postMessage"
SLACK_API_FILES = "files.upload"
def __init__(self, token, channel):
self.token = token
self.channel = channel
def post_message(self, text):
""" Post a... |
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
"""app_name = 'layout'
urlpatterns = [
url(r'^$', views.home, name='home'),
]""" |
from . import Draft
from .. import TLObject, types, functions
from ... import utils
class Dialog:
"""
Custom class that encapsulates a dialog (an open "conversation" with
someone, a group or a channel) providing an abstraction to easily
access the input version/normal entity/message etc. The library wil... |
import os
from google_streetview_api import *
from time import sleep
import grequests
import requests
import json
import csv, time, cStringIO
import math
import wget
from PIL import Image
from resizeimage import resizeimage
from StringIO import StringIO
if __name__ == '__main__':
import argparse
parser = argpar... |
import numpy as np
import pandas as pd
import scipy.io.wavfile as wavfile
import os
from sklearn.linear_model import LinearRegression
from sklearn.utils.validation import check_random_state
provided_portion = 0.25
zero = [wavfile.read('Datasets/recordings/' + file)[1] for file in os.listdir('Datasets/recordings') if
... |
from flask import Blueprint
auth = Blueprint('auth', __name__)
from . import methods |
from brain import Brain
from bot import Bot
import sys
class PredHeuristicBrain(Brain):
def __init__(self, name, ninputs, nactions, **kwargs):
super().__init__(name, ninputs, nactions, **kwargs)
def think(self, inputs, memory):
return {bid: Bot.make_actions_from_label(self.think_indiv(inputs[bid... |
__author__ = 'syso'
from bitarray import bitarray
from itertools import combinations
import random
import os
def All_var(F):
all_vars = [];
for i in range(len(F)):
all_vars = all_vars + F[i];
l = set(all_vars);
return list(l);
def BFSAT(F):
all_vars = All_var(F);
res = [[],[]];
for l... |
c = get_config() # noqa: F821
c.NotebookApp.ip = "localhost"
c.NotebookApp.server_extensions = ["biokbase.narrative.handlers.narrativehandler"]
c.NotebookApp.port = 8888
c.NotebookApp.contents_manager_class = (
"biokbase.narrative.contents.kbasewsmanager.KBaseWSManager"
)
c.NotebookApp.logout_handler_class = (
... |
import sys, os
sys.path.insert(0, os.path.abspath('../../'))
sys.path.insert(0, os.path.abspath('.'))
import avalon
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
from datetime import datetime
project = u'Avalon Music Server'
cop... |
"""Test the router."""
from malt.routing import Router
import pytest
import re
def test_get_and_post():
router = Router()
def get_root():
pass
def post_root():
pass
def get_home():
pass
def get_thing(t):
pass
router.add_rule('GET', r'^/$', get_root)
router.add... |
import re
supplier_regex = r""
content_regex = r""
bill_ladding_regex = r'BO[LI]-[0-9]+'
shipping_line_regex =r'[Cc]arrier[\s+]?[Nn]ame[\s+]?[.]+[\s+]?:[\s+].*[\s+]?[\n+]?Truck[\s+]?No:'
container_regex = r'[Cc]ontainer number[\s+]?[.]:[\s+]?[A-Z]+[\s+]?[0-9]+-[0-9]'
product_number_regex = r'P0[\s+]?#[\s+]?[0-9]+'
invo... |
import unittest
from example import main_1
from example import main_2
from example import main_3
from example import main_4
class TestExample(unittest.TestCase):
def test_example_add(self):
self.assertEqual(main_1(), 3)
def test_example_multiply(self):
self.assertEqual(main_2(), 56)
def test... |
from django.conf.urls import url
from django.conf.urls import include, url
from django.contrib import admin
from gear import views
urlpatterns = [
url(r'^gear/', include('gear.urls', namespace="gear")),
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
url(r'^passwordreset/', includ... |
"""
Base application class.
"""
import ConfigParser
from zope.interface import implements
from twisted.internet import defer
from fmspy.application.room import Room
from fmspy.application.interfaces import IApplication
from fmspy.config import config
class Application(object):
"""
Base FMSPy application.
@i... |
"""Test spending coinbase transactions.
The coinbase transaction in block N can appear in block
N+100... so is valid in the mempool when the best block
height is N+99.
This test makes sure coinbase spends that will be mature
in the next block are accepted into the memory pool,
but less mature coinbase spends are NOT.
"... |
"""
Author: Jon Ander Gomez Adrian (jon@dsic.upv.es, http://personales.upv.es/jon)
Version: 2.0
Date: October 2016
Universitat Politecnica de Valencia
Technical University of Valencia TU.VLC
"""
import sys
import numpy
from sklearn import metrics
class MyKernel:
"""
This class implements a K... |
"""Module to implement ORM for the experimental portion of the OME database"""
from cobradb.base import (Base, DataSource, Session)
from cobradb.util import get_or_create
from sqlalchemy.orm import relationship
from sqlalchemy import (Table, Column, Integer, String, Float, ForeignKey)
from sqlalchemy.schema import Uniq... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.