content stringlengths 4 20k |
|---|
from openerp import models
class ResUsers(models.Model):
_inherit = 'res.users'
def _auth_oauth_validate(self, cr, uid, provider, access_token, context=None):
validation = super(ResUsers, self)._auth_oauth_validate(cr, uid, provider, access_token, context=None)
client_id = validation.get('cli... |
"""add is default to qos policies
Revision ID: 62c781cb6192
Revises: 2b42d90729da
Create Date: 2017-02-07 13:28:35.894357
"""
# revision identifiers, used by Alembic.
revision = '62c781cb6192'
down_revision = '2b42d90729da'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
... |
import re
import urllib
import urllib2
from binsearch import BinSearch
from nzbclub import NZBClub
from nzbindex import NZBIndex
from bs4 import BeautifulSoup
from sickbeard import logger, classes, show_name_helpers, db
from sickbeard.providers import generic
from sickbeard.common import Quality
from sickbeard.excepti... |
"""
Usage: (python) check_snp_match.py <snp_file> <ref_snp_file>
Prints the number and percentage match of snp_file SNPS to ref_snp_file SNPS.
"""
import sys
def build_snp_map(ref_file):
"""Build a map of RSIDs to genotype strings"""
ref_map = {}
for line in ref_file:
if line[0] == '#': # skip he... |
import json
import mock
import requests
import responses
import unittest2
# XXX: This file uses a lot of globals and shared state.
# We should definitely refactor this at some
# point since we have tests now.
import st2_handler as sensu_handler
__all__ = [
'SensuHandlerTestCase'
]
class FakeResponse(object):
... |
import abc
import asyncio
import os
import subprocess
import pyinotify
RSYNC = "rsync"
class EventHandler(metaclass=abc.ABCMeta):
'''
Base class for handling file events. Defines the abstract methods for
subclasses to handle specific cases of directory synchronization.
'''
def __call__(self, ev... |
"""Classes relating to widgets."""
__author__ = 'Sean Lip'
import copy
import logging
import os
from core.domain import obj_services
from core.domain import rule_domain
import feconf
import jinja_utils
import utils
import json
class AnswerHandler(object):
"""Value object for an answer event stream (e.g. submi... |
import os.path
import pep8
from optparse import make_option
from django.conf import settings
from . import set_option
class Reporter(object):
# TODO Remove, when drop django 1.7 support
option_list = (
make_option("--pep8-exclude",
dest="pep8-exclude",
help="ex... |
import sys
import os
import io
import threading
import traceback
import html
import json
import base64
import http
import multiprocessing
from PIL import Image
import numpy as np
# from .fserver import AsyncTCPServer, AsyncHTTPRequestHandler
from . import fserver
from ..fpbench import fpcparser, fpcast as ast
from .... |
"""
Support for Melnor RainCloud sprinkler water timer.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.raincloud/
"""
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.rain... |
from __future__ import annotations
import inspect
import logging
import re
from typing import (
Any,
Iterable,
TYPE_CHECKING,
Tuple,
)
from aiohttp import web
import aiohttp_cors
from aiojobs.aiohttp import atomic
import attr
import graphene
from graphql.execution.executors.asyncio import AsyncioExecu... |
import sys
import os
from io import StringIO
import textwrap
from distutils.core import Distribution
from distutils.command.build_ext import build_ext
from distutils import sysconfig
from distutils.tests.support import (TempdirManager, LoggingSilencer,
copy_xxmodule_c, fixup_build_... |
from __future__ import print_function
import aerospike
import sys
import time
import json
class UserService(object):
#client
def __init__(self, client):
self.client = client
def createUser(self):
print("\n********** Create User **********\n")
# /*********************///
#... |
from .sub_resource import SubResource
class Probe(SubResource):
"""A load balancer probe.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Resource ID.
:type id: str
:i... |
# -*- coding: utf-8 -*-
from lxml import etree
from openerp import api, fields, models
from openerp.osv.orm import setup_modifiers
class AssetModify(models.TransientModel):
_name = 'asset.modify'
_description = 'Modify Asset'
name = fields.Char(string='Reason', required=True)
method_number = fields.... |
import unicodedata
from models import Tweet, User
class TweetImporter(object):
def __init__(self, twitter_client):
self.twitter_client = twitter_client
def createUser(self, screen_name, is_bot=False):
api_user = self.twitter_client.user_shows(screen_name=screen_name)
user = User.creat... |
import numpy as np
import unittest
from numpy.testing import assert_allclose
from qspectra.simulate import utils
class FourierTransform(object):
def verify(self, t):
v, X = utils.fourier_transform(t, self.f(t))
self.assertTrue(utils.is_constant(np.diff(v), positive=True))
assert_allclose(... |
"""Create county_code table
Revision ID: aa10ae595d3e
Revises: ea02faf8bc7a
Create Date: 2017-06-20 12:21:46.165312
"""
# revision identifiers, used by Alembic.
revision = 'aa10ae595d3e'
down_revision = 'ea02faf8bc7a'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrad... |
"""
A generic optimizer class.
Author:
Ilias Bilionis
Date:
6/5/2014
"""
__all__ = ['Optimizer']
import math
import numpy as np
from copy import deepcopy
from scipy.optimize import minimize
from . import EvidenceLowerBound
class Optimizer(object):
"""
A generic optimizer object.
"""
... |
#!/usr/bin/env python
import sys
import readline
import argparse
from pprint import pprint
from parser import mopen
from functools import partial
import debug_passes as debug
banner = """mod-debug
------------------------------------
Type :help for for more information.
"""
help = """
-- Usage:
-- Commmands:
:s... |
from __future__ import absolute_import
import sys
from optparse import Option
import curtsies
import curtsies.window
import curtsies.terminal
Window = curtsies.window.Window
Terminal = curtsies.terminal.Terminal
from bpython.curtsiesfrontend.repl import Repl
from bpython.curtsiesfrontend.coderunner import SystemExit... |
"""arbin MS SQL Server csv data"""
from dateutil.parser import parse
import pandas as pd
from cellpy.readers.core import (
FileID,
Cell,
)
from cellpy.parameters.internal_settings import HeaderDict, get_headers_normal
from cellpy.readers.instruments.mixin import Loader
from cellpy import prms
DEBUG_MODE = pr... |
import os
import time
import py
from hscommon.testutil import pytest_funcarg__app
from ..model.currency import RatesDB, Currency
from ..model import currency as currency_module
global_monkeypatch = None
def pytest_configure(config):
def fake_initialize_db(path):
ratesdb = RatesDB(':memory:', async=False... |
'''
Created on 9. juli 2014
@author: perroe
'''
from ert_gui.models.connectors.run import BaseRunModel, SensitivityTargetCaseFormatModel
from ert_gui.models.connectors.run.sensitivity_study_parameters_model import SensitivityStudyParametersModel
#from ert_gui.models.mixins.run_model import ErtRunError
class Sensiti... |
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import requests
from beets import ui
from beets import dbcore
from beets import config
from beets import plugins
from beets.dbcore import types
API_URL = 'http://ws.audioscrobbler.com/2.0/'
class LastImportP... |
"""Complete either attribute names or file names.
Either on demand or after a user-selected delay after a key character,
pop up a list of candidates.
"""
import __main__
import keyword
import os
import string
import sys
# Two types of completions; defined here for autocomplete_w import below.
ATTRS, FILES = 0, 1
from... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4.QtGui import QIcon, QSystemTrayIcon, QApplication, QMenu, QAction,\
qApp, QMessageBox, QPushButton, QLineEdit, QLabel, QWidget
from PyQt4.QtCore import QString
from weather_client import WeatherClient
import weather_consts
import pdb
class Eventer:
''' Cuid... |
from .binary import *
from .elf import ELF
from .enum import Enum
class OatClassType(Enum):
kOatClassAllCompiled = 0
kOatClassSomeCompiled = 1
kOatClassNoneCompiled = 2
kOatClassMax = 3
class DexHeader(Structure):
_fields_ = [('magic', c_char*8),
('checksum', c_uint),
... |
class CurrentLocation:
"""contains the actual location determined for the mobile terminal"""
def __init__(self):
"""Default class constructor"""
self.latitude=0.0
self.longitude=0.0
self.altitude=0.0
self.accuracy=0.0
self.timestamp=None
def __init__(self, jsondict):
"""Class constructor that will ... |
from django.contrib import admin
from testapp import models, forms
class CharModelAdmin(admin.ModelAdmin):
list_display = ('id', 'field')
def function_does_nothing(modeladmin, request, queryset):
pass
class TestModelAdmin(admin.ModelAdmin):
actions = ['method_does_nothing', function_does_nothing]
... |
from flask import current_app
from udata import theme
from udata.frontend.views import ListView
from udata.i18n import I18nBlueprint
from udata.models import Post
from udata.sitemap import sitemap
from .permissions import PostEditPermission
blueprint = I18nBlueprint('posts', __name__, url_prefix='/posts')
class Po... |
"""Adds lifo price to product cost methods"""
import wizard
import product |
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import Adafruit_MCP9808.MCP9808 as MCP9808
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def to_farenheit(c):
""" Convert a celcius reading to farenheit """
return ((c * 9.0) / 5.0) + 32.0
PADDING = 2
# Raspberry ... |
#!/usr/bin/python
#---------------------------------------------------------------------------------------------------
# Update one assignments in the database using the unique task id. If there is no previous record
# that matches the query will fail.
#------------------------------------------------------------------... |
import os
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = [
# ("Your Name", "<EMAIL>"),
]
MANAGERS = ADMINS
## Pull in CloudFoundry's production settings
if 'VCAP_SERVICES'... |
from googlecloudsdk.third_party.appengine.api import validation
from googlecloudsdk.third_party.appengine.api import yaml_listener
from googlecloudsdk.third_party.appengine.api import yaml_builder
from googlecloudsdk.third_party.appengine.api import yaml_errors
import yaml
class _ObjectMapper(object):
"""Wrapper u... |
from seecrtest.timing import T
from unittest import TestCase
#from cq2utils.profileit import profile
from cqlparser import parseString, cql2string, CqlIdentityVisitor, CqlVisitor
from time import time
class SpeedTest(TestCase):
@staticmethod
def ridiculouslongquery():
with open('ridiculouslongquery.txt... |
import chainer
import numpy as np
from generate_anchors import generate_anchors
from utils.cython_bbox import bbox_overlaps
from fast_rcnn.bbox_transform import bbox_transform
class AnchorTarget(object):
"""
Args:
feat_stride (int):
"""
RPN_NEGATIVE_OVERLAP = 0.3
RPN_POSITIVE_OVERLAP = 0... |
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from localflavor.us.us_states import US_STATES
import re
class District(models.Model):
name = models.CharField(_("name"), max_length=250)
slug = models.SlugField(_("slug"), unique... |
# -*- coding: utf-8 -*-
import hashlib
import pycurl
from ..internal.MultiAccount import MultiAccount
from ..internal.misc import json
class LinkifierCom(MultiAccount):
__name__ = "LinkifierCom"
__type__ = "account"
__version__ = "0.01"
__status__ = "testing"
__description__ = """Linkifier.com ... |
# Create CSV files for network analysis with Gephi, using random sample
# data to create links between nodes representing categories of individuals
# (whether by location or by genre or similar). The code here was based on
# genre_network2.py
# Now modified to include indegree and eigenvector centrality in the output
... |
import time
import array
import struct
import usb.core
import usb.util
class StepperStatus:
def __init__(self, s):
(self.flags, dummy, self.pos) = struct.unpack("BBh", s)
class PCBWriter:
PCBWRITER_TIMEOUT = 100 # ms
REQ_SET_SPEED = 0x80
REQ_ENABLE_DEBUG_OUT = 0x81
REQ_SET_PERSIS... |
'''
Copyright (C) 2015 Constantin Tschuertz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it wil... |
from __future__ import absolute_import, division, print_function, unicode_literals
from pants.backend.jvm.subsystems.junit import JUnit
from pants.backend.jvm.targets.java_library import JavaLibrary
from pants.backend.jvm.targets.junit_tests import JUnitTests
from pants.build_graph.build_file_aliases import BuildFileA... |
from Bio.config.DBRegistry import CGIDB, DBGroup
from _support import *
embl_xembl_cgi = CGIDB(
name="embl-xembl-cgi",
doc="Query XEMBL for EMBL sequence data in XML format.",
cgi="http://www.ebi.ac.uk/cgi-bin/xembl/XEMBL.pl",
url="http://www.ebi.ac.uk/xembl/",
delay=5.0,
params=[("format", "Bs... |
"""Holds the constants for pretty printing histograms.xml."""
import os
import re
import sys
# Import the metrics/common module for pretty print xml.
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
import pretty_print_xml
# Desired order for tag and tag attributes. The *_ATTRIBUTE_ORDER maps... |
from wormhole.common import processutils
from wormhole.common import log
from wormhole import exception
from wormhole.common import utils
from wormhole.i18n import _
LOG = log.getLogger(__name__)
def teardown_network(container_id):
try:
output, err = utils.execute('ip', '-o', 'netns', 'list')
f... |
import argparse
import tempfile
import os
import signal
import shutil
import urllib
import urllib.request
import hashlib
import time
import socket
import json
import base64
from prepare_release_candidate import run
from http.client import HTTPConnection
DEFAULT_PLUGINS = ["analysis-icu",
"analysis-... |
import warnings
from nistats._utils import helpers
def _mock_args_for_testing_replace_parameter():
"""
:return: Creates mock deprecated & replacement parameters for use with
testing functions related to replace_parameters().
"""
mock_kwargs_with_deprecated_params_used = {
'unchanged_param... |
#!/bin/python
import os, subprocess
import logging
from autotest.client import test
from autotest.client.shared import error
class mlocate(test.test):
"""
Autotest module for testing basic functionality
of mlocate
@author Robert Paulsen, <EMAIL>
"""
version = 1
nfail = 0
path = ''
... |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.testing.decorators import image_comparison
@image_comparison(baseline_images=['table_zorder'],
extensions=['png'],
remove_text=True)
def test_zorder():
data = [[ 66386, 174296,],
[ 58230, 381139,... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# $File: hello.py
# In this tutorial, you will learn how to call Face ++ APIs and implement a
# simple App which could recognize a face image in 3 candidates.
# 在本教程中,您将了解到Face ++ API的基本调用方法,并实现一个简单的App,用以在3
# 张备选人脸图片中识别一个新的人脸图片。
# You need to register your App first, an... |
"""The tests for the integration sensor platform."""
from homeassistant.components.compensation.const import CONF_PRECISION, DOMAIN
from homeassistant.components.compensation.sensor import ATTR_COEFFICIENTS
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import (
ATTR_U... |
import time
__author__ = 'renhao.cui'
import json
import twitter
import properties
def oauth_login():
# credentials for OAuth
CONSUMER_KEY = properties.twitter_cred2['c_k']
CONSUMER_SECRET = properties.twitter_cred2['c_s']
OAUTH_TOKEN = properties.twitter_cred2['a_t']
OAUTH_TOKEN_SECRET = properti... |
"""
sphinxcontrib.httpdomain
~~~~~~~~~~~~~~~~~~~~~~~~
The HTTP domain for documenting RESTful HTTP APIs.
:copyright: Copyright 2011 by Hong Minhee
:license: BSD, see LICENSE for details.
"""
import re
from docutils import nodes
from docutils.parsers.rst.roles import set_classes
from pygments.l... |
import unittest
import os
import helper
from autosign.main import getIndex
class TestgetIndex(unittest.TestCase):
"""
tests the getIndex function in main module
"""
def setUp(self):
self.dire = os.path.dirname(__file__)
helper.readrc(self)
def test_signed_files_py(self):
pa... |
# Local library
from .. import lib
import pyblish.plugin
import pyblish.logic
from nose.tools import (
with_setup,
assert_equals,
assert_raises,
assert_true,
assert_false
)
@with_setup(lib.setup_empty, lib.teardown)
def test_di():
"""Dependency injection works fine"""
_disk = dict()
... |
#!/usr/bin/env python
"""demo_uicallback.py - An application that executes Python code from a Java UI
It would be handy to have a Java class that called Python through the Javabridge,
perhaps something like::
public class PythonEnv {
public native void exec(String script);
public native String ev... |
config = {
"suite_definitions": {
"mochitest": {
"run_filename": "runtestsremote.py",
"options": ["--dm_trans=sut", "--app=%(app)s", "--remote-webserver=%(remote_webserver)s",
"--xre-path=%(xre_path)s", "--utility-path=%(utility_path)s",
"--deviceIP=%(... |
"""
Support for Qwikswitch relays.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.qwikswitch/
"""
import logging
import blumate.components.qwikswitch as qwikswitch
from blumate.components.switch import SwitchDevice
DEPENDENCIES = ['qwikswitch']
... |
# coding=utf-8
"""
This module, problem_001.py, solves the fifteenth project euler problem.
"""
from project_euler_problems.problem import Problem
'''
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many su... |
from __future__ import print_function
import numpy as np
import argparse
import os
import sys
import signal
import time
import socket
from contextlib import closing
from six import string_types
import math
import paddle
import paddle.fluid as fluid
import paddle.fluid.profiler as profiler
import paddle.fluid.unique_na... |
from oslo_log import log as logging
from oslo_serialization import jsonutils
import six
from nova.scheduler import filters
from nova.scheduler.filters import extra_specs_ops
LOG = logging.getLogger(__name__)
class ComputeCapabilitiesFilter(filters.BaseHostFilter):
"""HostFilter hard-coded to work with Instance... |
# This program converts OpenFOAM raw data for the velocity field to a text file with
# both position and velocity vector that exist within the folder
#
# Output format :
# position (x y z), velocity vector (x,y,z), velocity vector (r,theta,z)
#
#
#Python imports
#----------------
import os
import sys
import numpy
#-... |
import calendar
import datetime
import functools
import importlib
import os
import re
import time
import unicodedata
import uuid
import warnings
from collections import OrderedDict
from itertools import chain
from operator import itemgetter
import jwt
import requests
from django.apps import apps
from django.conf impor... |
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import lib.helper
from lib.delegate_movie import *
from lib.obex_items import *
from lib.obex_model import *
class ObexView(QTreeView):
def __init__(self, parent, handler=None, scheduler=None, rootItem=None):
super(ObexView, self).__init_... |
"""
问题描述:对于二叉树的节点来说,其本身的值域,有指向左孩子和右孩子的两个指针:对双向
链表的节点来说,其本身的值域,有指向上一个节点和下一个节点的指针。在结构上,两种结构
有相似性,对于每个节点来说,原来的right指针等价于转换后的next指针,原来的left指针
等价于转换后的last指针。现在有一颗搜索二叉树,请将其转换一个有序的双向链表,并且返回
转换后的双向链表头结点。
"""
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = Non... |
"""Setup file for django-closuretree."""
from setuptools import setup, find_packages
from closuretree.version import __VERSION__
setup(
name='django-closuretree',
version=__VERSION__,
packages=find_packages(),
author='Mike Bryant',
author_email='<EMAIL>',
description='Efficient tree-based data... |
#!/usr/bin/env python
"""
This module demonstrates how to find virtual machines that
exist on a datastore, but are not part of the inventory.
This can be useful to find orphaned virtual machines that
are still taking up datastore space, but not currently
being used.
Issues:
Currently works with Windows based vCent... |
# -*- coding: future_fstrings -*-
import stimela
from stimela import utils, recipe
import logging
import os
import sys
import textwrap
from stimela.pathformatter import pathformatter, placeholder
from stimela.exceptions import *
import time
TYPES = {
"str": str,
"float": float,
"bool": bool,
"int... |
"""Test 2D refocusing"""
import pathlib
import sys
import numpy as np
import nrefocus
def test_2d_refocus1():
myname = sys._getframe().f_code.co_name
rfield = nrefocus.refocus(field=np.arange(256).reshape(16, 16),
d=2.13,
nm=1.533,
... |
import os
import time
from oslo_config import cfg
from rally.plugins.openstack import scenario
from rally.task import atomic
from rally.task import utils
GLANCE_BENCHMARK_OPTS = [
cfg.FloatOpt("glance_image_create_prepoll_delay",
default=2.0,
help="Time to sleep after creating ... |
"""
Sniffer tool that outputs raw pcap.
Real-time stream to wireshark:
./sniffer.py | wireshark -k -i -
Save stream to file or pipe:
./sniffer.py > trace.pcap
"""
import sys
import optparse
import spinel.util as util
import spinel.config as CONFIG
from spinel.const import SPINEL
from spinel.c... |
from __future__ import absolute_import
import logging
from tornado import web
from ..views import BaseHandler
from ..models import WorkersModel
class ControlHandler(BaseHandler):
def is_worker(self, name):
return WorkersModel.is_worker(self.application, name)
class WorkerShutDown(ControlHandler):
... |
import argparse
import browser
import sys
latest_channels = {
'firefox': 'nightly',
'chrome': 'dev',
'safari': 'preview',
'servo': 'nightly'
}
channel_by_name = {
'stable': 'stable',
'release': 'stable',
'beta': 'beta',
'nightly': latest_channels,
'dev': latest_channels,
'prev... |
from ..C import INDENT
from .datatype import DataType, TypeInfo
from common.deco import cachedprop
class EnumType(DataType):
def _get_is_scalar(self):
return True
class Enumerator(TypeInfo):
def __init__(self, elf, eid):
query = 'select parent, name, value, loc from enumerato... |
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
import sys
from .lanzador_base import Ui_Dialog
from . import utils
class Ventana(Ui_Dialog):
def setupUi(self, Dialog):
Ui_Dialog.setupUi(self, Dialog)
self.ha_aceptado = False
self._quitar_barras_scroll()
QtCore.QObject.conn... |
import pexpect
import time
import sys
import pygattt
import os
import numpy
import convert
import notifi
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
global calc_output
global raw_output
accel_list_handles = [52,'01','00',48,49,'0100',55,'10']
gyro_list_handles = [100,... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
MAX_REPLACEMENT_LIMIT = 100
def txToHex(tx):
return bytes_to_hex_str(tx.serialize())
def make_utxo(node, amount, confirmed=True, scriptPubKey=C... |
"""
Automated tests for VarEmbed wrapper.
"""
import logging
import os
import sys
import numpy as np
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from gensim.models.wrappers import varembed
try:
import morfessor # noqa: F401
except ImportError:
raise unittest.Sk... |
import abc
import functools
import sys
import weakref
from keystoneclient import auth
from keystoneclient.auth.identity import v2
from keystoneclient.auth.identity import v3
from keystoneclient import exceptions
from keystoneclient import session
from oslo_config import cfg
import six
from heat.common.i18n import _
... |
from deuce.tests import V1Base
from deuce.model import Vault, File
class TestModel(V1Base):
def setUp(self):
super(TestModel, self).setUp()
def test_get_nonexistent_block(self):
v = Vault.get('should_not_exist')
assert v is None
def test_vault_crud(self):
vault_id = sel... |
from django.db import models
class Banque(models.Model):
nom = models.CharField(max_length=100)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.nom
def get_pays_choix():
return ['Belgique'] |
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, Field
from nav.models.fields import INFINITY
class MaintenanceTaskForm(forms.Form):
start_time = forms.DateTimeField(required=True)
end_time = forms.DateTimeField(required=False... |
from couchdbkit.exceptions import ResourceNotFound
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _, ugettext_noop
from corehq.app... |
from pbr import tests
from pbr import version
class DeferredVersionTestCase(tests.BaseTestCase):
def test_cached_version(self):
class MyVersionInfo(version.VersionInfo):
def _get_version_from_pkg_resources(self):
return "5.5.5.5"
deferred_string = MyVersionInfo("opens... |
"""Test Setup
$Id: tests.py 100552 2009-05-30 15:16:11Z srichter $
"""
__docformat__ = "reStructuredText"
import unittest
from zope.testing import doctest
from zope.testing.doctestunit import DocFileSuite
def printTaggedTerms(terms):
for term, tag, norm in terms:
print (
term + ' '*(16-len(ter... |
import pandas as pd
from alpenglow.offline.models import FactorModel
import alpenglow.Getter as rs
data = pd.read_csv(
"../../python/test_alpenglow/test_data_4",
sep=' ',
header=None,
names=['time', 'user', 'item', 'id', 'score', 'eval']
)
model = FactorModel(
factor_seed=254938879,
dimension=1... |
import numpy as np
from .trottersuzuki import Lattice1D as _Lattice1D
from .trottersuzuki import Lattice2D as _Lattice2D
from .trottersuzuki import State as _State
from .trottersuzuki import GaussianState as _GaussianState
from .trottersuzuki import SinusoidState as _SinusoidState
from .trottersuzuki import Exponential... |
from __future__ import absolute_import
from traits.api import HasTraits, List, Button, Int
from traitsui.api import View, UItem, TabularEditor, VGroup, HGroup, spring
from traitsui.tabular_adapter import TabularAdapter
# ============= standard library imports ========================
# ============= local library impor... |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='sqlshare-web',
version='0.1',
packages=['sqlshare_web'],
... |
from django.conf.urls import url
from .views import (
IndexView, StatisticsView,
UserList, UserDetail, UserCreate, UserUpdate, UserDelete, SwitchUser,
OrganisationList, OrganisationCreate, OrganisationDelete,
ProjectList, ProjectCreate, ProjectDelete,
PolicyList, PolicyDetail, PolicyCreate, PolicyU... |
import os
import dj_database_url
### Basic config
BASE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
DEBUG = TEMPLATE_DEBUG = True
SITE_ID = 1
SECRET_KEY = 'its-a-secret-to-everybody'
# Until Sentry works on Py3, do errors the old-fashioned way.
ADMINS = []
# General project information
# T... |
import base64
import six
def log2floor(n):
"""
Returns the exact value of floor(log2(n)).
No floating point calculations are used.
Requires positive integer type.
"""
assert n > 0
return n.bit_length() - 1
def log2ceil(n):
"""
Returns the exact value of ceil(log2(n)).
No float... |
import itertools
import copy
import numpy as np
from .. import Time
from ...tests.helper import pytest
from ...utils.compat.numpycompat import NUMPY_LT_1_9
from ...utils.compat.numpy import broadcast_to as np_broadcast_to
class TestManipulation():
"""Manipulation of Time objects, ensuring attributes are done cor... |
from StandardDataSets.scripts import JudgeAssistant
# Please feed your node list here:
tagLst = []
attrName = ''
attrVal = ''
dataToCheck = ''
class SimpleJudgingObject:
def __init__(self, _tagLst, _attrName, _attrVal, _data):
self.tagList = _tagLst
self.attrName = _attrName
se... |
import os
import re
import tarfile
import json
import requests
import time
from datetime import datetime
from spicedham import Spicedham
THRESHHOLD = 0.5
def test_on_training_data():
print 'testing against the training data set'
test_file(os.path.join('corpus', 'train'))
def test_on_spam_data():
print '... |
"""
Show 10,000 realtime scrolling plots
"""
from vispy import app, scene
import numpy as np
canvas = scene.SceneCanvas(keys='interactive', show=True, size=(1024, 768))
grid = canvas.central_widget.add_grid()
view = grid.add_view(0, 1)
view.camera = scene.MagnifyCamera(mag=1, size_factor=0.5, radius_ratio=0.6)
# Add... |
from __future__ import absolute_import
import unittest
from telemetry import decorators
from telemetry.internal.browser import browser_finder
from telemetry.testing import options_for_unittests
from telemetry.testing import tab_test_case
from telemetry.timeline import tracing_config
from telemetry.util import trace_pr... |
import base64
import logging
import subprocess
from . import JavaScriptInterpreter
##########################################################################################################################################################
BUG_REPORT = 'Cloudflare may have changed their technique, or there may be a bu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.