code stringlengths 1 199k |
|---|
import sys
sys.stdin.readline()
xs = map(int, sys.stdin.readline().split(' '))
s = reduce(lambda a, b: a ^ b, xs, 0)
r = 0
for x in xs:
if x ^ s < x:
r += 1
print r |
RANK_NAMES = [
('Deuce', 'Deuces'),
('Three', 'Threes'),
('Four', 'Fours'),
('Five', 'Fives'),
('Six', 'Sixes'),
('Seven', 'Sevens'),
('Eight', 'Eights'),
('Nine', 'Nines'),
('Ten', 'Tens'),
('Jack', 'Jacks'),
('Queen', 'Queens'),
... |
__author__ = 'bbowman@pacificbiosciences.com'
from .SmrtHmlReportWriter import *
from .SmrtHmlReport import * |
from __future__ import unicode_literals
import datetime
import functools
import math
import os
import re
import tokenize
import unittest
import custom_migration_operations.more_operations
import custom_migration_operations.operations
from django import get_version
from django.conf import settings
from django.core.valid... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Quantization'] , ['PolyTrend'] , ['Seasonal_Minute'] , ['NoAR'] ); |
def extractKapsouratranslatesBlogspotCom(item):
'''
Parser for 'kapsouratranslates.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated... |
from __future__ import with_statement
from datetime import datetime
import shutil
from StringIO import StringIO
import tempfile
import unittest
import trac.tests.compat
from trac.attachment import Attachment
from trac.core import *
from trac.resource import Resource
from trac.test import EnvironmentStub
from trac.util.... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0011_auto_20160622_1334'),
]
operations = [
migrations.AddField(
model_name='post',
name='read_time',
field=... |
""" tests ReOBJ Classes
"""
from inspect import (
getfile,
currentframe
)
from os.path import (
abspath,
dirname,
join
)
from sys import path as syspath
from nose.tools import (
raises,
ok_
)
SCRIPT_PATH = dirname(abspath(getfile(currentframe())))
PROJECT_ROOT = dirname(SCRIPT_PATH)
ROOT_PACKAGE_N... |
"""add withdrawal reason
Revision ID: 378ee128c23f
Revises: 380d2c363481
Create Date: 2018-10-11 11:07:27.080104
"""
import model.utils
import sqlalchemy as sa
from alembic import op
from rdr_service.participant_enums import WithdrawalReason
revision = "378ee128c23f"
down_revision = "380d2c363481"
branch_labels = None
... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Article.featured_image_caption'
db.add_column(u'article_article', 'featured_image_ca... |
from django.contrib.auth import get_user_model
from django.http import HttpRequest
from django.test import TestCase
from ..models import AdSense
from .. import utils as util
from .. import defaults as defs
User = get_user_model()
class CommonTestCase(TestCase):
"""
Model Tests.
"""
site_value = (defs.AD... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'PhaseCriterion'
db.create_table('challenges_phasecriterion', (
('id', self.gf('django.db.models.fields.Auto... |
import json
from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from .models import Order
@csrf_exempt
def handle_order_callback(request):
if settings.COINBASE_SHARED_SECRET != request.GET.get("secret"):
return Htt... |
from django.conf.urls.defaults import patterns, url
from django.views.generic.base import TemplateView
from csp.decorators import csp_exempt
urlpatterns = patterns('',
url(r'^/?$', 'innovate.views.splash', name='innovate_splash'),
url(r'^about/$', 'innovate.views.about', name='innovate_about'),
url(r'^hatch... |
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "STT"
addresses_name = "2021-03-08T13:26:49.693904/Democracy_Club__06May2021.tsv"
stations_name = "2021-03-08T13:26:49.693904/Democracy_Club__06May2021.tsv"
e... |
"""
Synchronize two directories.
Source: https://gist.github.com/xalexchen/7038205
"""
import filecmp, shutil, os, sys
IGNORE = ['.git', '.hg']
__all__ = [
'syncfiles',
]
def get_cmp_paths(dir_cmp, filenames):
return ((os.path.join(dir_cmp.left, f), os.path.join(dir_cmp.right, f)) for f in filenames)
def sync(d... |
import os, numpy, pickle
from readplatemap import *
p='C:/Users/Gregoire/Documents/CaltechWork/platemaps/0037-04-0730-mp.txt'
dlist=readsingleplatemaptxt(p)
codes=numpy.array([d['code'] for d in dlist])
smps=numpy.array([d['Sample'] for d in dlist])[codes==0]
comps=numpy.array([[d[let] for let in ['A', 'B', 'C', 'D']] ... |
from django.views.generic import DetailView
from django.views.generic import UpdateView
from django_viewset import URLView
from django_viewset import ViewSet
def describe_viewset():
class SimpleViewSet(ViewSet):
read = URLView(r'^(?P<pk>[0-9]+)/read/$', DetailView)
update = URLView(r'^(?P<pk>[0-9]+)... |
from __future__ import absolute_import, division, print_function
import unittest
from skbio.util import classproperty, overrides
from skbio.util._exception import OverrideError
class TestOverrides(unittest.TestCase):
def test_raises_when_missing(self):
class A(object):
pass
with self.ass... |
from __main__ import vtk, qt, ctk, slicer
import string
import numpy
import math
import operator
import collections
import time
class TextureGLCM:
def __init__(self, grayLevels, numGrayLevels, parameterMatrix, parameterMatrixCoordinates, parameterValues,
allKeys, checkStopProcessFunction):
... |
def extractWwwKitchennovelCom(item):
'''
Parser for 'www.kitchennovel.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'L... |
import numpy as np
import unittest
from menpo.mesh.face import Face
from scipy.sparse import linalg
class LaplacianTest(unittest.TestCase):
"""Unit tests for Laplacian Operator"""
def setUp(self):
"""Construct a square mesh and it's cotangent Laplacian/Area matrix
Sparse representations are at self.A and... |
from django import forms
from movieGraphs import models
class FilmForm(forms.ModelForm):
profession = forms.ModelChoiceField(label = 'Profession', empty_label='Select Profession for Artist', queryset=models.Profession.objects.all())
artist = forms.CharField(max_length = 150, label = 'Artist Name', help_text = '... |
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'localhost',
'PORT': '5432',
}
}
CACHES = {
'default': {
'BACKEND': 'social_graph.cache_back... |
"""Generates new baselines for Blink layout tests that need rebaselining.
Intended to be called periodically. Syncs to the Blink repo and runs
'webkit-patch auto-rebaseline', which processes entries in
LayoutTests/TestExpectations that are marked with 'NeedsRebaseline'.
Slaves running this recipe will require SVN acces... |
import sys
sys.path.append('.')
from objp.util import dontwrap
class Simple:
def hello_(self, name: str):
print("Hello %s!" % name)
print("Now, let's try a hello from ObjC...")
from ObjCHello import ObjCHello
proxy = ObjCHello()
proxy.helloToName_(name)
print("Oh, and... |
from __future__ import print_function
import sys, time
class ProgressBar:
def __init__(self, iterations):
self.iterations = iterations
self.prog_bar = '[]'
self.fill_char = '*'
self.width = 50
self.startTime = time.time()
self.lastIter = 0
self.__update_amount... |
from django.test import TestCase
from django import template
class GetCategoryTest(TestCase):
fixtures = ['musicgenres.json']
def render_template(self, template_string, context={}):
"""
Return the rendered string or raise an exception.
"""
tpl = template.Template(template_string)... |
from tokenizer import GameEvent, NewClient, PlayerinfoChange, KillClient, ItemPickup, Kill, InitGame, TeamName, Chat, WeaponStats, EndGame, ServerTime, TeamScore, FlagCapture, FlagReturn, FlagAssistReturn, FlagCarrierKill, FlagDefend, BaseDefend, FlagAssistFrag, CarrierDefend, Score
from awards2 import give_awards
from... |
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
import models
from django.conf import settings
class FilerFilePlugin(CMSPluginBase):
module = 'Filer'
model = models.FilerFile
name = _("File")
render_template = "cms... |
"""Creates a GYP include file for building FFmpeg from source.
The way this works is a bit silly but it's easier than reverse engineering
FFmpeg's configure scripts and Makefiles. It scans through build directories for
object files then does a reverse lookup against the FFmpeg source tree to find
the corresponding C or... |
import numpy as np
from scipy import linalg, special
from traits.api import HasTraits, Array, CFloat, List, \
Instance, on_trait_change, Property
from traitsui.api import Item, View, ListEditor, \
HSplit, VSplit
from mayavi.core.ui.api import EngineView, MlabSceneModel, \
SceneEditor
X, Y, Z = np.mgr... |
"""
Django settings for nthucourses project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
BASE... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('grades', '0009_micromasterscoursecertificate'),
]
operations = [
migrations.AlterField(
model_name='micromas... |
''' Interfaces to SPM '''
from __future__ import with_statement
import os
import numpy as np
from scipy.io import savemat
from nipy.utils import InTemporaryDirectory, setattr_on_read
from nipy.io.imageformats import load
from nipy.interfaces.matlab import run_matlab_script
class SpmInfo(object):
@setattr_on_read
... |
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _
from simplemenu.models import SimpleMenuPlugin as SimpleMenuPluginModel
from simplemenu.models import Link
class CMSPluginSimpleMenu(CMSPluginBase):
model = SimpleMenuPluginModel... |
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
def get_display_name(user):
"""
Tries to return (in order):
* ``user.profile.display_name``
* ``user.username``
"""
if user is None:
return None
profile = user.profile
if profi... |
from contextlib import contextmanager
from nose.tools import eq_
from tower import activate
import amo.tests
import mkt.constants.ratingsbodies as ratingsbodies
class TestRatingsBodies(amo.tests.TestCase):
def test_all_ratings_waffle_off(self):
ratings = ratingsbodies.ALL_RATINGS()
# Assert only CLA... |
import tigre
import numpy as np
from tigre.utilities import sample_loader
from tigre.utilities import CTnoise
import tigre.algorithms as algs
geo = tigre.geometry_default(high_resolution=False)
angles = np.linspace(0, 2 * np.pi, 100)
head = sample_loader.load_head_phantom(geo.nVoxel)
projections = tigre.Ax(head, geo, a... |
import unittest
import sys
import os
from datetime import datetime, timedelta
from get_database import get_db, get_client_db, get_profile_db, get_uuid_db, get_pending_signup_db, get_section_db
from utils import load_database_json, purge_database_json
sys.path.append("%s" % os.getcwd())
from dao.client import Client
fro... |
"""Read/write event class from/to gzip-compressed pickle files.
"""
import pickle
from pax.FolderIO import WriteZippedEncoder, ReadZippedDecoder
class EncodeZPickle(WriteZippedEncoder):
def encode_event(self, event):
return pickle.dumps(event)
class DecodeZPickle(ReadZippedDecoder):
def decode_event(sel... |
from __future__ import unicode_literals, absolute_import
import unittest
from copy import deepcopy
try:
from unittest.mock import Mock, patch, ANY
except ImportError:
from mock import Mock, patch, ANY
from django.db import models, IntegrityError
from django.core.exceptions import (ImproperlyConfigured,
... |
def sum_even_fib(limit):
fib_list = [1, 2]
even_fib_list = [2]
next_fib = fib_list[-1] + fib_list[-2]
while(next_fib <= limit):
next_fib = fib_list[-1] + fib_list[-2]
fib_list.append(next_fib)
if next_fib % 2 == 0:
even_fib_list.append(next_fib)
return sum(even_fi... |
from unittest import expectedFailure
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class GlobalsTests(TranspileTestCase):
@expectedFailure
def test_simple(self):
self.assertCodeExecution("""
print("There are %s globals" % len(globals()))
x = 1
y = 'z... |
"""
Django accounts management made easy.
"""
default_app_config = 'userena.apps.UserenaConfig'
VERSION = (1, 5, 1)
__version__ = '.'.join((str(each) for each in VERSION[:4]))
def get_version():
"""
Returns string with digit parts only as version.
"""
return '.'.join((str(each) for each in VERSION[:3])) |
import tomviz.operators
NUMBER_OF_CHUNKS = 10
class InvertOperator(tomviz.operators.CancelableOperator):
def transform(self, dataset):
import numpy as np
self.progress.maximum = NUMBER_OF_CHUNKS
scalars = dataset.active_scalars
if scalars is None:
raise RuntimeError("No s... |
import numpy as np
import pytest
from pandas import Int64Index, Interval, IntervalIndex
import pandas.util.testing as tm
pytestmark = pytest.mark.skip(reason="new indexing tests for issue 16316")
class TestIntervalIndex:
@pytest.mark.parametrize("side", ['right', 'left', 'both', 'neither'])
def test_get_loc_int... |
from base import BabeBase, StreamHeader, StreamFooter, StreamMeta
import re
def mapTo(stream, function, insert_fields=None, fields=None, typename=None):
"""
Apply a function to a stream. The function receives as input a named tuple.
if insert_columns is not None, a new stream type is generated
with... |
from django_dbdev.backends.mysql import DBSETTINGS
from .base import *
DATABASES = {
'default': DBSETTINGS
} |
import versioneer
from setuptools import find_packages, setup
NAME = "pydata-google-auth"
cmdclass = versioneer.get_cmdclass()
def readme():
with open("README.rst") as f:
return f.read()
INSTALL_REQUIRES = [
"setuptools",
"google-auth >=1.25.0, <2.0dev; python_version<'3.0'",
"google-auth >=1.2... |
from openstack.api import base
class Tenant(base.Resource):
def __repr__(self):
return "<Tenant %s>" % self._info
@property
def id(self):
return self._info['id']
@property
def description(self):
return self._info['description']
@property
def enabled(self):
ret... |
"""
flaskbb.message.forms
~~~~~~~~~~~~~~~~~~~~~
It provides the forms that are needed for the message views.
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
from flask_login import current_user
from flask_wtf import Form
from wtforms import StringField, Tex... |
from httplib import OK
from unittest import SkipTest
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth.models import User, Group, Permission
from pycon.tests.factories import PyConTalkProposalFactory, PyConTu... |
DEFAULT_REGION = 'eu-west-1'
DEFAULT_ZONE = 'a'
ami = {'ubuntu-12.04-lts': 'ami-c1aaabb5'}
def make_launch_config(description,
instance_type,
ami):
return {'description': description,
# Ami ID (E.g.: ami-fb665f8f)
'ami': ami,
# One of... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Product.long_description'
db.delete_column('shop_product', 'long_description')
# Deleting field 'Product.shor... |
"""
"""
import asyncio
from .registry import get_driver
class Proxy:
def __getattr__(self, name):
if name == '__venusian_callbacks__': # Venusian scan must ignore me
raise AttributeError(name)
return _Method(name)
class _Method:
# some magic to bind an XML-RPC method to an RPC serve... |
from PySide import QtCore, QtGui, QtOpenGL
from vsml import vsml
from world import *
from actor import *
try:
from pyglet.gl import *
except ImportError:
print("Need pyglet for OpenGL rendering")
empty_messages={ 'key_pressed':None,
'mouse_pressed':None,
'mouse_position':... |
import numpy as np
from detan.detan import AssignmentAnnealing, assignment_iteration
distances = np.asarray((
(0.0 , 2.1 , 0.10, 0.85, 0.2 , 0.78),
(0.0 , 0.0 , 0.92, 0.05, 1.01, 0.01),
(0.0 , 0.0 , 0.0 , 2.02, 0.15, 0.99),
(0.0 , 0.0 , 0.0 , 0.0 , 1.30, 0.31),
(0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 1.05),
... |
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
- Use sentry for error logging
'''
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.u... |
import pathlib
from unittest import TestCase
from ..transferfunction import tf
from tcontrol.rlocus import rlocus
import numpy as np
path = pathlib.Path('.')
if 'tests' not in str(path.cwd()):
path = (path / 'tcontrol/tests/rlocus_result.npz').resolve()
else:
path = (path / 'rlocus_result.npz').resolve()
class ... |
from porcupy.compiler import compile as compile_
def test_pass():
assert compile_('pass') == ''
def test_pass_if():
assert (compile_('x = 11\n'
'if x > 0: pass') == 'p1z 11')
assert (compile_('x = 11\n'
'if x > 0: x += 1\n'
'else: pass') ==
... |
"""Simple wrapper over scipy integration in a spirit of derivative.py
>>> func1 = lambda x : x*x
>>> print integral ( func1 , 0 , 1 )
>>> func2 = lambda x,y: x*x+y*y
>>> print integral2 ( func2 , 0 , 1 , 0 , 2 )
>>> func3 = lambda x,y,z: x*x+y*y+z*z
>>> print integral3 ( func3 , 0 , 1 , 0 , 2 , 0 , 3 )
there are also ... |
"""
flask_oauthlib.provider.oauth2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implemnts OAuth2 provider support for Flask.
:copyright: (c) 2013 - 2014 by Hsiaoming Yang.
"""
import os
import logging
import datetime
from functools import wraps
from flask import request, url_for, jsonify, json
from flask import redir... |
from collections import OrderedDict
import re
from pymel.core import cmds, delete, ls, nt, sets, shadingNode
from .._add import path
try:
basestring
except NameError:
basestring = str
__all__ = [
'namedColors',
'parseStr',
'rgbToHsv',
'hsvToRgb',
'createShader',
'listControlShaders',
... |
from os.path import join
from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
(r'^static/(?P<path>.*)$', ... |
from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm
env.hosts = ['horus.davidbrenneman.com']
def test():
with settings(warn_only=True):
result = local('python dontpanic_tests.py', capture=True)
if result.failed and not confirm("Tests failed. Continue... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'Folder', fields ['name', 'parent']
db.delete_unique('filer_folder', ['name', 'parent_id'])
def bac... |
__doc__ = '''
Testing when various basic commands meet bad parameters.
'''
__author__ = "Yao Yue <yao@twitter.com>"
__version__ = "0.1-1.45"
import os
import time
import sys
try:
from lib import memcache
except ImportError:
print "Check your sys.path setting to include lib/memcache.py."
sys.exit()
try:
... |
import unittest
import mock
from catapult_base import dependency_manager
from catapult_base import cloud_storage
from catapult_base.dependency_manager import exceptions
class DependencyManagerTest(unittest.TestCase):
def setUp(self):
self.local_paths = ['path0', 'path1', 'path2']
self.cloud_storage_info = dep... |
"""Test the infos classes used to stored information about instruments.
"""
import os
import pytest
from configobj import ConfigObj
from exopy.instruments.infos import (DriverInfos, InstrumentModelInfos,
SeriesInfos, ManufacturerInfos,
Manufactur... |
"""Various miscellaneous functions"""
__author__ = "Adam Simpkin, Felix Simkovic & Jens Thomas"
__date__ = "05 May 2017"
__version__ = "1.0"
import glob
import json
import logging
import math
import os
import pandas as pd
import shutil
import tempfile
from simbad.db import convert_pdb_to_dat
from simbad.util.pdb_util i... |
"""With this string:
'monty pythons flying circus'
Create a function that returns a sorted string with no duplicate characters
(keep any whitespace):
Example: ' cfghilmnoprstuy'
Create a function that returns the words in reverse order:
Example: ['circus', 'flying', 'pythons', 'monty']
Create a function that returns a ... |
from setuptools import setup
setup(name='chordgenerator',
version='0.9',
description='A Django app for enumerating chords in a scale.',
author='Peter Murphy',
author_email='peterkmurphy@gmail.com',
url='http://pypi.python.org/pypi/chordgenerator/',
packages=['chordgenerator', 'chordgenerator.tem... |
from GPy.core.model import Model
from .parameterization import Param, Parameterized
from . import parameterization
from .gp import GP
from .svgp import SVGP
from .sparse_gp import SparseGP
from .mapping import *
def randomize(self, rand_gen=None, *args, **kwargs):
"""
Randomize the model.
Make this draw fro... |
"""
firebat-overlord.forms
~~~~~~~~~~~~~~~~~~~~~~
Main app forms.
"""
from flask.ext.wtf import Form, TextField, PasswordField, validators
from models import User
class LoginForm(Form):
username = TextField('Username', [validators.Required()])
password = PasswordField('Password', [validators.Required()])
de... |
"""Unit tests for cros_mark_android_as_stable.py."""
from __future__ import print_function
import os
import sys
import mock
from six.moves import zip as izip
from chromite.lib import constants
from chromite.lib import cros_build_lib
from chromite.lib import cros_logging as logging
from chromite.lib import cros_test_lib... |
import unittest
import os
import sys
import commands
import comm
class TestSampleAppFunctions(unittest.TestCase):
def test_uninstall(self):
comm.setUp()
app_name = "Memorygame"
cmdfind = "adb -s " + comm.device + \
" shell pm list packages |grep org.xwalk.%s" % (app_name.lower())... |
import django
if django.VERSION >= (1, 5):
from django.contrib.auth import get_user_model
User = get_user_model()
else:
from django.contrib.auth.models import User |
from core import perf_benchmark
from core import platforms
from telemetry import benchmark
from telemetry import story
from telemetry.timeline import chrome_trace_category_filter
from telemetry.timeline import chrome_trace_config
from telemetry.web_perf import timeline_based_measurement
import page_sets
class _MediaBen... |
import os.path as op
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_equal, assert_allclose)
import pytest
from scipy import linalg
import scipy.io
import mne
from mne import pick_types, Epochs, find_events, read_events
from mne.datasets.tes... |
from tests.common import DummyPostData
from wtforms.fields import StringField
from wtforms.form import Form
class F(Form):
a = StringField()
def test_string_field():
form = F()
assert form.a.data is None
assert form.a() == """<input id="a" name="a" type="text" value="">"""
form = F(DummyPostData(a=[... |
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
module_path = os.path.join(os.path.dirname(__file__), 'flask_siilo.py')
version_line = [line for line in open(mod... |
"""Keep in mind throughout those tests that the mails from demo.demo_app.mails
are automatically registered, and serve as fixture."""
from __future__ import unicode_literals
from django.conf import settings
from django.test import TestCase
from .. import factory
from ..exceptions import MailFactoryError
from ..forms im... |
"""Defines fixtures available to all tests."""
import os
import pytest
from webtest import TestApp
from enma.settings import TestConfig
from enma.app import create_app
from enma.database import db as _db
from tests.test_enma.factories import UserFactory
from enma.user.models import Role
from copy import deepcopy
@pytes... |
from __future__ import unicode_literals
import iso639
from dash.utils import chunks
from django.db import migrations, transaction
from django.db.models import Q
migration_lang_cache = {}
MIGRATION_OVERRIDES = {
"Africa/Lagos:cpe": "pcm",
"Africa/Monrovia:cpe": "lir",
"America/Managua:cpe": "bzk",
"*:mkh... |
from __future__ import absolute_import
import logging
import six
from django.conf import settings
logger = logging.getLogger(__name__)
geoip_path_mmdb = getattr(settings, "GEOIP_PATH_MMDB", None)
def geo_by_addr(ip):
pass
rust_geoip = None
def _init_geoip():
global geo_by_addr
try:
import maxminddb
... |
from django.core.management.base import BaseCommand, CommandError
import os
from dimagi.utils.post import post_file
class Command(BaseCommand):
help = "Submits forms to a url."
args = ""
label = ""
def handle(self, *args, **options):
if len(args) < 2:
raise CommandError('Usage: manag... |
import hashlib
import os
def informacion(archivo):
info = {}
sha1 = hashlib.sha1()
f = open(archivo, "r")
for line in f.readlines():
sha1.update(line)
f.close()
info["sha1"] = sha1.hexdigest()
info["size"] = str(os.path.getsize(archivo)) + " bytes"
return info |
"""Generic utils."""
import codecs
import cStringIO
import datetime
import logging
import os
import pipes
import platform
import Queue
import re
import stat
import subprocess
import sys
import tempfile
import threading
import time
import urlparse
import subprocess2
RETRY_MAX = 3
RETRY_INITIAL_SLEEP = 0.5
START = dateti... |
import os
import numpy as np
import nibabel as nb
from CPAC.pipeline import nipype_pipeline_engine as pe
import nipype.interfaces.utility as util
from CPAC.utils.interfaces.function import Function
from nipype.interfaces.afni.base import (AFNICommand, AFNICommandInputSpec)
from nipype.interfaces.base import (TraitedSpe... |
'''
Settings shared between events_receiver.py and caravan_wsgi.py,
mainly for being able to retrieve a report associated with a given scenario
'''
events_folder_name = "local_events"
events_folder_location = "./" |
"""Regression test for dnsrmdnsserver
Make sure you are running this against a database that can be destroyed.
DO NOT EVER RUN THIS TEST AGAINST A PRODUCTION DATABASE.
"""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import os
import sys
import socket
import thread... |
import sys
import os
import pytoken
def doit(fname):
lexer = pytoken.lexer()
lexer.add_pattern("[0123456789]", 1)
lexer.add_pattern("[abcdefghijklmnopqrstuvwxyz]", 2)
lexer.add_pattern("[ABCDEFGHIJKLMNOPQRSTUVWXYZ]", 3)
lexer.add_pattern(" ", None)
lexer.add_pattern("\n", None)
lexer.compil... |
def phenoVein_getCurrentVersion():
return "r163" |
import atexit
import collections
import contextlib
import ctypes
import logging
import os
import platform
import re
import socket
import struct
import subprocess
import sys
import time
import zipfile
from catapult_base import cloud_storage # pylint: disable=import-error
from telemetry.core import exceptions
from telem... |
import mimetypes
import sys
import typing as t
import warnings
from collections import defaultdict
from datetime import datetime
from datetime import timedelta
from http.cookiejar import CookieJar
from io import BytesIO
from itertools import chain
from random import random
from tempfile import TemporaryFile
from time i... |
from django.db import models
from model_utils.models import TimeStampedModel
class WebsiteScraperConfig(TimeStampedModel):
SELECTOR_STYLE_CSS = 'css'
SELECTOR_STYLE_XPATH = 'xpath'
SELECTOR_STYLES = ((SELECTOR_STYLE_CSS, SELECTOR_STYLE_CSS), (SELECTOR_STYLE_XPATH, SELECTOR_STYLE_XPATH))
domain = models.... |
from datetime import datetime, timedelta
from django import http
from django.conf import settings
from django.core.exceptions import PermissionDenied
import mock
import pytest
from nose.tools import eq_
import amo.tests
from amo import decorators, get_user, set_user
from amo.urlresolvers import reverse
from users.model... |
from django.forms.fields import BooleanField
from django.utils.translation import ugettext_lazy as _
import mock
from nose.tools import eq_, ok_
from test_utils import RequestFactory
import amo
import amo.tests
from devhub.models import AppLog
from editors.models import RereviewQueue
from files.models import FileUpload... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.