content stringlengths 4 20k |
|---|
""" This module defines our local database model. """
from sqlalchemy import Column, ForeignKey
from sqlalchemy.types import Integer, Float, String, Boolean, Enum
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base, synonym_for
from sqlalchemy import c... |
import sys
import string
import urlparse
import urllib
from StringIO import StringIO
import utils
from constants import COLLECTION, OBJECT, DAV_PROPS
from constants import RT_ALLPROP, RT_PROPNAME, RT_PROP
from errors import *
from utils import create_treelist, quote_uri, gen_estring, make_xmlresponse
from davcmd impor... |
"""
Read test or example data
"""
from __future__ import division, print_function, absolute_import
import sys
import json
from nibabel import load
from os.path import join as pjoin, dirname
if sys.version_info[0] < 3:
import cPickle
def loads_compat(bytes):
return cPickle.loads(bytes)
else: # Pyth... |
import unittest
from datetime import timedelta, datetime
from t77_date import parse_timedelta
class ParseTimedeltaTestCase(unittest.TestCase):
def test_none(self):
"""parse_timedelta return None for None input"""
self.assertIsNone(parse_timedelta(None))
def test_not_str(self):
"""par... |
__author__ = 'Sol'
from past.builtins import xrange
import numpy as np
import json
from ..devices import Computer
from collections import OrderedDict
from ..errors import print2err, printExceptionDetailsToStdErr
getTime = Computer.getTime
# Experiment Variable (IV and DV) Condition Management
#
class ConditionSet... |
#!/usr/bin/env
from setuptools import setup, find_packages
from ghizmo import main
setup(
name="ghizmo",
version=main.VERSION,
python_requires='>=3',
packages=find_packages(),
author="Joshua Levy",
license="Apache 2",
url="https://github.com/jlevy/ghizmo",
# Pinning uritemplate dep; see https://github... |
#!/Python27/python
# -*- coding: UTF-8 -*-
from os import path
import os
import matplotlib
matplotlib.use('Agg')
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import pandas as pd
import time
start_time = time.time()
d = path.dirname(__file__)
if not path.exists(d+"/WordClo... |
import math
import numpy
from chainer import functions
from chainer import testing
@testing.parameterize(*testing.product({
'shape': [(3, 2), ()],
'dtype': [numpy.float16, numpy.float32, numpy.float64],
}))
@testing.fix_random()
@testing.inject_backend_tests(
None,
# CPU tests
[
{},
... |
import cPickle
from openquake.commonlib import sap
def make_figure(output_key, losses, poes):
"""
Plot a loss curve
"""
# NB: matplotlib is imported inside, otherwise nosetest would fail in an
# installation without matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fi... |
'''
JSON related utilities.
This module provides a few things:
1) A handy function for getting an object down to something that can be
JSON serialized. See to_primitive().
2) Wrappers around loads() and dumps(). The dumps() wrapper will
automatically use to_primitive() for you if needed.
3) Th... |
""" AmazonDriver for Compute
based on BaseDriver for Compute Resource
"""
import mock
from botocore.exceptions import ClientError
from calplus.tests import base
from calplus.v1.compute.drivers.amazon import AmazonDriver
fake_config_driver = {
'driver_name': 'AMAZON1',
'aws_access_key_id': 'fake_id',
... |
from openerp import api, fields, models
class StockMove(models.Model):
_inherit = "stock.move"
invoice_line_ids = fields.Many2many(
comodel_name='account.invoice.line', string='Invoice Lines',
copy=False, readonly=True)
# Provide this field for backwards compatibility
invoice_line_id ... |
from datetime import timedelta
from decimal import Decimal
from io import StringIO
from csv import DictReader
from django.test import TestCase
from django.test import Client as HttpClient
from django.contrib.auth.models import User
from django.core.management import call_command
from faker import Factory
from conf.m... |
"""The Spot object definition and and some predefined spots, like registers."""
class Spot:
"""Spot in the machine where an IL value can be.
spot_type (enum) - One of the values below describing the general type of
spot this is.
detail - Additional information about this spot. The this attribute's ty... |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from rapidsms.messages import IncomingMessage, OutgoingMessage
from rapidsms.tests.harness import RapidTest
from ..app import MessageLogApp
from ..models import Message
__all__ = ['MessageLogAppTestBase', 'IncomingMessageLogAppTest',
'OutgoingMessageLogAp... |
from django.contrib.auth.models import User
from fsm.fsm_base import FSMStack
from fsm.models import (
FSM,
FSMNode,
FSMState,
ActivityLog,
JSONBlobMixin
)
from ct.models import (
Course,
Unit,
Lesson,
UnitLesson,
Response,
DONE_STATUS
)
from ct.tests.integrate import (
... |
#!/usr/bin/env python
'''
OWASP ZSC
https://www.owasp.org/index.php/OWASP_ZSC_Tool_Project
https://github.com/zscproject/OWASP-ZSC
http://api.z3r0d4y.com/
https://groups.google.com/d/forum/owasp-zsc [ owasp-zsc[at]googlegroups[dot]com ]
'''
import random
import binascii
import string
from core.compatible import version... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the OXML plugin."""
import unittest
from plaso.lib import definitions
from plaso.parsers.czip_plugins import oxml
from tests.parsers.czip_plugins import test_lib
class OXMLTest(test_lib.CompoundZIPPluginTestCase):
"""Tests for the OXML plugin."""
# p... |
"""
This module contains Helper constructs
This module is a part of the program Kupfer, see the main program file for
more information.
"""
from gi.repository import Gio, GLib
from kupfer import pretty
class PicklingHelperMixin (object):
""" This pickling helper will define __getstate__/__setstate__
acting ... |
# -*- coding: utf-8 -*-
from sympy import sympify, Symbol, S, sqrt
from sympy.physics.units.dimensions import Dimension
from sympy.physics.units.dimensions import length, time
from sympy.utilities.pytest import raises
def test_definition():
assert length.get_dimensional_dependencies() == {"length": 1}
assert... |
from django.conf.urls import patterns, include, url
from userinfo import views
urlpatterns = patterns('',
url(r'^$', 'userinfo.views.profile', name = 'profile'),
url(r'^settings/$', 'userinfo.views.settings', name = 'settings'),
url(r'^settings/changePassword/$', 'userinfo.views.changePassword', name = '... |
#!/usr/bin/env python3
class Decoder:
# In a class method, always list self as first parameter
def __init__(self):
print()
def decode(self, aString, aCipher):
aString = aString.lower()
decodedString = ''
for aChar in aString:
decodedString = decodedString + aCi... |
from distutils.core import setup
import os
try:
import autotest.common as common
except ImportError:
import common
from autotest.client.shared import version
# Mostly needed when called one level up
if os.path.isdir('installation_support'):
pkg_dir = 'installation_support'
else:
pkg_dir = '.'
def ge... |
from __future__ import division, print_function
from .doa import *
class SRP(DOA):
"""
Class to apply Steered Response Power (SRP) direction-of-arrival (DoA) for
a particular microphone array.
.. note:: Run locate_source() to apply the SRP-PHAT algorithm.
Parameters
----------
L: numpy... |
from __future__ import absolute_import, print_function
__all__ = ["OAuth2Provider", "OAuth2CallbackView", "OAuth2LoginView"]
import logging
from six.moves.urllib.parse import parse_qsl, urlencode
from uuid import uuid4
from time import time
from requests.exceptions import SSLError
from simplejson import JSONDecodeErr... |
from spack import *
class Mozjs(AutotoolsPackage):
"""SpiderMonkey is Mozilla's JavaScript engine written in C/C++.
It is used in various Mozilla products, including Firefox, and is
available under the MPL2."""
homepage = "https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey"
v... |
# @filename:hydrogen_bond_interaction.py
# @usage:
# @author: AbhiramG
# @description: 1. Gives information about all co crystal ligands present in receptor pdb_file
# 2. extracts each co-crystal ligand from pdb filename
# 3. Gives the hydrogen bond interactions with ligand and pdb and
# 4. writes interaction in ... |
# -*- coding: utf-8 -*-
# File: concurrency.py
import multiprocessing
import numpy as np
from concurrent.futures import Future
import tensorflow as tf
from six.moves import queue, range
from ..compat import tfv1
from ..tfutils.model_utils import describe_trainable_vars
from ..utils import logger
from ..utils.concurr... |
import timeit
from functools import reduce
import numpy as np
from numpy import float_
import numpy.core.fromnumeric as fromnumeric
from numpy.testing import build_err_msg
# Fixme: this does not look right.
np.seterr(all='ignore')
pi = np.pi
class ModuleTester:
def __init__(self, module):
self.module ... |
from collections import namedtuple
from functools import partial
ARN = namedtuple("ARN", ["region", "account", "function_name", "version"])
LAYER_ARN = namedtuple("LAYER_ARN", ["region", "account", "layer_name", "version"])
def make_arn(resource_type, region, account, name):
return "arn:aws:lambda:{0}:{1}:{2}:{3... |
import os
from django.utils.translation import ugettext as _
from django.utils.translation import get_language
from skepticalsciencewebsite.settings import SENDFILE_ROOT
from pyinvoice.models import Item, InvoiceInfo, ServiceProviderInfo, ClientInfo
from pyinvoice.templates import SimpleInvoice
from pyinvoice.constants... |
# -*- coding: utf-8 -*-
"""Provides audience segment object."""
from __future__ import absolute_import
from .. import t1types
from ..entity import Entity
class AudienceSegment(Entity):
"""Audience segment entity object"""
collection = 'audience_segments'
resource = 'audience_segment'
_relations = {
... |
import os
import logging
import struct
import threading
import sys
import random
import binascii
import time
import socket
import zlib
from eventlet.green import zmq
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller import dpset
from ryu.controller.handler import MAIN_DISPATCHER,... |
import sys
import traceback
def test_1(environment, start_response):
try:
start_response('200', [])
raise Exception
yield b'200 OK'
except:
# We get to start again as long as no data has been yielded
start_response('500', [], sys.exc_info())
yield b'500 Error'
d... |
"""Provisions Android devices with settings required for bots.
Usage:
./provision_devices.py [-d <device serial number>]
"""
import argparse
import datetime
import json
import logging
import os
import posixpath
import re
import subprocess
import sys
import time
from devil.android import battery_utils
from devil.an... |
from schedules_tools.schedule_handlers import ScheduleHandlerBase
import logging
from lxml.html import etree
log = logging.getLogger(__name__)
css = """
a[href=""] {display:none}
table.schedule {
border-collapse: collapse;
}
table.schedule th, table.schedule td {
border: 2px solid black;
padding: 3px 5... |
# Very rudimentary test of threading module
import test.support
from test.support import verbose
import random
import re
import sys
import threading
import _thread
import time
import unittest
import weakref
# A trivial mutable counter.
class Counter(object):
def __init__(self):
self.value = 0
def inc(... |
## False: Turns logging off. - True[default]: Uses default logging setup. -
## Dictionay is passed into the python logging.config.dictConfig()
LOGGING = True
## True: intelligent classes are created based off of the RDF vocabulary
## definitions and custom defintions. - False: only a basic RDF class is used.
## *Star... |
import logging
import numpy
import zmq
from numpy.lib.format import header_data_from_array_1_0
from fuel.utils import buffer_
logger = logging.getLogger(__name__)
def send_arrays(socket, arrays, stop=False):
"""Send NumPy arrays using the buffer interface and some metadata.
Parameters
----------
s... |
from iptest.assert_util import *
import time
def test_strftime():
t = time.localtime()
x = time.strftime('%x %X', t)
Assert(len(x) > 3)
x1 = time.strftime('%x', t)
x2 = time.strftime('%X', t)
Assert(len(x1) > 1)
Assert(len(x2) > 1)
AreEqual(x, x1 + ' ' + x2)
... |
from hpfortify.model.users import (
PostUserRequest,
PostUserResponse,
PutUserRequest,
User,
UserListResponse,
)
from hpfortify.tests.test_util import assert_from_and_to_dict
POST_USER_REQUEST_DICT = {
"userName": "user1",
"firstName": "user1 first name",
"lastName": "user1 second name"... |
from __future__ import unicode_literals
import frappe
import unittest
from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
from erpnext.stock.get_item_details import get_item_details
from frappe.test_runner import make_test_objects
def test_create_test_data():
frappe.set_user("Administra... |
# -*- coding: utf-8 -*-
"""Test add_text bot module."""
#
# (C) Pywikibot team, 2016
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
import pywikibot
from scripts.add_text import add_text
from tests.aspects import unittest, TestCase
class TestAdding(Te... |
"""
Routines for configuring Tacker
"""
import os
import uuid
from oslo_config import cfg
from oslo_db import options as db_options
from oslo_log import log as logging
import oslo_messaging
from paste import deploy
from tacker.common import utils
from tacker import version
LOG = logging.getLogger(__name__)
core_o... |
import bpy
from bpy.props import StringProperty, EnumProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import flatten_data, map_recursive
from sverchok.utils.curve.core import SvCurve
from sverchok.utils.surface.core import SvSurface
from sverchok.utils.logging import debug
from... |
# http://hacktheuniverse.github.io/star-api/
from bowshock.helpers import dispatch_http_get
def stars():
'''
This endpoint gets you a list of all stars in json
'''
base_url = "http://star-api.herokuapp.com/api/v1/stars"
return dispatch_http_get(base_url)
def search_star(star):
'''
It ... |
import ConfigParser
import os
import sys
import install_venv_common as install_venv # flake8: noqa
def print_help(project, venv, root):
help = """
%(project)s development environment setup is complete.
%(project)s development uses virtualenv to track and manage Python
dependencies while in developm... |
"""Functional tests of caching different methods."""
from __future__ import print_function
from helpers import tf_cfg, chains
from testers import functional
__author__ = 'Tempesta Technologies, Inc.'
__copyright__ = 'Copyright (C) 2017 Tempesta Technologies, Inc.'
__license__ = 'GPL2'
class TestCacheMethods(functio... |
from __future__ import unicode_literals, division
import math
from sorl.thumbnail.engines.base import EngineBase
from sorl.thumbnail.compat import BufferIO
try:
from PIL import Image, ImageFile, ImageDraw, ImageFilter
except ImportError:
import Image
import ImageFile
import ImageDraw
def round_corne... |
from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
import os
import re
import sys
import six
from docker.utils.ports import split_port
from jsonschema import Draft4Validator
from jsonschema import FormatChecker
from jsonschema import RefResolver
from jsonschema i... |
from gi.repository import Gtk
from gi.repository import Gdk
class VolumeScale():
""" Volume scale/slider """
def __init__(self, main_instance):
""" Constructor """
self.main = main_instance
rval,self.screen,self.rectangle,self.orientation = self.main.get_geometry()
self.win = N... |
"""HSL class."""
import re
from ...spaces import hsl as generic
from ...spaces import _parse
from ... import util
class HSL(generic.HSL):
"""HSL class."""
DEF_VALUE = "hsl(0 0% 0% / 1)"
START = re.compile(r'(?i)\bhsla?\(')
MATCH = re.compile(
r"""(?xi)
\bhsla?\(\s*
(?:
... |
'''
Created on Jun 14, 2011
@author: lebleu1
'''
from sccp.sccpmessage import SCCPMessage
from sccp.sccpmessagetype import SCCPMessageType
from struct import pack
from network.ipAddress import IpAddress
class SCCPRegister(SCCPMessage):
'''
sccp register message
'''
TelecasterBus=0x08
MAXSTREAMS=0
... |
"""Creates a rule-based user list.
The list will be defined by an expression rule for users who have visited two
different pages of a website.
"""
import argparse
import sys
from uuid import uuid4
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
URL_... |
import os
import mock
from oslo_config import cfg
from tacker.common import config # noqa
from tacker.tests import base
class ConfigurationTest(base.BaseTestCase):
def test_defaults(self):
self.assertEqual('0.0.0.0', cfg.CONF.bind_host)
self.assertEqual(9890, cfg.CONF.bind_port)
self.a... |
# Brought to you by Jeremy Rubin, 2013
# Import all main libs
from Imports import *
# Import all handlers/models
from handlers_list import *
# Import Routes
import routes
class Application(tornado.web.Application):
def __init__(self):
handlers = routes.handlers
if config["devmode"]: handlers.appe... |
#!/usr/bin/env python
'''
Multitarget planar tracking
==================
Example of using features2d framework for interactive video homography matching.
ORB features and FLANN matcher are used. This sample provides PlaneTracker class
and an example of its usage.
video: http://www.youtube.com/watch?v=pzVbhxx6aog
Us... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('media_tree', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='filenode',
option... |
# coding=utf-8
"""event.py - Event handling (keyboard, mouse, etc.) for the main window.
Logically this isn't really a separate module from main.py, but it is
given its own file for the sake of readability.
"""
from __future__ import absolute_import
import urllib
import gtk
from src import cursor
from src import pr... |
# -*- coding: UTF-8 -*-
from twisted.words.protocols.jabber.jid import JID
from twisted.words.xish import domish
from wokkel.xmppim import MessageProtocol, AvailablePresence
from wokkel import client, xmppim
from twisted.internet.protocol import Protocol, ReconnectingClientFactory
import json
import xml.etree.ElementTr... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt')) as f:
CHANGES = f.read()
requires = [
'pyramid',
'pyramid_chameleon',
'pyramid_d... |
from __future__ import unicode_literals
import logging
import random
import nose
from nose.tools import raises
from xvalidator import validators, InitKeyStore, KeyName, Stores
from xvalidator.element import Element
from xvalidator.schemas import Choice, ElementSchema, SequenceSchema
from xvalidator import utils
__... |
from dataHolder import PageData, DataBox, TextData
from ocrfeeder.util.lib import debug
from ocrfeeder.util.configuration import ConfigurationManager
from xml.dom import minidom
import os.path
import re
import shutil
import tempfile
import zipfile
class ProjectSaver:
def __init__(self, pages_data):
self.... |
"""Copyright 2008 Orbitz WorldWide
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software... |
# coding: utf-8
"""Utility module for standardising python logging throughout SIP.
Usage:
```python
import logging
from sip_logging import init_logger
def foo():
log = logging.getLogger('sip.foo')
log.info('Hello')
if __name__ == '__main__':
init_logger()
```
"""
import time
import sys
import logging
... |
"""
Merges overlapping regions on same strand and chromosome.
Example input:
chr1 1000 2000 +
chr1 1500 2500 +
chr1 5000 6000 +
Example output:
chr1 1000 2500 +
chr1 5000 6000 +
Output is sorted.
"""
import sys
import os
from operator import itemgetter, attrgetter
input_file = sys.argv[1... |
"""
Service Support Emails
"""
from threading import Thread
from maker.identities.models import ContactValue
from maker.core.mail import BaseEmail
from django.utils.translation import ugettext as _
class EmailMessage(Thread):
"Email Message"
active = False
def __init__(self, message, tick... |
from Components.Converter.Converter import Converter
from Components.Element import cached
from Components.Converter.genre import getGenreStringLong, getGenreStringSub
from enigma import eEPGCache
class EventName(Converter, object):
NAME = 0
SHORT_DESCRIPTION = 1
EXTENDED_DESCRIPTION = 2
FULL_DESCRIPTION = 3
ID =... |
import types
import collections
import inspect
import json
from rest_framework import generics
from rest_framework import views as rest_views
try:
from rest_framework import viewsets
except ImportError:
viewsets = None
from rest_framework.compat import View
from rest_framework import serializers
from rest_fram... |
__author__ = "Microsoft Corporation <<EMAIL>>"
__version__ = "3.0.0.0"
import datetime
import os
import sys
import traceback
if sys.version_info[0] == 3:
def to_str(value):
return value.decode(sys.getfilesystemencoding())
def execfile(path, global_dict):
"""Execute a file"""
with open... |
from .mininode import *
from .blockstore import BlockStore, TxStore
from .util import p2p_port
'''
This is a tool for comparing two or more navcoinds to each other
using a script provided.
To use, create a class that implements get_tests(), and pass it in
as the test generator to TestManager. get_tests() should be a... |
'''
MMD functions implemented in tensorflow.
'''
from __future__ import division
import tensorflow as tf
from tf_ops import dot, sq_sum
_eps=1e-8
################################################################################
### Quadratic-time MMD with Gaussian RBF kernel
def _mix_rbf_kernel(X, Y, sigmas, wts=N... |
from __future__ import print_function
import unittest
import numpy as np
import sys
sys.path.append("../")
from op_test import OpTest
class TestSequenceExpand(OpTest):
def set_data(self):
x_data = np.random.uniform(0.1, 1, [3, 40]).astype('float64')
y_data = np.random.uniform(0.1, 1, [8, 1]).asty... |
from __future__ import absolute_import
import datetime
import mock
import unittest2
from st2client.utils.date import add_utc_tz
from st2client.utils.date import format_dt
from st2client.utils.date import format_isodate
from st2client.utils.date import format_isodate_for_user_timezone
class DateUtilsTestCase(unittes... |
from test_framework import GreenCoinTestFramework
from greencoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
def get_sub_array_from_array(object_array, to_match):
'''
Finds and returns a sub array from an array of arrays.
to_match should be a unique idetifier of a sub... |
import os
import time
import unittest
import pytest
from conans.model.ref import ConanFileReference, PackageReference
from conans.test.assets.cpp_test_files import cpp_hello_conan_files
from conans.test.utils.test_files import uncompress_packaged_files
from conans.test.utils.tools import TestClient, TestServer
@pyt... |
from __future__ import absolute_import
import gtk
from solfege import cfg
from solfege import gu
from solfege import soundcard
from solfege import utils
MAX_VOLUME = 127.0
class MidiInstrumentMenu(gtk.Menu):
def __init__(self, callback):
gtk.Menu.__init__(self)
self.m_callback = callback
... |
#!/usr/bin/env python3
try:
import eventlet
eventlet.monkey_patch()
print('Using eventlet')
create_thread_func = lambda f: f
start_thread_func = lambda f: eventlet.spawn(f)
except ImportError:
try:
import gevent
import gevent.monkey
gevent.monkey.patch_all()
pr... |
class View(dict):
"""A View contains the content displayed in the main window."""
def __init__(self, d=None):
"""
View constructor.
Keyword arguments:
d=None: Initial keys and values to initialize the view with.
Regardless of the value of d, keys 'songs', 'artists' an... |
import logging
from gettext import gettext as _
import uuid
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkX11
import dbus
import statvfs
import os
from sugar3.graphics.alert import ErrorAlert
from sugar3 import env
from sugar3.activity import activityfactory
from gi.reposit... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import forte
import pytest
def det(s):
return forte.det(s)
# for k, c in enumerate(s):
# if c == '+':
# d.create_alfa_bit(k)
# elif c == '-':
# d.create_beta_bit(k)
# elif c == '2':
# d.creat... |
import sklearn.preprocessing
from HPOlibConfigSpace.configuration_space import ConfigurationSpace
from HPOlibConfigSpace.hyperparameters import CategoricalHyperparameter, \
UniformIntegerHyperparameter
from ParamSklearn.components.base import \
ParamSklearnPreprocessingAlgorithm
from ParamSklearn.constants im... |
from django.db import transaction
from rest_framework import mixins
from rest_framework import status
from rest_framework import viewsets, serializers
from rest_framework.decorators import list_route
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from crowdsourcing.... |
"""Module for the GSoC profile page.
"""
from django.forms import fields
from django.core.urlresolvers import reverse
from soc.logic import cleaning
from soc.logic import dicts
from soc.models.user import User
from soc.views import forms
from soc.views import profile
from soc.views.helper import url_patterns
from s... |
from __future__ import print_function, division
from random import randint
import myhdl
from myhdl import Signal, intbv, instance, delay, StopSimulation, now
from rhea.system import Global, Clock, Reset
from rhea.cores.comm import prbs_generate
from rhea.cores.comm import prbs_check
from rhea.utils.test import run_t... |
import collections
import logging
from telemetry.core import exceptions
def DebuggerUrlToId(debugger_url):
return debugger_url.split('/')[-1]
class InspectorBackendList(collections.Sequence):
"""A dynamic sequence of active InspectorBackends."""
def __init__(self, browser_backend):
"""Constructor.
... |
import argparse
import copy
import sys
from rdkit import Chem
from rdkit.Chem import AllChem
def main(argv=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument("--smarts", type=argparse.FileType('r'), help="File with reactions in SMART format", required=True)
parser.add_argument("input", ... |
# -*- coding: utf-8 -*-
"""
sphinx.ext.coverage
~~~~~~~~~~~~~~~~~~~
Check Python modules and C API for coverage. Mostly written by Josip
Dzolonga for the Google Highly Open Participation contest.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for d... |
import logging
import traceback
from pygithub3 import Github
from pygithub3 import exceptions
from utils import file_utils
logging.basicConfig()
log = logging.getLogger('PARSE-PR')
log.setLevel(logging.INFO)
user = 'apache'
repo = 'drill'
gh = Github(user=user, repo=repo)
gh.repos.set_token(token='*****')
log.info... |
from compat import Request, urlopen, urlencode, urlparse, parse_qsl, quote
import oauth
from error import QWeiboError
from api import API
from utils import convert_to_utf8_bytes
import utils
class AuthHandler(object):
def authorize_request(self, url, method, headers, parameters):
raise NotImplementedErro... |
#! /usr/bin/env python
"""Generates test suite smartcard configuration from
connected readers and cards.
The generated configuration is store in local_config.py.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:<EMAIL>
This file is part of pyscard.
pyscard is fre... |
import subprocess
import sys
import os
import setup_util
from os.path import expanduser
home = expanduser("~")
def start(args, logfile, errfile):
setup_util.replace_text("php-yii2/app/index.php", "localhost", ""+ args.database_host +"")
setup_util.replace_text("php-yii2/deploy/nginx.conf", "root .*\/FrameworkBenc... |
# Tai Sakuma <<EMAIL>>
import os
import gzip
try:
import cPickle as pickle
except:
import pickle
##__________________________________________________________________||
class DatasetLoop:
def __init__(self, datasets, reader):
self.datasets = datasets
self.reader = reader
def __repr__(se... |
from __future__ import absolute_import
import contextlib
import json
import re
import threading
import six
from . import local_volume, trackable_state, viewer_config_state, viewer_state
from .json_utils import decode_json, encode_json, json_encoder_default
from .random_token import make_random_token
class LocalVol... |
from django.contrib import admin
from opencivicdata.models import vote as models
class VoteCountInline(admin.TabularInline):
model = models.VoteCount
fields = readonly_fields = ('option', 'value')
extra = 0
class PersonVoteInline(admin.TabularInline):
model = models.PersonVote
fields = readonly... |
# -*- coding: utf-8 -*-
"""These test the utils.py functions."""
import pytest
from hypothesis import given
from hypothesis.strategies import floats, integers
from natsort.ns_enum import ns
from natsort.utils import parse_number_or_none_factory
@pytest.mark.usefixtures("with_locale_en_us")
@pytest.mark.parametrize(
... |
# +-----------------------------------------------------------------------------+
# | ____ _ _ ____ _____ _ _ |
# | | _ \ _ _| \ | | _ \ |_ _|__ _ __ ___ _ __ | | __ _| |_ ___ |
# | | |_) | | | | \| | |_) |____| |/ _ \ '_ ` _ \| '_ \| |/ _`... |
from zun.common.validation import parameter_types
query_param_enable = {
'type': 'object',
'properties': {
'host': parameter_types.hostname,
'binary': {
'type': 'string', 'minLength': 1, 'maxLength': 255,
},
},
'additionalProperties': False
}
query_param_disable = {... |
import functools
import graphene
import operator
from django.db.models import Q
from graphene import relay
from graphene_django import DjangoObjectType, DjangoConnectionField
from graphene_django.debug import DjangoDebug
from django_prices.templatetags import prices_i18n
from ..product.models import (AttributeChoiceV... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# -- stdlib --
from functools import partial
import copy
import datetime
import json
import logging
import time
# -- third party --
from gevent.lock import RLock
import gevent
import gevent.pool
import redis
# -- own --
from state import State
import bac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.