content stringlengths 4 20k |
|---|
import logging
import modulemap
import paths
import singlescore_handler
logging.info ( "LOADING: multiscore_handler" )
def update_hi ( req ):
# how many slots in the table?
n = modulemap.gamemap [ req [ 'gamename' ] ][ 'module' ].get_table_slots ( req )
# keep a copy of bindata since get_hi is destruct... |
from functools import partial
import hashlib
import datetime
from storage import Storage
class FunctionCache(Storage):
ONE_MINUTE = 60
ONE_HOUR = 60 * ONE_MINUTE
ONE_DAY = 24 * ONE_HOUR
ONE_WEEK = 7 * ONE_DAY
ONE_MONTH = 4 * ONE_WEEK
def __init__(self, filename, max_file_size_kb=-1):
... |
"""Provide a jinja2 extension for the cookiecutter.."""
from __future__ import absolute_import
import os
from os.path import basename, expanduser, isabs, join
from jinja2.ext import Extension
__all__ = ("MemoteExtension",)
class MemoteExtension(Extension):
"""Provide an absolute path to a file."""
tags ... |
"""
Tests for the wrapping layer that provides the XBlock API using XModule/Descriptor
functionality
"""
# For tests, ignore access to protected members
# pylint: disable=protected-access
from unittest.case import SkipTest, TestCase
from unittest.mock import Mock
import ddt
import webob
from webob.multidict import M... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsMapRendererCache.
.. note:: 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 2 of the License, or
(at your option) any later version.
"... |
#!Measurement
'''
baseline:
after: true
before: false
counts: 20
detector: H1
mass: 34.2
settling_time: 15.0
default_fits: nominal_linear
equilibration:
eqtime: 1.0
inlet: R
inlet_delay: 3
outlet: O
use_extraction_eqtime: true
multicollect:
counts: 90
detector: H1
isotope: Ar40
peakcenter:
... |
# rank upgrades
import host
import bf2.PlayerManager
import bf2.Timer
from bf2.stats.constants import *
from bf2 import g_debug
def init():
# Events
#if g_debug: print "getUseGlobalRank = %s" % str(bf2.serverSettings.getUseGlobalRank())
#if bf2.serverSettings.getUseGlobalRank():
host.registerHandler('PlayerConn... |
import logging
from airflow.hooks import PostgresHook
from airflow.models import BaseOperator
from airflow.utils import apply_defaults
class PostgresOperator(BaseOperator):
"""
Executes sql code in a specific Postgres database
:param postgres_conn_id: reference to a specific postgres database
:type ... |
"""
TwoStepPicker
:Authors:
Berend Klein Haneveld
"""
from Picker import Picker
from core.decorators import overrides
from core.operations import Multiply
from core.operations import Add
from core.operations import ClosestPoints
from core.operations import Subtract
from core.operations import LineIntersectionWithTria... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import inspect
import string
from rpython.rlib import streamio as sio
from rpython.rlib.listsort import make_timsort_class
from rpython.rlib import jit, objectmodel, rtime
from rpython.rlib.unroll import unrolling_iterable
def os_check_env_var(var_str... |
import os
import glob
import numpy as np
import sympy
from sympy import pi, sin, cos, var, Matrix
var('i1, j1, k1, l1', integer=True)
var('x, t, xa, xb, tmin, tmax, L, r, sina, cosa')
var('A11, A12, A16, A22, A26, A66, A44, A45, A55')
var('B11, B12, B16, B22, B26, B66')
var('D11, D12, D16, D22, D26, D66')
var('wx, wt... |
from django.db import transaction
class TransactionMiddleware(object):
"""
Transaction middleware. If this is enabled, each view function will be run
with commit_on_response activated - that way a save() doesn't do a direct
commit, the commit is done when a successful response is created. If an
exc... |
from django import forms
from django.conf import settings
class EventForm(forms.Form):
title = forms.CharField(
label='Titre',
widget=forms.TextInput(
attrs={
'autofocus': '',
'placeholder': 'Titre'
}
)
)
place = forms.CharFie... |
# Various tests that don't fit into the other categories and don't make their own really.
import os
import yaml
from test_helpers import get_expanded_config
__maintainer__ = 'branden'
__contact__ = '<EMAIL>'
# Test that user config is loadable
# TODO(cmaloney): Validate it contains some settings we expact.
def te... |
import collections
import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json
import sys
generator_supports_multiple_toolsets = True
generator_wants_static_library_dependencies_adjusted = False
generator_filelist_paths = {
}
generator_default_variables = {
}
for dirname in ['INTERMEDIATE_DIR', 'SH... |
import os
import io
import sys
from test.support import (run_unittest, TESTFN, rmtree, unlink,
captured_stdout)
import unittest
import trace
from trace import CoverageResults, Trace
from test.tracedmodules import testmod
#------------------------------- Utilities ---------------------... |
# -*- coding: utf8 -*-
'''
Python SSAP API
Version 1.5
© Indra Sistemas, S.A.
2014 SPAIN
All rights reserved
'''
import logging
import sys
class LogFactory(object):
'''
This class configures a Python logger.
'''
__line_pattern = '%(asctime)s %(name)s [%(levelname)s] - %(... |
import logging
import re
import os
formatter = logging.Formatter('%(asctime)s %(name)-8s %(levelname)-6s %(message)s')
_logger = None
CHATTY_LOGGERS = [
'apirequest',
'requests',
]
# python 2.7
class NullHandler(logging.Handler):
def createLock(self):
self.lock = None
def handle(self, rec... |
import json
from social.p3 import urlencode
from social.tests.backends.oauth import OAuth1Test
class DropboxOAuth1Test(OAuth1Test):
backend_path = 'social.backends.dropbox.DropboxOAuth'
user_data_url = 'https://api.dropbox.com/1/account/info'
expected_username = '10101010'
access_token_body = json.du... |
intCodeTemplate = '''
def rom
{
# This vectors the CPU into an interrupt handler in long mode.
# On entry, t1 is set to the vector of the interrupt and t7 is the current
# ip. We need that because rdip returns the next ip.
extern %(startLabel)s:
#
# Get the 64 bit interrupt or trap gate descrip... |
from __future__ import unicode_literals
from django.db import models
from popolo.models import Person
from compat import python_2_unicode_compatible
def get_complex_popolo_fields():
"""Return a mapping of field name to ComplexField object
This returns a dict mapping the name of the field to the
Comple... |
import time
from common_report_header import common_report_header
from openerp.report import report_sxw
class journal_print(report_sxw.rml_parse, common_report_header):
def __init__(self, cr, uid, name, context=None):
if context is None:
context = {}
super(journal_print, self).__init__... |
import pdb;
import sys;
import linecache
def qdebug(options = None,
expanded = None,
typeformats = None,
individualformats = None,
watchers = None):
class QDebug:
def __init__(self,
options = None,
expanded = None,
... |
from multiprocessing import Pool, Manager, Process, Lock, Queue, Value, Array, Pipe, TimeoutError
import multiprocessing as mp
import concurrent.futures
import time
import os
from timeit import default_timer as timer
import struct
import itertools as it
import math
import random as rnd
import time
def sendMsgsToMultiS... |
import re
import sys
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style
from .winterm import WinTerm, WinColor, WinStyle
from .win32 import windll
winterm = None
if windll is not None:
winterm = WinTerm()
def is_a_tty(stream):
return hasattr(stream, 'isatty') and stream.isatty()
class StreamWrapper(o... |
"""
Utilities for waffle.
Includes namespacing, caching, and course overrides for waffle flags.
Usage:
For Waffle Flags, first set up the namespace, and then create flags using the
namespace. For example:
WAFFLE_FLAG_NAMESPACE = WaffleFlagNamespace(name='course_experience')
# Use CourseWaffleFlag when you a... |
import numpy as np
from pyscf import scf
def convert_to_gcisd(myci):
from pyscf.ci import gcisd
if isinstance(myci, gcisd.GCISD):
return myci
mf = scf.addons.convert_to_ghf(myci._scf)
gci = gcisd.GCISD(mf)
assert(myci._nocc is None)
assert(myci._nmo is None)
gci.__dict__.update(myc... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import tempfile
import tarfile
from subprocess import Popen, PIPE
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native
from ansible.module_utils.six... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from units.compat.mock import patch
from units.modules.utils import set_module_args
from .dellos9_module import TestDellos9Module, load_fixture
from ansible.modules.network.dellos9 import dellos9_facts
class TestDell... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.vars.clean import module_response_deepcopy
import pytest
def test_module_response_deepcopy_basic():
x = 42
y = module_response_deepcopy(x)
assert y == x
def test_module_response_deepcopy_atomic():
te... |
from django.conf.urls import url
from . import feeds
urlpatterns = [
url(r'^syndication/rss2/$', feeds.TestRss2Feed()),
url(r'^syndication/rss2/guid_ispermalink_true/$',
feeds.TestRss2FeedWithGuidIsPermaLinkTrue()),
url(r'^syndication/rss2/guid_ispermalink_false/$',
feeds.TestRss2FeedWithG... |
"""
Certificate tool in the student support app.
"""
import urllib
from django.utils.decorators import method_decorator
from django.views.generic import View
from edxmako.shortcuts import render_to_response
from support.decorators import require_support_permission
class CertificatesSupportView(View):
"""
Vi... |
import sys
import tkinter
import unittest
from test.support import requires
class AbstractTkTest:
@classmethod
def setUpClass(cls):
cls._old_support_default_root = tkinter._support_default_root
destroy_default_root()
tkinter.NoDefaultRoot()
cls.root = tkinter.Tk()
cls.w... |
import base64
import six
from mongoengine import DictField, IntField, StringField, \
EmailField, BooleanField
from mongoengine.queryset import OperationError
from social.storage.base import UserMixin, AssociationMixin, NonceMixin, \
CodeMixin, BaseStorage
UNUS... |
""" Python 'utf-8' Codec
Written by Marc-Andre Lemburg (<EMAIL>).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import codecs
### Codec APIs
encode = codecs.utf_8_encode
def decode(input, errors='strict'):
return codecs.utf_8_decode(input, errors, True)
class IncrementalEncoder(... |
import numpy as np
#from ..util.warping_functions import *
from ..core import GP
from .. import likelihoods
from paramz import ObsAr
#from GPy.util.warping_functions import TanhFunction
from ..util.warping_functions import TanhFunction
from GPy import kern
class WarpedGP(GP):
"""
This defines a GP Regression m... |
from __future__ import absolute_import, print_function, division
import wx
from ivy.std_api import *
from ivy.ivy import IvyIllegalStateError
import logging
from textdroptarget import *
import math
import random
import sys
from os import getenv, path
import messagepicker
# if PAPARAZZI_SRC not set, then assume the tr... |
# coding: utf-8
from .. import fixtures, config
from ..assertions import eq_
from ..config import requirements
from sqlalchemy import Integer, Unicode, UnicodeText, select
from sqlalchemy import Date, DateTime, Time, MetaData, String, \
Text, Numeric, Float, literal, Boolean
from ..schema import Table, Column
from... |
from setuptools.command.easy_install import easy_install
from distutils.util import convert_path, subst_vars
from pkg_resources import Distribution, PathMetadata, normalize_path
from distutils import log
from distutils.errors import DistutilsError, DistutilsOptionError
import os, sys, setuptools, glob
class develop(ea... |
data = (
'Di ', # 0x00
'Qi ', # 0x01
'Jiao ', # 0x02
'Chong ', # 0x03
'Jiao ', # 0x04
'Kai ', # 0x05
'Tan ', # 0x06
'San ', # 0x07
'Cao ', # 0x08
'Jia ', # 0x09
'Ai ', # 0x0a
'Xiao ', # 0x0b
'Piao ', # 0x0c
'Lou ', # 0x0d
'Ga ', # 0x0e
'Gu ', # 0x0f
'Xiao ', # 0x10
'Hu... |
"""Tests for Softsign and SoftsignGrad."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import nn_ops
im... |
"""Tests for DecodeCSV op from parsing_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.ops import parsing_ops
from tensorflow.python.platform import test
class DecodeCSVOpTest(test.TestCase):
def _test... |
"""Generate and work with PEP 425 Compatibility Tags."""
from __future__ import absolute_import
import re
import sys
import warnings
try:
import sysconfig
except ImportError: # pragma nocover
# Python < 2.7
import distutils.sysconfig as sysconfig
import distutils.util
_osx_arch_pat = re.compile(r'(.+)_(... |
__version__ = "$Revision: 194 $"
__author__ = "$Author: holtwick $"
__date__ = "$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $"
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.units import inch
from reportlab.platypus import Frame
import ho.pisa as pisa
def test(filename):
# Convert HTML... |
import sys
from twisted.internet import reactor
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.python import log
from autobahn.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
class EchoClientP... |
# -*- encoding: utf-8 -*-
import collections
from abjad.tools.abctools import AbjadValueObject
class StringNumber(AbjadValueObject):
r'''String number indicator.
.. container:: example
**Example 1.** String I:
::
>>> indicator = indicatortools.StringNumber(1)
>>> p... |
from webkitpy.tool.steps.abstractstep import AbstractStep
# FIXME: Unify with StepSequence? I'm not sure yet which is the better design.
class MetaStep(AbstractStep):
substeps = [] # Override in subclasses
def __init__(self, tool, options):
AbstractStep.__init__(self, tool, options)
self._ste... |
from __future__ import division, print_function, absolute_import
from io import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse import coo_matrix, csc_matrix, rand
from scipy.io import hb_read, hb_write
SIMPLE = """\
No Ti... |
from django.apps import apps
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.core.exceptions import FieldDoesNotExist
from django.db.models.fields import CharField, Field, related
from django.db.models.options import EMPTY_RELATION_TREE, IMMUTABLE_WARNING
from djan... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline ... |
"""
Read in the cmsis/devinc/stm32f405xx.h header, extract relevant constants,
and create modstmconst.c.
This is not part of the automatic build process because stm32f405xx.h isn't
expected to change. After generating the file, some manual intervention is
needed to copy the new qstr definitions to qstrdefsport.h.
"""... |
import os
import shutil
import sys
from threading import Lock
from tempfile import NamedTemporaryFile
from pyspark import accumulators
from pyspark.accumulators import Accumulator
from pyspark.broadcast import Broadcast
from pyspark.conf import SparkConf
from pyspark.files import SparkFiles
from pyspark.java_gateway i... |
"""Deploy"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
from datetime import datetime
import os.path
import sys
import time
import math
import numpy as np
from six.moves import xrange
import tensorflow as tf
from config import *
from datas... |
import MySQLdb
import psycopg2
import os
from wsgi import *
def create_dbs():
print("create_dbs: let's go.")
django_settings = __import__(os.environ['DJANGO_SETTINGS_MODULE'], fromlist='DATABASES')
print("create_dbs: got settings.")
databases = django_settings.DATABASES
for name, db in databases.it... |
from pygametk.logger import Logger
from pylaunchr.service.handler import ServiceCommandHandler
from plugin.twitch.data import TwitchGame
class TwitchHandler(ServiceCommandHandler):
# TODO: Use inherited variant
def handle_event(self, event):
Logger("twitch").debug("Received event")
callbac... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from os import close
from tempfile import mkstemp, mkdtemp
from traceback import format_exc
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
def main():
module = AnsibleMod... |
#!/usr/bin/env python
# Download individual checksum files for Electron zip files from S3,
# concatenate them, and upload to GitHub.
from __future__ import print_function
import argparse
import sys
from lib.config import s3_config
from lib.util import boto_path_dirs
sys.path.extend(boto_path_dirs())
from boto.s3.c... |
import os
from optparse import OptionParser
import sys
if sys.version_info < (3, 0):
string_type = basestring
if os.name != 'nt':
import codecs
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
else:
string_type = str
sys.path.insert(0, os.path.dirname(os.pat... |
from datetime import datetime
from django.core.management import BaseCommand
from corehq.apps.locations.models import SQLLocation
from custom.ilsgateway.models import ILSGatewayConfig, ReportRun, SupplyPointStatus, DeliveryGroupReport, \
SupplyPointWarehouseRecord, OrganizationSummary, ProductAvailabilityData, Aler... |
"""
This script changes versions in every pom.xml and relevant files.
(How to run)
python change_version <reef_home> <reef_version_for_pom.xml> -s <true or false> (optional) -p
-s option changes value of 'IsSnapshot' in lang/cs/build.props.
If you use the option "-s false", bulid.props changes as,
<IsSnapshot>fals... |
import sys
import re
atre = re.compile('(@\d+):')
intro_re = re.compile (r'(.*[:|])\s')
keyword_re = re.compile (r'(\S+)\s')
# strip extra backslashes that are inserted by the python
# string handling routines
def strip_backslash(input_string):
i=input_string.find(r'"\\')
while i > -1 :
input_string ... |
"""Basic word2vec example."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import math
import os
import sys
import argparse
import random
from tempfile import gettempdir
import zipfile
import numpy as np
from six.moves import urllib
f... |
from gettext import gettext as _
from gettext import ngettext
import locale
import logging
from gi.repository import GObject
from gi.repository import Gtk
from sugar3.graphics import style
from sugar3.graphics.icon import Icon, CellRendererIcon
from jarabe.controlpanel.sectionview import SectionView
from model impo... |
# Base classes for ASN.1 types
import sys
from pyasn1.type import constraint, tagmap
from pyasn1 import error
class Asn1Item: pass
class Asn1ItemBase(Asn1Item):
# Set of tags for this ASN.1 type
tagSet = ()
# A list of constraint.Constraint instances for checking values
subtypeSpec = constraint.C... |
"""
Python tests for the Survey models
"""
from collections import OrderedDict
import ddt
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.test import TestCase
from django.test.client import Client
from survey.exceptions import SurveyFormNameAlreadyExists, Su... |
"""Common media action functions."""
import logging
import os
from telemetry.core import util
from telemetry.page.actions import page_action
class MediaAction(page_action.PageAction):
def WillRunAction(self, page, tab):
"""Loads the common media action JS code prior to running the action."""
self.LoadJS(t... |
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.template.defaultfilters import timeuntil_filter
from django.test import SimpleTestCase
from django.test.utils import requires_tz_support
from ..utils import setup
from .timezone_utils import TimezoneTestCase
class Timeunti... |
import asyncio
import errno
from pexpect import EOF
@asyncio.coroutine
def expect_async(expecter, timeout=None):
# First process data that was previously read - if it maches, we don't need
# async stuff.
previously_read = expecter.spawn.buffer
expecter.spawn.buffer = expecter.spawn.string_type()
i... |
"""Command for measuring how long pages take to load in a browser.
Prerequisites:
1. The command_line package from tools/site_compare
2. Either the IE BHO or Firefox extension (or both)
Installation:
1. Build the IE BHO, or call regsvr32 on a prebuilt binary
2. Add a file called "<EMAIL>" to
the default ... |
"""
homeassistant.components.notify.instapush
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Instapush notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.instapush/
"""
import logging
import json
import requests
from homeassistant.h... |
from django.contrib.auth.models import User
from rest_framework import pagination
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet
from notification_prefs import NOTIFICATION_PREF_KEY
from notifier_api.serializers import NotifierUserSerializer
from openedx.core.lib.... |
import os
import time
import unittest
import shutil
from swift.account import replicator, backend, server
from swift.common.utils import normalize_timestamp
from swift.common.storage_policy import POLICIES
from test.unit.common import test_db_replicator
class TestReplicatorSync(test_db_replicator.TestReplicatorSync... |
#!/usr/bin/env python3
#
# test_multibytecodec.py
# Unit test for multibytecodec itself
#
from test import support
from test.support import TESTFN
import unittest, io, codecs, sys, os
import _multibytecodec
ALL_CJKENCODINGS = [
# _codecs_cn
'gb2312', 'gbk', 'gb18030', 'hz',
# _codecs_hk
'big5hkscs',
# _code... |
from django.core.management.base import BaseCommand
from google.appengine.api import apiproxy_stub_map
from google.appengine.datastore import datastore_stub_util
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--noinput', action='store_f... |
#!/usr/bin/env python
import random
import timeit
import numpy as np
from werkzeug.security import check_password_hash, generate_password_hash
random.seed(0)
def main():
str_gen = "import random;random.seed(0);string=''.join(random.choices('ABCDEFGHIJKLM', k=20));"
pw_gen = (
"from werkzeug.securit... |
import chainer
import numpy
import pytest
import chainerx
from chainerx_tests import array_utils
def _create_max_pool_args(
xp, device, x_shape, ksize, stride, pad, cover_all, float_dtype):
x = array_utils.create_dummy_ndarray(xp, x_shape, float_dtype)
ret_args = dict(x=x, ksize=ksize)
if stride... |
#!/usr/bin/env python
"""
Usage:
./top_filters <path_to_a_saved_DBM.pkl> <optional: output path prefix>
Displays the matrix product of the layer 1 and layer 2 weights.
Also displays a grid visualization the connections in more detail.
Row i of the grid corresponds to the second layer hidden unit
with the ith largest f... |
"""Base classes for server/gateway implementations"""
from types import StringType
from util import FileWrapper, guess_scheme, is_hop_by_hop
from headers import Headers
import sys, os, time
__all__ = ['BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler']
try:
dict
except NameError:
def dict(items)... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class TxnMallTest(BitcoinTestFramework):
def add_options(self, parser):
parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true",
help="Test double-spend... |
from satoyama.database import manager
from app import flapp, limiter
### Settings necessary to use the app in the console
### Note that enrivonment settings override module settings.
module_config = {
'LOGLEVEL': 'DEBUG'
}
### Settings shared between environments
shared_config = {
'CSRF_ENABLED': True,
'SECRET_K... |
from code.agent import Agent,AgentConfig
import gym
from code.preprocessors import AtariPreprocessor
from code.policies import LinearDecayGreedyEpsilonPolicy
from code.utils import get_output_folder
import os
from keras import backend as K
import tensorflow as tf
import numpy as np
if __name__== '__main__':
ata... |
from __future__ import absolute_import
from __future__ import with_statement
import sys
import time
from functools import partial
from itertools import chain, izip
from celery.registry import TaskRegistry
from celery.task.base import Task
from celery.utils import timeutils
from celery.utils import uuid
from celery.w... |
from nova.api.openstack.compute.schemas import scheduler_hints as schema
from nova.api.openstack import extensions
ALIAS = "os-scheduler-hints"
class SchedulerHints(extensions.V3APIExtensionBase):
"""Pass arbitrary key/value pairs to the scheduler."""
name = "SchedulerHints"
alias = ALIAS
version = ... |
"""
test_router
----------------------------------
Functional tests for `shade` router methods.
"""
import ipaddress
from shade.exc import OpenStackCloudException
from shade.tests.functional import base
EXPECTED_TOPLEVEL_FIELDS = (
'id', 'name', 'admin_state_up', 'external_gateway_info',
'tenant_id', 'rout... |
from django.db.models import Q
from django.test import TestCase
from .models import Issue, StringReferenceModel, User
class RelatedObjectTests(TestCase):
def test_related_objects_have_name_attribute(self):
for field_name in ('test_issue_client', 'test_issue_cc'):
obj = User._meta.get_field(f... |
from south.db import db
from django.db import models
from cmsplugin_filer_file.models import *
class Migration:
depends_on = (
("filer", "0008_polymorphic__del_field_file__file_type_plugin_name"),
("cms", "0039_auto__del_field_page_moderator_state"),
)
def forwards(self, orm):
... |
import regex
from pynab import log
from pynab.db import db_session, Release, Pre, Group, windowed_query
import config
GROUP_ALIASES = {
# from: to
'alt.binaries.etc': 'alt.binaries.teevee',
}
GROUP_REQUEST_REGEXES = {
'alt.binaries.etc': '^(\d{4,8})$',
'alt.binaries.teevee': '^(\d{4,8}... |
from deluge.ui.console.main import BaseCommand
from deluge.ui.client import client
import deluge.ui.console.colors as colors
import deluge.component as component
class Command(BaseCommand):
"""Show information about the disk cache"""
usage = "Usage: cache"
def handle(self, *args, **options):
self.c... |
"""Arm Compute Library network tests."""
import numpy as np
import pytest
from tvm import testing
from tvm import relay
from test_arm_compute_lib.infrastructure import skip_runtime_test, build_and_run, verify
from test_arm_compute_lib.infrastructure import Device
def _build_and_run_network(mod, params, inputs, devi... |
"""
Covariance estimators using shrinkage.
Shrinkage corresponds to regularising `cov` using a convex combination:
shrunk_cov = (1-shrinkage)*cov + shrinkage*structured_estimate.
"""
# Gael Varoquaux <<EMAIL>>
# Virgile Fritsch <<EMAIL>>
#
# License: BSD 3 clause
# avoid division truncation
from __f... |
from __future__ import unicode_literals
import frappe, re, os, json, imp
import requests, requests.exceptions
from frappe.website.website_generator import WebsiteGenerator
from frappe.website.router import resolve_route
from frappe.website.doctype.website_slideshow.website_slideshow import get_slideshow
from frappe.web... |
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst
def caps_is_video(caps):
s = caps.get_structure(0)
return s.get_name().startswith('video/')
def caps_is_audio(caps):
s = caps.get_structure(0)
return s.get_name().startswith('audio/') |
import datetime
import logging
import operator
import boto3
from botocore.exceptions import ClientError
from concurrent.futures import as_completed
import click
from tabulate import tabulate
from c7n.credentials import assumed_session, SessionFactory
from c7n.utils import format_event, chunks
from c7n_org.cli import... |
"""
Student progress page
"""
from .course_page import CoursePage
class ProgressPage(CoursePage):
"""
Student progress page.
"""
url_path = "progress"
def is_browser_on_page(self):
is_present = (
self.q(css='div.course-info').present and
self.q(css='div#grade-deta... |
"""StatsOptions to configure stats aggregation options for `tf.data` pipelines.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.experimental.ops import stats_aggregator
from tensorflow.python.data.util import options
from ten... |
from generator.actions import Actions, Variable
from random import choice, randint
from os.path import dirname, abspath, join
import sys
sys.path.append(join(dirname(dirname(dirname(abspath(__file__)))), "support"))
import support as sp
from common import DEBUG, CONFIG
from orderup import OrderUp
from table import Tab... |
from openerp.osv import fields,osv
class res_partner(osv.osv):
""" Inherits partner and adds CRM information in the partner form """
_inherit = 'res.partner'
def _opportunity_meeting_phonecall_count(self, cr, uid, ids, field_name, arg, context=None):
res = dict(map(lambda x: (x,{'opportunity_count... |
import mock
import os
from buildbot.test.fake import fakemaster
from buildbot.test.util import www
from buildbot.www import auth
from buildbot.www import resource
from buildbot.www import rest
from buildbot.www import service
from twisted.internet import defer
from twisted.trial import unittest
class NeedsReconfigRe... |
ParGrp = App.ParamGet("System parameter:Modules").GetGroup("Path")
# Set the needed information
ParGrp.SetString("HelpIndex", "Path/Help/index.html")
ParGrp.SetString("WorkBenchName", "Path")
ParGrp.SetString("WorkBenchModule", "PathWorkbench.py") |
from zope.interface import Interface, Attribute, implements
class IProtocolPlugin(Interface):
"""Interface for plugins providing an interface to a Words service
"""
name = Attribute("A single word describing what kind of interface this is (eg, irc or web)")
def getFactory(realm, portal):
"""R... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.