code stringlengths 1 199k |
|---|
import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
... |
import _plotly_utils.basevalidators
class TickformatValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="tickformat",
parent_name="scattercarpet.marker.colorbar",
**kwargs
):
super(TickformatValidator, self).__init__(
plotl... |
from TOSSIM import *
from sets import Set
import sys
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] filename",
version="%prog 1.0")
parser.add_option("-g", "--gainfile",
action="store",
dest="gainfile",
default="topology.txt",
help="file containing gains between simulation no... |
"""
XKCD plot generator
-------------------
Author: Jake Vanderplas
This is a script that will take any matplotlib line diagram, and convert it
to an XKCD-style plot. It will work for plots with line & text elements,
including axes labels and titles (but not axes tick labels).
The idea for this comes from work by Damo... |
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.widget import Widget
from kivy.clock import Clock
import os
import dynamixel
import sys
import subprocess
import optparse
import yaml
import cinematica
... |
from django.conf.urls import include, url
from article import views
urlpatterns = [
url(r'^$', views.articles, name='articles'),
url(r'^add/?$', views.add_articles, name='add-articles'),
] |
from __future__ import absolute_import, print_function, unicode_literals
from django.views.generic.base import TemplateView
class CoachToolsView(TemplateView):
template_name = "coach/coach.html" |
""" Log Config
"""
__author__ = 'Zagfai'
__date__ = '2018-06'
SANIC_LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format':
'%(levelname)s [%(asctime)s %(name)s:%(lineno)d] %(message)s',
'datefmt': '%y%m%d %H:... |
import os
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
import django_openS3
with open(os.path.join(os.path.dirname(__file__), "README.rst")) as file:
README = file.read()
with open(os.path.join(os.path.dirname(__file__), 'LICENSE')) as file:
LICENSE = file.read... |
from collections import Iterable
import array
list_comp = [x * x for x in range(10)]
list_gene = (x * x for x in range(10))
print(isinstance(list_gene, Iterable))
symbols = '$¢£¥€¤'
t = tuple(ord(symbol) for symbol in symbols)
print(t)
array.array('I', (ord(s) for s in symbols))
colors = ['black', 'white']
sizes = ['S'... |
from helper import greeting
greeting('Hello') |
import os,glob,platform
def makeFileName(startupDir):
files = glob.glob(os.path.join(startupDir,'*.py'))
#Make a startup filename that doesn't already exist
for i in range(10000):
if i<100:
fname = '%02d-startup.py'%i
else:
fname ='%04d-startup.py'%i
fname = o... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('content', '0004_ediimages'),
]
operations = [
migrations.AlterModelOptions(
name='ediimages',
options={'ordering': ('sort_order',... |
import importlib
from flask import render_template
import lib.es as es
def get(p):
# get data source definiton
query = 'name:{}'.format(p['nav'][3])
p['ds'] = es.list(p['host'], 'core_data', 'datasource', query)[0]
# load service
path = "web.modules.dataservice.services.{}".format(p['ds']['type'])
... |
from __future__ import print_function,division
from astropy.io import fits
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
from pint.templates import lctemplate,lcprimitives,lcfitters
from pint.eventstats import z2m,sf_z2m, hm, sf_hm, sig2sigma
import sys
from astropy import log
import scipy.stats
... |
words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
print word,
print '\n'
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print key, 'corresponds to', d[key]
for key, value in d.items():
print key, 'to', value |
from __future__ import absolute_import
import codecs
import re
import types
import sys
from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase
from .constants import encodings, ReparseException
from . import utils
from io import StringIO
try:
from io import BytesIO
except ImportError:
BytesIO ... |
from nagu import (get_color, pack_color, pack, reset,
sequence, parse_line, html)
def test_get_color():
"""
>>> assert get_color(0) == ""
>>> assert get_color(13) == "color: #ff0;"
>>> assert get_color(64) == 'background-color: #ff0;'
>>> assert get_color(13 + 64) == 'color: #ff0;background-... |
import io
import pytest
from contextlib import redirect_stdout
from mock import patch
from mythril.mythril import MythrilLevelDB, MythrilConfig
from mythril.exceptions import CriticalError
@patch("mythril.ethereum.interface.leveldb.client.EthLevelDB.search")
@patch("mythril.ethereum.interface.leveldb.client.ETH_DB", re... |
import math
import fractions
import pygame
import argparse
import os.path
import sys
import subprocess
import time
from itertools import combinations,islice
from ntracer import NTracer,Material,ImageFormat,Channel,BlockingRenderer,CUBE
from ntracer.pygame_render import PygameRenderer
ROT_SENSITIVITY = 0.005
WHEEL_INCRE... |
from growler_guys import scrape_growler_guys |
from __future__ import absolute_import
from apscheduler.jobstores.base import BaseJobStore, JobLookupError, ConflictingIdError
from apscheduler.util import datetime_to_utc_timestamp
class MemoryJobStore(BaseJobStore):
"""
Stores jobs in an array in RAM. Provides no persistence support.
Plugin alias: ``memor... |
import pygame
from pygame.locals import *
class Application:
def __init__(self, screen_size, caption="PyGame"):
pygame.init()
self.display_surface = pygame.display.set_mode(screen_size)
pygame.display.set_caption(caption)
self.is_run = False
self.update_func = self.__update_s... |
from __future__ import absolute_import
from .activation_maximization import visualize_activation_with_losses
from .activation_maximization import visualize_activation
from .saliency import visualize_saliency_with_losses
from .saliency import visualize_saliency
from .saliency import visualize_cam_with_losses
from .salie... |
"""
Package-wide constants.
"""
CALL = 'C'
PUT = 'P' |
from distutils.core import setup
setup( name='dramatis',
version='0.1.1',
author='Steven Parkes',
author_email='smparkes@smparkes.net',
url='http://dramatis.mischance.net',
description="an actor library for ruby and python",
package_dir = {'':'lib'},
packages=[
... |
import cgi
from redis import Connection
from socket import gethostname
from navi import *
fields = cgi.FieldStorage()
title = "Message Box"
msg_prefix = 'custom.message.'
def insert_msg(cust, tm, msg):
conn = Connection(host=gethostname(),port=6379)
conn.send_command('set', msg_prefix+cust+'--'+tm, msg)
con... |
from __future__ import division, absolute_import
import os
import sys
from textwrap import dedent
from twisted.trial import unittest
from twisted.persisted import sob
from twisted.python import components
from twisted.persisted.styles import Ephemeral
class Dummy(components.Componentized):
pass
objects = [
1,
"hell... |
from os.path import abspath
from flask import current_app
from flask.ext.script import Manager
from flask.ext.assets import ManageAssets
from flask.ext.migrate import Migrate, MigrateCommand
from bluespot import create_app
from bluespot.extensions import db
app = create_app(mode='development')
manager = Manager(app)
ma... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import re
from io import StringIO
from .strings import escape
EMBEDDED_NEWLINE_MATCHER = re.compile(r'[^\n]\n+[^\n]')
class PoFile(object):
def __init__(self):
self.header_fields = []
... |
import sys
try:
data = map(int, sys.stdin.readline().split())
except ValueError:
sys.stdout.write("NO" + '\n')
exit()
if not data:
sys.stdout.write("NO" + '\n')
exit()
if len(data) != 2:
sys.stdout.write("NO" + '\n')
exit()
if data[0] < 1 or data[0] > 1000:
sys.stdout.write("NO" + '\n')
... |
"""alerts.py Classes for sendings alerts
"""
__author__ = "Jean-Martin Archer"
__copyright__ = "Copyright 2013, MIT License."
import smtplib
from twilio.rest import TwilioRestClient
from vendors.pushbullet.pushbullet import PushBullet
import configuration
class Alerts(object):
"""<ac:image ac:thumbnail="true" ac:wi... |
from flask import Flask
from flask.views import http_method_funcs
from .auth import secure
from .config import config_autoapi
from .messages import message
from .operations import invalid_operation, login, logout, password, roles, user
from .views import get, post, delete, put, patch
class AutoApi(Flask):
def __ini... |
from django.db import models
from django.contrib.auth.models import User
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self, ... |
from .viewsets import *
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'person', PersonViewSet)
router.register(r'skill', SkillViewSet)
router.register(r'mycontent', MyContentViewSet)
router.register(r'job', JobViewSet)
router.register(r'course', CourseViewSet)
router.register(r'po... |
from __future__ import print_function
import argparse
import os
import sys
import pokedex.cli.search
import pokedex.db
import pokedex.db.load
import pokedex.db.tables
import pokedex.lookup
from pokedex import defaults
def main(junk, *argv):
if len(argv) <= 0:
command_help()
return
parser = creat... |
from django.apps import AppConfig
class ScrapperConfig(AppConfig):
name = 'scrapper' |
from setuptools import setup, find_packages
setup(
name = "FreeCite",
version = "0.1",
py_modules = ['freecite'],
#install requirements
install_requires = [
'requests==1.1.0'
],
#author details
author = "James Ravenscroft",
author_email = "ravenscroftj@gmail.com",
des... |
from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
('', include('imago.urls')),
url(r'^report/(?P<module_name>[a-z0-9_]+)/$', 'reports.views.report', name='report'),
url(r'^represent/(?P<module_name>[a-z0-9_]+)/$', 'reports.views.represent', name='represent'),
url(r'^warnings... |
from tfs import *
from pylab import *
from numpy import *
import glob, os
import nibabel as nib
matplotlib.interactive(True)
session = tf.InteractiveSession()
dataPath = './corpusCallosum/'
def computePad(dims,depth):
y1=y2=x1=x2=0;
y,x = [numpy.ceil(dims[i]/float(2**depth)) * (2**depth) for i in range(-2,0)]
x = fl... |
import _plotly_utils.basevalidators
class TicklenValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="ticklen", parent_name="treemap.marker.colorbar", **kwargs
):
super(TicklenValidator, self).__init__(
plotly_name=plotly_name,
parent_... |
from django.core import serializers
from django.http import HttpResponse, JsonResponse
from Assessment.models import *
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_GET
import json
@csrf_exempt
@require_GET
def getAssignmentByCode(request):
respo... |
instr = [x.strip().split(' ') for x in open("input/dec25").readlines()]
skip = {}
modified = {}
"""instr[10] = ['add', 'a', 'b'] # adds b to a, sets b to 0
skip[11] = True
skip[12] = True"""
def print_program(inss):
i = 0
for inst in inss:
prefix = ' # ' if i in skip else ' '
print(prefix, i,... |
import enum
from typing import Dict, Optional, Set
@enum.unique
class MediaTag(enum.IntEnum):
# ndb keys are based on these! Don't change!
CHAIRMANS_VIDEO = 0
CHAIRMANS_PRESENTATION = 1
CHAIRMANS_ESSAY = 2
MEDIA_TAGS: Set[MediaTag] = {t for t in MediaTag}
TAG_NAMES: Dict[MediaTag, str] = {
MediaTag.... |
from django.template import Library
register = Library()
@register.simple_tag(takes_context=True)
def assign(context, **kwargs):
"""
Usage:
{% assign hello="Hello Django" %}
"""
for key, value in kwargs.items():
context[key] = value
return ''
@register.filter
def get(content, key):
"... |
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import start_nodes
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framew... |
import reprlib
print(reprlib.repr(set('supercalifragilisticexpialidocious')))
import pprint
t = [[[['black','cyan'],'white',['green','red']],[['magenta','yellow'],'blue']]]
pprint.pprint(t, width=30)
print()
import textwrap
doc = """The wrap() method is just like fill() except that it returns a list of strings with new... |
"""
Wind Turbine Company - 2013
Author: Stephan Rayner
Email: stephan.rayner@gmail.com
"""
import time
from test.Base_Test import Base_Test
class Maintenance_153Validation(Base_Test):
def setUp(self):
self.WindSpeedValue = "4.5"
self.interface.reset()
self.interface.write("Yaw_Generation", "... |
import ast
import inspect
class NameLower(ast.NodeVisitor):
def __init__(self, lowered_names):
self.lowered_names = lowered_names
def visit_FunctionDef(self, node):
code = '__globals = globals()\n'
code += '\n'.join("{0} = __globals['{0}']".format(name) for name in self.lowered_names)
... |
from django.utils.encoding import python_2_unicode_compatible
from allauth.socialaccount import app_settings
from allauth.account.models import EmailAddress
from ..models import SocialApp, SocialAccount, SocialLogin
from ..adapter import get_adapter
class AuthProcess(object):
LOGIN = 'login'
CONNECT = 'connect'... |
XXXXXXXXX XXXXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX XXXXXXX X XXXXXXXXXX XXXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX X... |
from ..baseapi import BaseApi
class Template(BaseApi):
def __init__(self, *args, **kwargs):
super(Template, self).__init__(*args, **kwargs)
self.endpoint = 'templates'
self.list_id = None
def all(self):
"""
returns a list of available templates.
"""
return... |
import datetime
import os
import sys
from contextlib import contextmanager
import freezegun
import pretend
import pytest
from pip._vendor import lockfile
from pip._internal.index import InstallationCandidate
from pip._internal.utils import outdated
class MockPackageFinder(object):
BASE_URL = 'https://pypi.python.or... |
import sys, math
class Tree(object):
def __repr__(self):
return self.val
def __init__(self, val=None):
self.val = val
self.childs = []
def add_number(self, number):
if not number:
return
for child in self.childs:
if number[0] == child.val:
... |
from __future__ import unicode_literals
from ..internet import Provider as InternetProvider
class Provider(InternetProvider):
safe_email_tlds = ('com', 'net', 'fr', 'fr')
free_email_domains = (
'voila.fr', 'gmail.com', 'hotmail.fr', 'yahoo.fr', 'laposte.net', 'free.fr', 'sfr.fr', 'orange.fr', 'bouygtel.fr',... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0011_auto_20170621_1224'),
]
operations = [
migrations.AddField(
model_name='category',
name='slug',
field=mo... |
import _plotly_utils.basevalidators
class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, plotly_name="tickvals", parent_name="parcoords.dimension", **kwargs
):
super(TickvalsValidator, self).__init__(
plotly_name=plotly_name,
paren... |
from django.forms import ModelForm, ModelChoiceField
from django.utils.translation import ugettext_lazy as _
from apps.task.models import Task
class FormChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return obj.name
class TaskForm(ModelForm):
"""
Task form used to add or update a task in the Ch... |
import redis
import json
class Redis(object):
def __init__(self, host="localhost", port=6379):
self._host = host
self._port = port
self._redis_cursor = None
def conn(self):
if self._redis_cursor is None:
pool = redis.ConnectionPool(host=self._host, port=self._port, db... |
__author__ = 'thorwhalen'
import requests
from serialize.khan_logger import KhanLogger
import logging
class SimpleRequest(object):
def __init__(self, log_file_name=None, log_level=logging.INFO):
full_log_path_and_name = KhanLogger.default_log_path_with_unique_name(log_file_name)
self.logger = KhanLo... |
import os
import glob
os.remove("a0.txt")
os.remove("a1.txt")
os.remove("a2.txt")
os.remove("a3.txt")
os.remove("a4.txt")
os.remove("a5.txt")
os.remove("a6.txt")
os.remove("a7.txt")
os.remove("a8.txt")
os.remove("a9.txt")
os.remove("n0.txt")
os.remove("n1.txt")
os.remove("n2.txt")
os.remove("n3.txt")
os.remove("n4.txt"... |
from __future__ import print_function, absolute_import, unicode_literals, division
from stackable.stackable import Stackable, StackableError
import json, pickle
from time import sleep
from threading import Thread, Event
from datetime import datetime, timedelta
class StackablePickler(Stackable):
'Pickle codec'
def pro... |
from flask_pymongo import PyMongo
from flask_cors import CORS
mongo = PyMongo()
cors = CORS() |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import mptt.fields
import uchicagohvz.overwrite_fs
from django.conf import settings
import django.utils.timezone
import uchicagohvz.game.models
class Migration(migrations.Migration):
dependencies = [
... |
import torch
import sys
import types
class VFModule(types.ModuleType):
def __init__(self, name):
super(VFModule, self).__init__(name)
self.vf = torch._C._VariableFunctions
def __getattr__(self, attr):
return getattr(self.vf, attr)
sys.modules[__name__] = VFModule(__name__) |
"""
Constructs a planner that is good for being kinda like a car-boat thing!
"""
from __future__ import division
import numpy as np
import numpy.linalg as npl
from params import *
import lqrrt
magic_rudder = 6000
def dynamics(x, u, dt):
"""
Returns next state given last state x, wrench u, and timestep dt.
"... |
from django.test import TestCase
from builds.models import Version
from projects.models import Project
class RedirectTests(TestCase):
fixtures = ["eric", "test_data"]
def setUp(self):
self.client.login(username='eric', password='test')
r = self.client.post(
'/dashboard/import/',
... |
import hexchat
import re
import sys
import twitch.hook, twitch.jtvmsghandler, twitch.user, twitch.channel
import twitch.normalize, twitch.commands, twitch.exceptions, twitch.topic
import twitch.logger, twitch.settings
from twitch import irc
log = twitch.logger.get()
ban_msg_regex = re.compile(r"for (\d+) more seconds")... |
from __future__ import absolute_import, unicode_literals, division
from ._version import __version__, __version_info__ # noqa
from .decorators import route, resource, asynchronous
from .helpers import use
from .relationship import Relationship
__all__ = [
'route',
'resource',
'asynchronous',
'use',
... |
from __future__ import absolute_import, division, print_function
import os
import sys
import argparse
import ros1_pytemplate
import logging.config
logging.config.dictConfig(
{
'version': 1,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(pro... |
from flask.ext.login import UserMixin, AnonymousUserMixin
from codeta import app, auth, logger
from codeta.models.course import Course
class User(UserMixin):
def __init__(self, user_id, username, password, email, fname, lname, active=True, courses=[]):
self.user_id = user_id
self.username = username... |
import sys
import time
from datetime import datetime
from pathlib import Path
from ezdxf.acc import USE_C_EXT
from ezdxf.render.forms import ellipse
if USE_C_EXT is False:
print("C-extension disabled or not available.")
sys.exit(1)
from ezdxf.math._construct import (
has_clockwise_orientation as py_has_cloc... |
import random
def program():
# These are the constants declaring what the colors are.
RED = 'red'
BLUE = 'blue'
GREEN = 'green'
ORANGE = 'orange'
PURPLE = 'purple'
PINK = 'pink'
class Color:
pass
c1 = Color()
c2 = Color()
c3 = Color()
guesses_made = 0
c1.name ... |
import os
from pi3bar.plugins.base import Plugin
from pi3bar.utils import humanize_size_bytes
class Disk(Plugin):
"""
:class:`pi3bar.app.Pi3Bar` plugin to disk usage.
Available format replacements (``*_p`` = percentage):
* ``%(size)s`` E.g. '100GB'
* ``%(free)s`` E.g. '70GB'
* ``%(free_p)f`` E.g... |
"""Process `site.json` and bower package tools."""
import os
import json
import subprocess
from functools import partial
import importlib
import sys
from flask import Flask, render_template, g, redirect, current_app
from gitloader import git_show
from import_code import import_code
try:
from app import app
except I... |
from app import app
import sys
port = 5000
debug = True
if len(sys.argv) == 3:
debug = sys.argv[1] == 'debug'
port = int(sys.argv[2])
app.run(debug = debug, port = port) |
"""
Find characters deep in the expanded string, for fun.
"""
import sys
from collections import Counter
def real_step(s, rules):
out = ""
for i in range(len(s)):
out += s[i]
k = s[i:i+2]
if k in rules:
out += rules[k]
return out
def step(cnt, rules):
ncnt = Counter()... |
from raptiformica.utils import list_all_files_in_directory
from tests.testcase import TestCase
class TestListAllFilesInDirectory(TestCase):
def setUp(self):
self.walk = self.set_up_patch('raptiformica.utils.walk')
self.walk.return_value = [
('/tmp/a/directory', ['dir'], ['file.txt', 'fil... |
import threading, time
from sqlalchemy import pool, interfaces, select, event
import sqlalchemy as tsa
from sqlalchemy import testing
from sqlalchemy.testing.util import gc_collect, lazy_gc
from sqlalchemy.testing import eq_, assert_raises
from sqlalchemy.testing.engines import testing_engine
from sqlalchemy.testing im... |
from .models import EmailUser
class EmailOrPhoneModelBackend:
def authenticate(self, username=None, password=None):
if '@' in username:
kwargs = {'email__iexact': username}
else:
kwargs = {'phone': username}
try:
user = EmailUser.objects.get(**kwargs)
... |
"""
Production settings
Debug OFF
Djeroku Defaults:
Mandrill Email -- Requires Mandrill addon
dj_database_url and django-postgrespool for heroku postgres configuration
memcachify for heroku memcache configuration
Commented out by default - redisify for heroku redis cache configuration
What you need to s... |
import json
import logging
from flask import abort, redirect, render_template, request, send_file
import ctrl.snip
from . import handlers
@handlers.route('/snip/<slug>.png')
def snip_view(slug):
filename = ctrl.snip.getSnipPath(slug)
if filename == None:
logging.warning("invalid slug: " + slug)
abort(400)
... |
from msrest.serialization import Model
class ClusterUpgradeDescriptionObject(Model):
"""Represents a ServiceFabric cluster upgrade.
:param config_version: The cluster configuration version (specified in the
cluster manifest).
:type config_version: str
:param code_version: The ServiceFabric code ver... |
"""Distutils installer for extras."""
from setuptools import setup
import os.path
import extras
testtools_cmd = extras.try_import('testtools.TestCommand')
def get_version():
"""Return the version of extras that we are building."""
version = '.'.join(
str(component) for component in extras.__version__[0:... |
import tensorflow as tf
import numpy as np
import deep_architect.modules as mo
import deep_architect.hyperparameters as hp
from deep_architect.contrib.misc.search_spaces.tensorflow.common import siso_tfm
D = hp.Discrete # Discrete Hyperparameter
def dense(h_units):
def compile_fn(di, dh): # compile function
... |
from cuescience_shop.models import Client, Address, Order
from natspec_utils.decorators import TextSyntax
from cart.cart import Cart
from django.test.client import Client as TestClient
class ClientTestSupport(object):
def __init__(self, test_case):
self.test_case = test_case
self.client = TestClient... |
from lib.utils import *
def _help():
usage = '''
Usage: type (file)
Print content of (file)
Use '%' in front of global
vars to use value as file
name.
'''
print(usage)
def main(argv):
if len(argv) < 1 or '-h' in argv:
_help()
return
# The shell doesnt send the
# command name in the a... |
from CIM14.IEC61970.OperationalLimits.OperationalLimit import OperationalLimit
class ActivePowerLimit(OperationalLimit):
"""Limit on active power flow.
"""
def __init__(self, value=0.0, *args, **kw_args):
"""Initialises a new 'ActivePowerLimit' instance.
@param value: Value of active power l... |
to_freud = lambda sentence: ' '.join(['sex'] * len(sentence.split(' '))) |
def filename_directive(filename):
return "\t.file\t\"{0}\"\n".format(filename)
def compiler_ident_directive():
return "\t.ident\t\"{0}\"\n".format("HEROCOMP - Tomas Mikula 2017")
def text_directive():
return "\t.text\n"
def data_directive():
return "\t.data\n"
def quad_directive(arg):
return "\t.qua... |
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^$', 'tests.views.index'),
) |
from flask import Flask, redirect, url_for, session, request, render_template_string, abort
import requests
import os
import ast
import base64
from nocache import nocache
ALLOWED_EXTENSIONS = set(['mp4'])
app = Flask(__name__)
app.secret_key = os.urandom(24)
@app.errorhandler(404)
@nocache
def error_404(e):
"""
... |
import pytest
from bcbio.pipeline import rnaseq
@pytest.yield_fixture
def ericscript_run(mocker):
yield mocker.patch('bcbio.pipeline.rnaseq.ericscript.run', autospec=True)
@pytest.fixture
def sample():
return {
'config': {
'algorithm': {
'fusion_mode': True,
'... |
from __future__ import print_function
import cPickle as pickle
import sys
import time
from collections import OrderedDict
import numpy
import theano
import theano.tensor as tensor
from theano import config
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
import encoder_decoder
SEED = 123
numpy.rand... |
from django.shortcuts import render
from django.middleware.csrf import get_token
from ajaxuploader.views import AjaxFileUploader
from pandora.backends import SignalBasedLocalUploadBackend
from pandora.models import Item
def home(request):
return render(request, 'pandora/home.html', {
'items': Item.objec... |
import os
import re
from setuptools import find_packages, setup
def text_of(relpath):
"""
Return string containing the contents of the file at *relpath* relative to
this file.
"""
thisdir = os.path.dirname(__file__)
file_path = os.path.join(thisdir, os.path.normpath(relpath))
with open(file_... |
"""
Author: Junhong Chen
"""
from Bio import SeqIO
import gzip
import sys
import os
pe1 = []
pe2 = []
pname = []
for dirName, subdirList, fileList in os.walk(sys.argv[1]):
for fname in fileList:
tmp = fname.split(".")[0]
tmp = tmp[:len(tmp)-1]
if tmp not in pname:
pname.append(tm... |
class Color:
''' print() wrappers for console colors
'''
def red(*args, **kwargs): print("\033[91m{}\033[0m".format(" ".join(map(str,args))), **kwargs)
def green(*args, **kwargs): print("\033[92m{}\033[0m".format(" ".join(map(str,args))), **kwargs)
def yellow(*args, **kwargs): print("\033[93m{}\033[... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('backups', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='backupfirewall',
name='file_location',
),
... |
version = '2.4.1'
release = False
if not release:
version += '.dev'
import os
svn_version_file = os.path.join(os.path.dirname(__file__),
'__svn_version__.py')
if os.path.isfile(svn_version_file):
import imp
svn = imp.load_module('numexpr.__svn_version_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.