code stringlengths 1 199k |
|---|
from __future__ import unicode_literals
from django.db import migrations
def create_root_space(apps, schema_editor):
""" Create a default ROOT space """
Space = apps.get_model("spaces", "Space")
Space.objects.create(id=1, name="__ROOT__", path="")
Space.objects.create(id=2, name="__USER__", path="user")... |
import balanced
balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY')
card = balanced.Card.fetch('/cards/CC3vhL91rWtwtHcOBl0ITshG')
card_hold = card.hold(
amount=5000,
description='Some descriptive text for the debit in the dashboard'
) |
from __future__ import print_function
from __future__ import division
import os
import codecs
import collections
import numpy as np
import pickle
class Vocab:
def __init__(self, token2index=None, index2token=None):
self._token2index = token2index or {}
self._index2token = index2token or []
def f... |
import sys, os
from math import *
from panda3d.core import *
from panda3d.egg import *
from utils import *
def retrieveTexture(textureName, textureFolderName, textureEnvType = EggTexture.ETUnspecified, textureScale = 1.0, textureFormat = "png"):
if EggTexture.ETUnspecified == textureEnvType:
textureNameEnding = "Dif... |
import pandas
from defines import Types
def load(metadata):
print 'Loading data file from location: \'' + metadata.LOCATION + '\''
# skip first row if CSV is labeled
skiprows = None
if metadata.IS_LABELED:
skiprows = 1
print 'Skipping header row...'
# parse CSV file
data = pandas... |
import re
import select
import socket
import threading
import time
import traceback
from app import redis
from arch.msp430 import CorruptionMSP
import config
command_re = re.compile(r'^(?P<ack>[+\-])|^\$(?P<data>[^#]*)#(?P<checksum>[a-f0-9]{2})')
def checksum(s):
if s is None:
return ''
return '%0.2x' %... |
"""
WSGI config for monitortwitter project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Dj... |
"""
Created on Fri Apr 20 13:16:57 2018
@author: smullally
"""
from astropy.io import fits
from astropy.time import Time
import numpy as np
def writeDetrendSeriesFitsFile(clip):
"""
Given a clipboard shelf write out the detrended light curve and the time
to the first extension.
The resulting FITS file m... |
import pytest
class Test{{ cookiecutter.project_name |capitalize }}():
"""Tests for `{{ cookiecutter.project_name }}` module."""
def test_one(self):
assert True
@pytest.mark.integrations
def test_two():
assert True |
"""Test p4lib.py's interface to 'p4 sync'."""
import os
import unittest
import testsupport
from p4lib import P4
class SyncTestCase(unittest.TestCase):
def test_sync_added_file(self):
top = os.getcwd()
andrew = testsupport.users['andrew']
bertha = testsupport.users['bertha']
p4 = P4()... |
file_open = open('code.txt', 'r')
def code_gen():
for c1 in range(100):
for c2 in range(100):
for c3 in range(100):
yield (c1, c2, c3)
for line in file_open.readlines():
sequence = tuple([int(x) for x in line.split()])
for (c1, c2, c3) in code_gen():
if (c1, c2, c... |
import _plotly_utils.basevalidators
class ShowexponentValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="showexponent", parent_name="surface.colorbar", **kwargs
):
super(ShowexponentValidator, self).__init__(
plotly_name=plotly_name,
... |
"""
Removes reads from a BAM file based on criteria
Given a BAM file, this script will only allow reads that meet filtering
criteria to be written to output. The output is another BAM file with the
reads not matching the criteria removed.
Note: this does not adjust tag values reflecting any filtering. (for example:
... |
import re
def solution():
T = int(input())
for t in range(1, T+1):
solve(t)
def solve(t):
n = int(input())
eva = {''}
ok = True
assi = []
for i in range(n):
r = re.split('[\=\,\(\)]', input())
assi.append([r[0], set(r[2:-1])])
while assi:
noupdate = True
... |
import sys
import os
import atexit
import readline, rlcompleter
from tempfile import mkstemp
from code import InteractiveConsole
HISTFILE = "%s/.pyhistory" % os.environ["HOME"]
if os.path.exists(HISTFILE):
readline.read_history_file(HISTFILE)
readline.set_history_length(300)
def savehist():
readline.write_history_fil... |
import os, datetime
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.worksheet import Worksheet
from config import Config
class XlsxProcessor(object):
"""XlsxProcesser maintain and update xlsm file to keep data"""
def __init__(self):
self.config = Config.get_xlsxconfig()
... |
"""added key to comments.subreddit_id
Revision ID: 2959fa8d7ad8
Revises: 05a831a5db7b
Create Date: 2017-07-26 19:53:29.818965
"""
revision = '2959fa8d7ad8'
down_revision = '05a831a5db7b'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade(engine_name):
globals()["upgrad... |
"""Test zha switch."""
from unittest.mock import call, patch
import pytest
import zigpy.profiles.zha as zha
import zigpy.zcl.clusters.general as general
import zigpy.zcl.foundation as zcl_f
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.components.zha.core.group import GroupMembe... |
"""This lib calculates the probability of a given student needs the substitute
test"""
from pandas import get_dummies
from sklearn.naive_bayes import MultinomialNB
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from mlstudents.dataset import DataSet
class Classify(object... |
"""Database related tools."""
import logging
from datetime import datetime
import dateutil.parser
from sqlalchemy import (
Column,
MetaData,
Table,
create_engine,
inspect,
select,
type_coerce,
)
from sqlalchemy.exc import (
DatabaseError,
NoSuchTableError,
)
from sqlalchemy.types imp... |
""" Tests for utils.py """
import unittest
from medleydb import utils
from medleydb import multitrack
class TestLoadTrackList(unittest.TestCase):
def setUp(self):
self.track_list = utils.load_track_list()
def test_length(self):
self.assertEqual(len(self.track_list), 122)
def test_inclusion(s... |
from __future__ import unicode_literals
import swapper
from django.db import models
from accelerator_abstract.models.accelerator_model import AcceleratorModel
from accelerator_abstract.models.label_model import LabelModel
class BaseProgramRole(LabelModel):
program = models.ForeignKey(
swapper.get_model_name... |
import os
from subprocess import CalledProcessError, Popen
from libqtile.log_utils import logger
from libqtile.widget import base
class CheckUpdates(base.ThreadPoolText):
"""
Shows number of pending updates in different unix systems.
.. note::
It is common for package managers to return a non-zero c... |
from gremlinclient.requests.requests import Response, GraphDatabase, Pool |
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
setup(
name='hello_world',
version='0.1.0',
description='Example package',
long_description=readme,
author='Vasily Kuznetsov',
author_email='kvas.it@gmail.com',
url='https://gi... |
"""
FILE: matlab.py
AUTHOR: Cody Precord
@summary: Lexer configuration module for Matlab and Octave
"""
__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: _matlab.py 68798 2011-08-20 17:17:05Z CJP $"
__revision__ = "$Revision: 68798 $"
import wx.stc as stc
import synglob
import syndata
MATLAB_KW = (0, ... |
import os
import sys
import scipy
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
if __name__ == '__main__':
num_sample = 100
x1 = np.random.normal(0.0, 0.6, num_sample)
x2 = np.random.normal(2.0, 0.6, 2 * num_sample)
x = np.hstack([x1, x2])
fig = plt.figure()
ax = fig.add_... |
"""
Base backend
Trace and Database classes from the other modules should Subclass the base
classes.
Concepts
--------
Each backend must define a Trace and a Database class that subclass the
base.Trace and base.Database classes.
The Model itself is given a `db` attribute, an instance of the Database
class. The __init__... |
from scipy.constants import physical_constants, angstrom # type: ignore
angstrom_to_bohr = physical_constants['atomic unit of length'][0] / angstrom
ev_to_hartree = physical_constants['electron volt-hartree relationship'][0] |
"""Diagnostics support for UptimeRobot."""
from __future__ import annotations
from typing import Any
from pyuptimerobot import UptimeRobotException
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from . import UptimeRobotDataUpdateCoordinator
from .const import DOMAIN
a... |
import AppKit
import os
from vanilla import *
from defconAppKit.windows.baseWindow import BaseWindowController
from defcon import Font as DefconFont
from lib.formatters import PathFormatter
from lib.tools.misc import walkDirectoryForFile
from lib.settings import doodleSupportedExportFileTypes
from mojo.UI import Accord... |
from sqlalchemy import create_engine, Column, String, DateTime, Integer, Text, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
from settings import MYSQL_CONFIG
Base = declarative_base()
def db_connect():
return create_engine(
"mysql://"+MYSQL_CONFIG["U... |
""" Sahana Eden GUI Layouts (HTML Renderers)
@copyright: 2012-14 (c) Sahana Software Foundation
@license: MIT
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
restric... |
from setuptools import setup
setup(
name='LibAnt',
packages=['libAnt', 'libAnt.profiles', 'libAnt.drivers', 'libAnt.loggers'],
version='0.1.4',
description='Python Ant+ Lib',
author='Benjamin Tamasi',
author_email='h@lfto.me',
url='https://github.com/half2me/libAnt',
download_url='https:... |
from toontown.suit.DistributedSellbotBossAI import DistributedSellbotBossAI
from toontown.suit import BrutalSellbotBossGlobals
from toontown.suit.DistributedSuitAI import DistributedSuitAI
from toontown.suit import SuitDNA
from toontown.toonbase import ToontownGlobals
from toontown.toon import NPCToons
import random
cl... |
import os
import ConfigParser
import glob
from prettytable import PrettyTable
import re
inputdir = "ini/N*s[2,3,4,5]*.ini"
inputdir = "ini/NSF*s1*.ini"
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedb... |
"""
Copyright (c) 2009-2012 Dirk Holtwick <http://www.holtwick.it>
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,... |
def super_additionneur(param1, param2):
return float(param1) + float(param2) |
import base_filters
COPY_GOOGLE_DOC_KEY = '1nbpweBccoaBqxuyKSL6o0q_qkdponL0OWgJpbozQp58'
USE_ASSETS = False
JINJA_FILTER_FUNCTIONS = base_filters.FILTERS |
from __future__ import unicode_literals
from wiki.core.version import get_version
VERSION = (0, 1, 0, 'final', 0)
__version__ = get_version(VERSION) |
from pluginbase import PluginBase
import sqlite3
import logging
import time
import os
import datetime
import re
class Statistics(PluginBase):
"""Statistics provides various user and channel statistics via commands.
channels: A dictionary of cached channel IDs.
users: A dictionary of cached user IDs.
"""... |
import torch
from fairseq.optim.amp_optimizer import AMPOptimizer
from fairseq.tasks import register_task
from fairseq.tasks.speech_to_text import SpeechToTextTask
from .data.speech_to_text_dataset_with_domain import SpeechToTextDatasetCreatorWithDomain
from .loss.attention_head_selection import HeadSelectionLoss
@regi... |
import unittest
from unittest.mock import MagicMock, Mock, patch
from libsshtman import *
class ListenerTest(unittest.TestCase):
def setUp(self):
self.cmd = Mock()
commands = {'test': self.cmd}
self.listener = Listener(commands)
def test_should_call_target_command(self):
self.lis... |
import unittest
import math
import numpy as np
import numpy.testing
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True
from parspec import SpecBuilder
from parspec import Source
from parspec import ParSpec
def logPoisson(k, v, s):
vv = np.array(k, dtype=float)
vv[vv<1] = 1
vv += s
return -0.5 * (... |
import json
import os
import os.path
import glob
def parse_lesson_file(filename):
lines = [x.replace('\n','') for x in file(filename)]
fields = {
'ignore_characters': '',
'case_sensitive': '',
'require_spaces': '',
'title': lines[0],
'subtitle': lines[1],
}
questions = []
for line in lines[2:]:
if line... |
"""
Python chess library by Kristian Glass (mail@doismellburning.co.uk)
"""
import copy
import pieces
WHITE_PIECES = frozenset('PRNBKQ')
BLACK_PIECES = frozenset([p.lower() for p in WHITE_PIECES])
WHITE_PROMOTION_OPTIONS = WHITE_PIECES - set('P')
BLACK_PROMOTION_OPTIONS = BLACK_PIECES - set('p')
class InvalidSquareExce... |
from __future__ import unicode_literals
from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework.exceptions import ValidationError as RestValidationError
from rest_framework.utils.serializer_helpers import ReturnDict
from rest_framework_friendly_errors import settings
from rest_fr... |
from websocket.controller import base_controller
class PlainController(base_controller.BaseController):
def __init__(self, stream, output, handler):
super(PlainController, self).__init__(stream, output, handler)
def _after_message_handler(self, response):
return response
def _before_message_... |
from setuptools import setup
from doxhooks import __version__
with open("README.rst") as readme:
lines = list(readme)
for line_no, line in enumerate(lines):
if line.startswith("Doxhooks helps you"):
long_description = "".join(lines[line_no:])
break
else:
raise RuntimeError("Cannot find long ... |
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from rest_framework.routers import DefaultRouter
from volunteer import views as volunteer_views
from users... |
import os
from google.appengine.api import namespace_manager
from google.appengine.dist import use_library
import config
os.environ['DJANGO_SETTINGS_MODULE'] = config.DJANGO_CONFIG_MODULE
use_library('django', '1.2')
import google.appengine.ext.webapp.template
def namespace_manager_default_namespace_for_request():
""... |
N, M = map(int, input().split())
A, B = [], []
for _ in range(N):
A.append(input())
for _ in range(M):
B.append(input())
res = False
for sy in range(N - M + 1):
for sx in range(N - M + 1):
ok = True
for dy in range(M):
y = sy + dy
a = A[y][sx:sx + M]
ok = ... |
from duashttp.models import AssetVersion
from rest_framework import serializers
class AssetVersionSerializer(serializers.HyperlinkedModelSerializer):
hash = serializers.SerializerMethodField('get_digest')
guid = serializers.SerializerMethodField('get_guid')
def get_digest(self, obj):
return str(hex(... |
class InsufficientFundsError(Exception):
pass |
#!/usr/bin/env python
from mpi4py import MPI
from baselines.common import set_global_seeds
import os.path as osp
import gym, logging
from baselines import logger
from baselines import bench
from baselines.common.atari_wrappers import make_atari, wrap_deepmind
def train(env_id, num_timesteps, seed):
from baselin... |
import os
import time
from datetime import datetime
import pytz
from pytz import timezone
import json
from django.http import HttpResponse
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from djan... |
from django.core.urlresolvers import reverse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import View
from django.shortcuts import render, redirect
from posts.utils import youtube
class PostCreateView(LoginRequiredMixin, View):
def get(self, request, *args, **kwargs):
... |
import struct
import re
import os
import os.path
import sys
import hashlib
import datetime
import time
from collections import namedtuple
from binascii import unhexlify
settings = {}
def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i:i+2].encode() fo... |
import random
import numpy as np
import pandas as pd
from keras.applications import imagenet_utils
from scipy.misc.pilutil import imread
from params import args
from sklearn.model_selection import train_test_split
import sklearn.utils
from random_transform_mask import ImageWithMaskFunction
import os
def pad(image, padd... |
"""Document."""
from mongoengine.document import Document as OrigDoc
from .custom import CustomDocumentBase
class Document(CustomDocumentBase, OrigDoc):
"""Base document."""
meta = {
"abstract": True,
} |
"""Overlay."""
import functools
import logging
import os
from typing import Generator
from etest import ebuild
logger = logging.getLogger(__name__)
class Overlay(object):
"""A portage defined overlay."""
@functools.cached_property
def directory(self) -> str:
"""Directory containing overlay."""
... |
import re
import urlparse
def convert_to_utf8_str(arg):
# written by Michael Norton (http://docondev.blogspot.com/)
if isinstance(arg, unicode):
arg = arg.encode('utf-8')
elif not isinstance(arg, str):
arg = str(arg)
return arg
def encode_post_data_dict( post_data ):
data = []
fo... |
__version__ = "1.0.9"
import logging
try:
# Python >= 2.7
from logging import NullHandler
except ImportError:
# Python < 2.7
class NullHandler(logging.Handler):
def emit(self, record):
pass
logger = logging.getLogger("pyaxiom")
logger.addHandler(logging.NullHandler()) |
"""
Setup.py for Vesper pip package.
All of the commands below should be issued from the directory containing
this file.
To build the Vesper package:
python setup.py sdist bdist_wheel
To upload the Vesper package to the test Python package index:
python -m twine upload --repository-url https://test.pypi.org/leg... |
Test.describe('Basic tests')
Test.assert_equals(volume(7, 3), 153)
Test.assert_equals(volume(56, 30), 98520)
Test.assert_equals(volume(0, 10), 0)
Test.assert_equals(volume(10, 0), 0)
Test.assert_equals(volume(0, 0), 0) |
import sys
import time
import pygame
import Adafruit_CharLCD as LCD
import time, subprocess, datetime
lcd_rs = 21
lcd_en = 20
lcd_d4 = 25
lcd_d5 = 24
lcd_d6 = 23
lcd_d7 = 18
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2
today = datetime.date.today()
scoutlab = datetime.date(2017, 10, 20) #angebrochenen Tag ausgleiche... |
from django.urls.base import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from core.tests.mixins import HTTPMethodStatusCodeTestMixin
from bank_accounts.tests.factories import AccountFactory
class TestAccountAPIViewsUnauthorizedUser(HTTPMethodStatusCodeTestMixin,
... |
import sys, os
sys.path = [os.path.abspath(os.path.dirname(__file__))] + sys.path
os.environ['is_test_suite'] = 'True'
import pandas as pd
from sklearn.datasets import load_boston
from sklearn.metrics import brier_score_loss, mean_squared_error
from sklearn.model_selection import train_test_split
from auto_ml import Pr... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from core.views import TransactionCreateView
urlpatterns = patterns(
'',
url(r'^dashboard/$',
TransactionCreateView.as_view(), name="dashboard"),
url(r'^admin/', include(admin.site.urls)),
url(r'^shop/', include... |
from penchy.compat import unittest
from penchy.jobs.typecheck import Types, TypeCheckError
from penchy.tests.util import MockPipelineElement
class CheckArgsTest(unittest.TestCase):
def setUp(self):
super(CheckArgsTest, self).setUp()
self.p = MockPipelineElement()
self.inputs = Types(('foo', ... |
import lasagne
from lasagne.layers import InputLayer
from lasagne.layers import Conv2DLayer as ConvLayer
from lasagne.layers import BatchNormLayer
from lasagne.layers import Pool2DLayer as PoolLayer
from lasagne.layers import NonlinearityLayer
from lasagne.layers import ElemwiseSumLayer
from lasagne.layers import Dense... |
"""
Created on Wed Oct 22 09:07:07 2014
@author: ydzhao
"""
from mas_sys import *
import spyderlib.utils.iofuncs as sui
if __name__=="__main__":
sui.save_session('simspy.spydata')
plt.close('all')
t_start=0
t_end=sim_times
energy=cal_energy(MAS1,sim_times,T_intval)
print ... |
"""
Given two media conditions, one where we grow and one where we do not,
and a set of reactions, test all the reactions to see which is required
for growth
"""
import os
import sys
import argparse
import copy
import PyFBA
from PyFBA import log_and_message
model_data = PyFBA.model_seed.ModelData()
__author__ = 'Rob Ed... |
"""
translate
=========
"""
import bs4 as _bs4
import re as _re
import update as _upd
def translate(nodes, astr, translator,
method='startswith',
cleanup=True,
translate_href_google=False,
add_attr=False,
add_target_blank=False):
"""
nodes [l... |
import brigalaxy as bg
import sys, os, argparse, re
def parse_input_args(parser=None):
parser.add_argument('-d', '--processed_dir',
required=True,
default=None,
help=("path to processed directory - e.g., "
"/mnt/ge... |
def read_file():
"""Opens Project Euer Name file. Reads names, sorts and converts str into
a list object"""
a = open('names.txt', 'r')
data = a.read()
names = data.split(",")
a.close()
names.sort()
return names
def name_score():
"""Calculates the total name score of each name in the ... |
from __future__ import unicode_literals
from django.db import migrations, models
def publish_everything(apps, schema_editor):
Company = apps.get_model("core", "Company")
Person = apps.get_model("core", "Person")
Person.objects.all().update(publish=True)
Company.objects.all().update(publish=True)
class M... |
from supriya.tools.ugentools.UGen import UGen
class LorenzL(UGen):
r'''A linear-interpolating Lorenz chaotic generator.
::
>>> lorenz_l = ugentools.LorenzL.ar(
... b=2.667,
... frequency=22050,
... h=0.05,
... r=28,
... s=10,
... xi... |
"""
Geometric Brownian Motion
=========================
"""
import numpy as np
__all__ = ['GBM', 'GBMParam']
class GBMParam(object):
"""Parameter storage.
"""
def __init__(self, sigma=.2):
"""Initialize class.
Parameters
----------
sigma : float
"""
self.sigma... |
import app
import json
from flask.ext.login import login_required
from flask import request, jsonify, render_template, url_for, redirect, flash
show_canvas = True
@app.flask_app.route('/user/<user_name_route>/<map_name_route>', methods=['GET'])
@login_required
def user_mapping(user_name_route, map_name_route):
u = ... |
import os
import subprocess
import re
import fileinput
import shutil
import errno
import tempfile
import pprint
try:
input = raw_input
except NameError:
pass
set_client_field = re.compile(r'(?P<mcpbot_command>scf) (?P<searge_name>\w+) (?P<semantic_name>\w+)( (?P<description>.+))?', flags=re.IGNORECASE)
set_client_met... |
from django import VERSION
from django.db.models import Manager
from faster.models.query import FasterQuerySet
class FasterManagerBase(Manager):
def get_fast_queryset(self):
return FasterQuerySet(self.model, using=self._db)
def dates(self, *args, **kwargs):
return self.get_fast_queryset().approx... |
import tensorflow as tf
from neupy.core.properties import (
ProperFractionProperty,
ScalarVariableProperty,
NumberProperty,
)
from .base import GradientDescent
__all__ = ('Adadelta',)
class Adadelta(GradientDescent):
"""
Adadelta algorithm.
Parameters
----------
rho : float
Decay... |
import pygame
from pygame.surface import Surface
from Menu.LoadGameMenu.LoadGameMenu import LoadGameMenu
from Menu.StartMenu.StartMenuItems.StartMenuItem import StartMenuItem
from Vector2 import Vector2
class LoadGame(StartMenuItem):
def __init__(self, offset: Vector2, image: Surface = None, hover: Surface = None,... |
import xml.dom.minidom as dom
import codecs
import re
import os
BROWN_POS_PATH = "/Path/On/Your/Disk/Where/All/The/Brown/POS/Files/Are/Brown/"
TAG_TOKEN_SEPARATOR = "#!#"
out = open("brown.pos","w")
tokens_pattern = re.compile('(\s*[(.+)/(.+)]\s+)*')
files = os.listdir(BROWN_POS_PATH)
sentence_lines = []
for filename ... |
import falcon
import falcon.errors
import json
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from .test_base import Base, BaseTestCase
from .test_fixtures import Account, Company
from .resource import CollectionResource, SingleResource
class Owner(Base):
__tablen... |
import unittest
from rest_framework.test import APITestCase
from tests.testapp.models import TimeSeries
from .settings import HAS_MATPLOTLIB
@unittest.skipUnless(HAS_MATPLOTLIB, "requires matplotlib")
class ImageTestCase(APITestCase):
def setUp(self):
data = (
('2014-01-01', 0.5),
('... |
from .core import LagringCore
from .entity import Entity
from .asset import Asset, AssetInstance, NoneAssetInstance
from .exceptions import *
from .logger import log
from .flask_lagring import FlaskLagring |
import numpy as np
import scipy.sparse as sp
from discretize.utils.matrix_utils import mkvc, sub2ind
from discretize.utils.code_utils import deprecate_function
try:
from discretize._extensions import interputils_cython as pyx
_interp_point_1D = pyx._interp_point_1D
_interpmat1D = pyx._interpmat1D
_inter... |
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 115200)
data = [
# b'\x06\x23\x21\xB7\x04\x00\x00', # set kp 0.1204
# b'\x06\x23\x22\xB5\x04\x00\x00', # set ki 0.1205
# b'\x06\x23\x23\xB6\x04\x00\x00', # set kd 0.1206
# b'\x02\x21\x21', #inc kp
# b'\x02\x21\x22', #inc ki
# b'\x02\x... |
print "Hello World!\n" |
'''CDR3 length distribution: Reads and Clones
% reads/% clones (yaxis) vs CDR3 aa_length (xaxis)
ttests: 1/ for the median length of group1 vs group2
2/ for each length, compare the proportion (reads/clones)
in group1 vs group2 having that length
'''
import os
import sys
import gzip
import cPickle as pi... |
import os
import django
from django.core.management import call_command
class DjangoSetupMixin(object):
@classmethod
def setup_class(cls):
# NOTE: this may potentially have side-effects, making tests pass
# that would otherwise fail, because it *always* overrides which
# settings module ... |
x = 3.14 |
import json
print json.dumps({
"_meta": {
"hostvars": {
"foobar": {"host_var": "this is foobar"}
}
},
"all": {
"vars": {
"inventory_var": "this is an inventory with host and group and inventory vars"
}
},
"southeast": {
"hosts": ["fooba... |
"""
This module contains various useful and frequently used functions.
""" |
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="family", parent_name="icicle.outsidetextfont", **kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Review',
fields=[
('id', models.AutoField... |
from collections import deque
import math
from graph_classes import GraphNode, Edge
def find_shortest_path_length(graph, start_node_id, end_node_id):
"""Finds the shortest path between two given nodes in the given graph. Uses dijkstra's algorithm to do this.
A few notes:
This should work for *graph* whe... |
"""
Download Thru.de PRTR database and create
relationship triple file 'thrude.csv'.
More information: http://www.thru.de/thrude/downloads/
"""
import csv
import sqlite3
import urllib2
import zipfile
import os
URL = "http://www.thru.de/fileadmin/SITE_MASTER/content/Dokumente/Downloads/PRTR-Gesamtdatenbestand_stand_maer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.