code stringlengths 1 199k |
|---|
import asyncio
from aiohttp_security.authorization import AbstractAuthorizationPolicy
class DictionaryAuthorizationPolicy(AbstractAuthorizationPolicy):
def __init__(self, data):
self.data = data
@asyncio.coroutine
def permits(self, identity, permission, context=None):
record = self.data.get(... |
"""RNN helpers for TensorFlow models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.fra... |
import unittest
from testfixtures import compare
from ..utils import (
hangout_factory,
credentials,
device_seter
)
class TestAudioSettings(unittest.TestCase):
@classmethod
def setup_class(self):
from hangout_api.tests import HANGOUT
self.hangout = HANGOUT
def test_get_audio_devi... |
'''
Author: Padma Gundapaneni @padma-g
Date: 7/28/21
Description: This script cleans up a csv file on county level
precipitation data downloaded from the CDC.
URL: https://data.cdc.gov/browse?category=Environmental+Health+%26+Toxicology
@input_file filepath to the original csv that needs to be cleaned
@output_file f... |
import os
import tensorflow as tf
from basic.main import main as m
flags = tf.app.flags
flags.DEFINE_string("model_name", "basic", "Model name [basic]")
flags.DEFINE_string("data_dir", "data/squad", "Data dir [data/squad]")
flags.DEFINE_string("run_id", "0", "Run ID [0]")
flags.DEFINE_string("out_base_dir", "out2", "ou... |
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 9
_modified_time = 1396998167.321098
_enable_loop = True
_template_filename = 'C:\\app\\manage\\templates/administration.html'
_template_uri = 'administration.html'
_source_encoding... |
'''
-----------------------------------------------------------------------------
Copyright 2016 Esri
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
Unle... |
__author__ = 'indrajit'
__email__ = 'eendroroy@gmail.com'
class BMI(object):
def __init__(self, weight=None, height=None):
self.__weight = weight
self.__height = height
def weight(self, weight):
self.__weight = weight
return self
def height(self, height):
self.__heigh... |
import importlib.machinery
import io
import json
import os
import types
from argparse import Namespace
from typing import List, Union
from colorlog.escape_codes import parse_colors
import nox
from nox import _options, registry
from nox._version import InvalidVersionSpecifier, VersionCheckFailed, check_nox_version
from ... |
from __future__ import print_function
import errno
import glob
import json
import logging
import os
import platform
import shlex
import signal
import subprocess
import sys
import tempfile
import textwrap
import time
import traceback
import uuid
from pynailgun import NailgunConnection, NailgunException
from timing impor... |
from bithordetest import message, BithordeD, TestConnection
import struct
from cStringIO import StringIO
ASSET_SIZE = 8 * 1024 * 1024
def generate(offset, size):
assert((offset % 4) == 0)
assert((size % 4) == 0)
offset /= 4
size /= 4
res = StringIO()
for i in xrange(offset, offset + size):
... |
class Solution(object):
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
return len(A) == len(B) and A in B * 2
def isRotation(s1, s2):
if not s1 and not s2:
return True
for i in range(0, len(s1)):
s3 = s1[-i:] + s1[... |
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import pkg_resources
import google.auth # type: ignore
import google.api_core
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth i... |
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
import pytest
from pytest import approx
from sumy.evaluation import precision, recall, f_score
def test_precision_empty_evaluated():
with pytest.raises(ValueError):
precision((), ("s1", "s2", "s3", "s4",... |
import os
import re
import subprocess
import sys
import tarfile
import tempfile
import test_server
import unittest
import zipfile
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BUILD_TOOLS_DIR = os.path.dirname(SCRIPT_DIR)
TOOLS_DIR = os.path.join(os.path.dirname(BUILD_TOOLS_DIR), 'tools')
sys.path.extend([BUI... |
"""
A service spawned on-demand by launchd, meant to handle configuration requests
from Server.app. When a request comes in on the socket specified in the
launchd agent.plist, launchd will run "caldavd -t Agent" which ends up creating
this service. Requests are made using HTTP POSTS to /gateway, and are
authenticated... |
""" RegionalBackendService class: a regional backend service
"""
from copy import deepcopy
from googleapiclient.http import HttpError
from vm_network_migration.module_helpers.subnet_network_helper import SubnetNetworkHelper
from vm_network_migration.modules.backend_service_modules.backend_service import BackendService
... |
"""
This is a place to put any prep code you need to run before your app
is ready.
For example, you might need to render some icons. The convention for
that is to put the source data in your app's media_src directory and
render the icons into your app's build/media directory (outside version
control).
How this script ... |
"""Test orchestrate projects register."""
from unittest import mock
import orchestrate.main
import pytest
original_create_command = orchestrate.main.create_command
register_Command_configure = mock.Mock()
def create_patched_command(name, loader):
"""Returns a command instance from the given module loader ready for te... |
from pathlib import Path
import pytest
import tempfile
import shutil
import os
class _Datadir(object):
def __init__(self, request):
basedir = request.fspath.dirpath()
datadir = basedir.join("data")
self._datadirs = []
for d in (basedir, datadir):
testdir = d.join(request.... |
"""Simple floor arenas."""
from dm_control import composer
from dm_control.locomotion.arenas import assets as locomotion_arenas_assets
import numpy as np
_GROUNDPLANE_QUAD_SIZE = 0.25
class Floor(composer.Arena):
"""A simple floor arena with a checkered pattern."""
def _build(self, size=(8, 8), reflectance=.2, aest... |
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.ya... |
from multiprocessing import Queue
import random
from neutron.agent import rpc as agent_rpc
from neutron_lib.agent import topics
from neutron_lib.api.definitions import portbindings
from neutron_lib.callbacks import events
from neutron_lib.callbacks import registry
from neutron_lib.callbacks import resources
from neutro... |
"""
Tests.
"""
import numpy as np
import hdmedians as hd
from numpy.testing import assert_equal, assert_array_almost_equal
from nose.tools import assert_true, assert_raises
DATA1 = np.array([[693, 990, 1281, 2101, 3524, 2577],
[606, 898, 1128, 1962, 2992, 2106],
[509, 831, 932, 2287,... |
from database_manager.db_context_manager import DBContextManager
QUERIES = {
'select_profile_photo':
"""
SELECT profile_photo, extension
FROM profile_photos
WHERE friend_id = ?
""",
'insert_profile_photo':
"""
INSERT INTO profile_photos
VALUES
... |
import luigi.format
import logging
import os
from luigi.contrib.hdfs.config import load_hadoop_cmd
from luigi.contrib.hdfs import config as hdfs_config
from luigi.contrib.hdfs.clients import remove, rename, mkdir, listdir, exists
from luigi.contrib.hdfs.error import HDFSCliError
logger = logging.getLogger('luigi-interf... |
"""Simple parsers for the output of WMI queries."""
from grr.lib import parsers
from grr.lib import rdfvalue
class WMIInstalledSoftwareParser(parsers.WMIQueryParser):
"""Parser for WMI output. Yields SoftwarePackage rdfvalues."""
output_types = ["SoftwarePackage"]
supported_artifacts = ["WindowsWMIInstalledSoftwa... |
from django.db import migrations
UPDATE_GWELLS_WELLS_VIEW_SQL = """
DROP VIEW postgis_ftw.gwells_well_view;
CREATE VIEW postgis_ftw.gwells_well_view AS
SELECT
well_tag_number,
aquifer_id,
artesian_conditions AS artesian,
street_address,
identif... |
import difflib
import hashlib
import logging
import os
import os.path
import re
import shutil
import sys
import tempfile
import time
import zipfile
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format="%(message)s")
jre_url = 'https://downloads.mesosphere.com/java/jre-8u121-linux-x64.tar... |
import hashlib
import os
import re
import sys
from typing import List, Optional
import jax
from jax.experimental.compilation_cache.file_system_cache import FileSystemCache
import jax._src.lib
from jax._src.lib import xla_client
from absl import logging
_cache = None
def initialize_cache(path, max_cache_size_bytes=32 * ... |
import unittest
from wsgiref import util as wsgi_util
from sordid import testing
def define_test_app(message):
"""Create a simple test application with custom message"""
def test_app(environ, start_response):
response_headers = [('content-type', 'text/plain')]
for name, value in environ.items():
if na... |
import requests
class LongPoll(object):
def __init__(self, key, server, ts):
self.k = key
self.s = server
self.t = ts
def get(self):
r = requests.get('https://%s?act=a_check&key=%s&ts=%s&wait=25&mode=2&version=1' % (self.s, self.k, self.t))
response = r.json()
if ... |
import xml.etree.ElementTree
import sqlite3
database_file = 'database.db'
cities_xmlfile = "Extra Information/help.xml"
from coordinates import convert_x, convert_y
conn = sqlite3.connect(database_file)
c = conn.cursor()
c.execute('DROP TABLE IF EXISTS CommandHelp');
c.execute('CREATE TABLE CommandHelp(command STRING, ... |
"""
COHORTE Java isolate loader, based on jPype
**TODO:**
* Review constants names & values
:author: Thomas Calmant
:license: Apache Software License 2.0
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the Lice... |
from pyjamas.ui.PopupPanel import PopupPanel
from pyjamas.ui.HTML import HTML
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.Timer import Timer
tooltip_hide_timer = None
class Tooltip(PopupPanel):
def __init__(self, sender, offsetX, offsetY, text, show_delay, hide_delay, styleName):
PopupPanel.__in... |
import mock
from neutron.common import constants
from neutron import context as neutron_context
from neutron.tests import base as tests_base
try:
from dragonflow.controller import l3_openflow_app as of_app
except Exception:
of_app = None
def ryu_enabled(func):
def func_wrapper(*args, **kwargs):
if o... |
"""
LsvmBus - Command ``lsvmbus -vv``
=================================
This module parses the output of the command ``lsvmbus -vv``.
"""
import re
from insights.util import deprecated
from insights import parser, CommandParser
from insights.parsers import SkipException
from insights.specs import Specs
@parser(Specs.ls... |
from __future__ import absolute_import, unicode_literals
import io
import os
import re
from setuptools import find_packages, setup
here = os.path.abspath(os.path.dirname(__file__))
PROJECT_MODULE = 'armory'
PROJECT = 'armory'
AUTHOR = 'Bryce Eggleton'
EMAIL = 'eggleton.bryce@gmail.com'
DESC = 'Python utilities and tool... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
os.environ['LOGS_DIR'] = os.path.abspath(os.path.join(BASE_DIR, 'logs'))
from django_project.settings import * # noqa
SECRET_KEY = 'build key' |
"""Implements experimental logic."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from copy import copy
from dl_bounds.src.data import LocalDatasetProvider
from dl_bounds.src.experiments.exp_base import Experiment
import tensorflow as tf
class BadMinimaExp... |
from posixpath import join as pjoin
import pytest
from pandas.util.testing import assert_frame_equal
import pandas as pd
from ibis.compat import unittest
from ibis.impala.compat import ImpylaError
from ibis.impala.tests.common import ImpalaE2E, ENV
from ibis.tests.util import assert_equal
import ibis
import ibis.util a... |
'''Validate YaML document against yamale schemas.
Fast includes YaML driven resource factories, along with their schemas which
are available at `fast/assets/schemas`.
An arbitrary number of files and directories can be validated against a given
schema via options (--file and --directory, optionally --recursive).
'''
im... |
import re
from .base_filter import BaseFilter
class TransactionFilter(BaseFilter):
filterArgs = [
('--transactions', {
'action': 'store_true', 'default': False,
'help': 'only output lines containing logs of transactions'}),
]
def __init__(self, mlogfilter):
BaseFilter... |
from django.conf.urls import patterns, url
from restAndroid import settings
from transactions.views import TransactionREST, TransactionDetailREST
urlpatterns = patterns(
'',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
url(r'^transactions/$', Transacti... |
import copy
import mock
import unittest2
from webob import exc
import webtest
from quantum.api import extensions
from quantum.api.v2 import attributes
from quantum.common import config
from quantum.extensions import loadbalancer
from quantum import manager
from quantum.openstack.common import cfg
from quantum.openstack... |
"""Helpers for listening to events."""
from datetime import timedelta
import functools as ft
from typing import Callable
import attr
from homeassistant.loader import bind_hass
from homeassistant.helpers.sun import get_astral_event_next
from homeassistant.core import HomeAssistant, callback
from homeassistant.const impo... |
from __future__ import print_function
import os
import sys
import imp
from setuptools import setup, find_packages
CODE_DIRECTORY = 'mcloud'
DOCS_DIRECTORY = 'docs'
TESTS_DIRECTORY = 'tests'
metadata = imp.load_source(
'metadata', os.path.join(CODE_DIRECTORY, 'metadata.py'))
python_version_specific_requires = []
if ... |
import os
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)
from motion_imitation.envs import locomotion_gym_env
from motion_imitation.envs import locomotion_gym_config
from moti... |
from copy import deepcopy
from zoo.orca.automl.model.abstract import BaseModel, ModelBuilder
from zoo.chronos.model.VanillaLSTM import VanillaLSTM
from zoo.chronos.model.Seq2Seq import LSTMSeq2Seq
from zoo.chronos.model.MTNet_keras import MTNetKeras
from zoo.chronos.autots.deprecated.feature.utils import save_config
fr... |
import unittest
import pandas as pd
from ..chart import Plot
from ..plotitem import Area, Stems
class TestSupportDataFrameInPlot(unittest.TestCase):
def test_data_frame_base_attribute_for_area(self):
# given
x = [1, 3, 5, 7, 10]
y = [100, 120, 90, 100, 80]
base = [50, 60, 45, 50, 40]... |
from .color_names import *
__version__ = '0.0.0' |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from mainapp.views import BookListView, BookAssignView, BookReleaseView
from django.contrib.auth.decorators import login_required
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'librarymanagementsystem... |
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 field 'Response.page'
db.add_column('responses', 'page',
self.gf('django.db.models.fields.related.Foreig... |
import random
from urlparse import urlsplit
import kive.event.timer as timer
import kive.event.engine as engine
import kive.http.http_protocol as http_protocol
import kive.http.dispatcher_client as dispatcher_client
def request(url, post=None, headers=None, callback=None):
res = urlsplit(url)
if res.scheme != "... |
__author__ = "Paul Council, Joseph Gonzoph, Anand Patel"
__version__ = "sprint1"
__credits__ = ["Dan, Pat"]
class Observable(object):
"""
Describes an Observable object.
includes methods to notify all observers
and to add/delete them
Attributes:
observer_list: the list of registered observer... |
import mock
from oslo_config import cfg
import testtools
from neutron.common import exceptions as exc
from neutron.common import topics
from neutron import context
from neutron.db import db_base_plugin_v2
from neutron.db import models_v2
from neutron.extensions import flavor as ext_flavor
from neutron.openstack.common ... |
"""
Tests for the twistedcaldav.directory module.
""" |
from django.db import models
class Log_Errors(models.Model):
error = models.TextField()
error_human = models.TextField()
date_time = models.DateTimeField(auto_now_add=True) |
from robot.errors import ExecutionFailed, DataError, PassExecution, SkipExecution
from robot.model import SuiteVisitor
from robot.result import TestSuite, Result
from robot.utils import get_timestamp, is_list_like, NormalizedDict, unic
from robot.variables import VariableScopes
from .context import EXECUTION_CONTEXTS
f... |
{
'name': 'Modifications Odoo 10',
'depends': ['base','hr','fleet','crm','sale','account','mail',
'contacts','account_accountant','l10n_multilang',
'hr_expense','hr_payroll','hr_payroll_account'],
'description': """
Assets management
=================
Manage assets owned by a... |
import json
import synapse.exc as s_exc
import synapse.tests.utils as s_test
logname = 'synapse.storm.log'
class LogTest(s_test.SynTest):
async def test_stormlib_log(self):
async with self.getTestCore() as core:
# Raw message
with self.getAsyncLoggerStream(logname, 'debug message') a... |
"""
Cloudbreak API
Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloudbreak is a RESTful... |
import asyncio
import aiohttp
import binascii
@asyncio.coroutine
def get(client):
print('Get data from httpbin.org')
resp = yield from client.get('http://httpbin.org/get')
print('Reponse code', resp.status)
text = yield from resp.text()
print(text)
yield from resp.release()
@asyncio.coroutine
de... |
import os
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk as gtk
os.chdir('/opt/pynaural')
from beat_gen import BeatGenerator
from auxiliary import *
GENERATOR = BeatGenerator()
def main():
builder = gtk.Builder()
builder.add_from_file('main.ui')
main_window = builder.get_object... |
"""
ELB Security Policy Update Tool
"""
__version_info__ = ('0', '0', '2')
__version__ = '.'.join(__version_info__) |
"""Simulate linearized CGL and find BPOD modes and reduced-order model."""
import numpy as np
import scipy.linalg as spla
import modred as mr
import hermite as hr
plots = True
if plots:
try:
import matplotlib.pyplot as plt
except:
plots = False
nx = 220
dt = 1.0
s = 1.6
U = 2.0
c_u = 0.2
c_d = -... |
'''
Created on Mar 20, 2011
@author: Mourad Mourafiq
@copyright: Copyright © 2011
other contributers:
'''
from django import forms
from django.utils.translation import ugettext, ugettext_lazy as _
from calendars.models.cals import Occurrence
class OccurrenceForm(forms.ModelForm):
start = forms.DateTimeField()
e... |
'''
Date : 2018-1-17
@Author : Amy
Goal : useful modules
Digest : 本模块包含4种启发式算法对容器新增场景的服务非容错初始放置的求解方法,
分别包好FFDSum、FFDProd、Dot-Product(cosine)、L2(distance of vector)算法
Notes:1. 所有的代价计算仅以集群中active HMs为准,即v_p/m_cost、h_p/m_cost均不为0.0或直接使用map_v_h计算
2. 代价计算模块中HM/VM的负载均已其上实际承载的所有容器产生的资源耗费作为计算准则;
3. 对于负载均... |
"""
Event Log Interface
"""
import sqlite3
import data
UNSPECIFIED = 0
SERVER_ERROR = 1
CLIENT_ERROR = 2
REQUEST = 3
RESPONSE = 4
TASKING = 5
STATISTICS = 6
ALL = 6
level_strings = (
'unspecified',
'server error',
'client error',
'request',
'response',
'tasking',
's... |
import os
def main(j, args, params, tags, tasklet):
page = args.page
page.addCSS(cssContent='''
.bigpicture{
margin: 10px 0 15px 0;
}
.bigpicture-container{
text-align: center;
}
.subtitle{
margin-bottom: 10px;
display: block;
}
.subtitle-paragraph{
margin-bottom: 5px;
}
.bigpicture-c... |
'''
Created on 2014-01-09
@author: Wei
'''
class Token:
def __init__(self, word, word_id, sentence):
self.word = word
self.id = word_id
self.sentence = sentence
self.lemma = None
self.char_begin_offset = None
self.char_end_offset = None
self.pos = None
def... |
import logging, itertools, datetime
import ptypes
from ptypes import *
from . import Object
class ulong(pint.bigendian(pint.uint32_t)): pass
class stringinteger(pstr.string):
def set(self, integer):
res, bs = str(integer), self.blocksize()
size = bs - len(res)
return self.__setvalue__(res + ... |
import sys
import unittest
import pyhsm
import test_common
class TestUtil(test_common.YHSM_TestCase):
def setUp(self):
self.saved_stderr = sys.stderr
# Discard everything written to stderr from these tests (i.e. debug output
# from YubiHSM communication routines with debugging enabled).
... |
from pyN.Populations.Base_Population import Base_Population
import numpy as np
class AdExPopulation(Base_Population):
def __init__(self, name, cm=0.281, tau_refrac=0.1, v_spike=-40.0, v_reset=-70.6, v_rest=-70.6, tau_m=9.3667, i_offset=0.0, a=4.0, b=0.0805, delta_T=2.0,tau_w=144.0,v_thresh=-50.4,e_rev_E=0.0, tau_syn_... |
"""Tests for the main module.
De facto they serve as integration tests.
"""
import io
import unittest
from unittest import mock
import sys
from py1 import constants
from py1 import main
from py1 import runner
class TestMain(unittest.TestCase):
def setUp(self):
self.addCleanup(mock.patch.stopall)
sel... |
import sys
from collections import OrderedDict
from table import Table
def load(file):
result = OrderedDict()
procedures = set()
for line in file:
tmp = line.split(',')
proc = tmp[0]
small_size = int(tmp[1])
large_size = int(tmp[2])
time_us = int(tmp[3])
key =... |
"""These are the plugins included with Lino XL.
Contacts management
===================
.. autosummary::
:toctree:
countries
contacts
addresses
phones
households
humanlinks
cv
dupable_partners
Groupware
=========
.. autosummary::
:toctree:
boards
teams
lists
groups
... |
import ptypes, pecoff
from . import umtypes
from .datatypes import *
class LDR_DATA_TABLE_ENTRY(pstruct.type, versioned):
class SectionPointerUnion(dynamic.union):
class SectionPointer(pstruct.type):
_fields_ = [(PVOID, 'SectionPointer'), (ULONG, 'CheckSum')]
_fields_ = [
(LI... |
from __future__ import print_function, division, absolute_import
from numba.typesystem import *
def is_obj(type):
return type.is_object or type.is_array
native_type_dict = {}
for native_type in minitypes.native_integral:
native_type_dict[(native_type.itemsize, native_type.signed)] = native_type
def promote_to_n... |
import unittest
import asyncio
from asyncio_amp import (
Integer,
Bytes,
Float,
Boolean,
String,
AMPProtocol,
Command,
RemoteAmpError,
TooLongError,
UnknownRemoteError,
UnhandledCommandError,
)
class MyException(Exception):
pass
class EchoCommand(Command):
arguments =... |
"""Daemon that runs and reports health checks
Documentation https://sauna.readthedocs.io
Usage:
sauna [--level=<lvl>] [--config=FILE] [<command> <args>...]
sauna sample
sauna (-h | --help)
sauna --version
Options:
-h --help Show this screen.
--version Show version.
--level=<lvl> Log level [defa... |
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('optimize10.xlsx')
self.set_text_file('uni... |
from nose.tools import ok_
from linot.Plugins.TwitchNotifier.Plugin import Plugin
from linot.LinotArgParser import LinotArgParser, LinotParser
from linot.LinotConfig import LinotConfig as Config
import argparse
import inspect
import pickle
import threading
import os
from collections import defaultdict
class MockSender:... |
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from sauna.consumers.base import AsyncConsumer
from sauna.consumers import ConsumerRegister
from sauna import __version__
my_consumer = ConsumerRegister('HTTPServer')
class StoppableHTTPServer(HTTPServer):
"""HTTPServer that stops itself when re... |
from django.contrib import admin
from . import models
class UplusTransactionAdmin(admin.ModelAdmin):
list_display = ['amount', 'basket_id', 'timestamp', 'status', 'pay_type',]
readonly_fields = ['amount', 'status', 'pay_type', 'basket_id']
admin.site.register(models.UplusTransaction, UplusTransactionAdmin) |
import os
from mpi4py import MPI
from mpi4py.MPI import ANY_SOURCE
import csv
import sys
import scipy.optimize as opt
import scipy.stats as stat
from operator import itemgetter
import random
import numpy as np
import numpy.ma as ma
import numpy.linalg as la
pi = np.pi
sin = np.sin
cos = np.cos
def fillin2(data):
""... |
VALID_TAINT_EFFECT = ["NO_EXECUTE", "NO_SCHEDULE", "PREFER_NO_SCHEDULE"]
def validate_taint_effect(taint_effect):
"""
Taint Effect validation rule.
Property: Taint.Effect
"""
if taint_effect not in VALID_TAINT_EFFECT:
raise ValueError(
"Taint Effect must be one of: %s" % ", ".joi... |
"""
Set up the plot figures, axes, and items to be done for each frame.
This module is imported by the plotting routines and then the
function setplot is called to set the plot parameters.
"""
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt... |
from __future__ import absolute_import
import platform
import unittest
from .x86translator import X86TranslationTestCase
@unittest.skipUnless(platform.machine().lower() == 'x86_64',
'Not running on an x86_64 system')
class X86TranslationArithmeticTests(X86TranslationTestCase):
def test_adc(self... |
def most_frequent(coded, index):
counts = {}
i = index
while i < len(coded):
nr = coded[i]
if nr in counts:
counts[nr] += 1
else:
counts[nr] = 1
i += 3
rev = [(freq, cod) for (cod, freq) in counts.items()]
(max_freq, max_freq_cod) = max(rev)
return max_freq_cod
def decode(coded, ... |
"""
Created on Mon Feb 21, 2011
@author:Isabel Restrepo
Adds the error of a portion of voxels. Each block is processed in a separate thread.
This script assumes that the reconstruction error at each voxel has been computed
"""
import os;
import bvpl_octree_batch
import multiprocessing
import Queue
import time
import ra... |
import binascii
import hashlib
import itertools
import random
import struct
import pyDes
from . import asn1
from . import constants
from . import types
class ValidationException(types.KerberosException):
pass
def _nfold(outlen, instr):
"""instr is a string (which represents binary data, not unicode or
anyth... |
import brukva
import tornado.httpserver
import tornado.web
import tornado.websocket
import tornado.ioloop
from brukva import adisp
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('app')
c = brukva.Client()
c.connect()
def on_set(result):
log.debug("set result: %s" % result)
c.set('fo... |
from unittest import SkipTest
import numpy as np
try:
import pandas as pd
import dask.dataframe as dd
except:
raise SkipTest("Could not import dask, skipping DaskInterface tests.")
from holoviews.core.data import Dataset
from holoviews.util.transform import dim
from .test_pandasinterface import BasePandasIn... |
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
admin.autodiscover()
from posts.views import PostArchiveIndexView, PostArchiveMonthView, PostArchiveYearIndex, PostDetailView, PostListView, PostTagListView, sitemaps
from posts.feeds impor... |
"""
A set of benchmark tests in order to compare the speed of algorithms under different
graph types.
"""
import numpy
import logging
import time
import networkx
from apgl.graph import DenseGraph, SparseGraph, PySparseGraph, DictGraph
from exp.sandbox.graph.CsArrayGraph import CsArrayGraph
numpy.set_printoptions(suppre... |
from django.conf import settings
class UncertaintyMiddleware(object):
def __init__(self, get_response):
"""A Django middleware to introduced controlled uncertainty into the stack. It is controlled
by the DJANGO_UNCERTAINTY setting, were the developers can specify (using the provided
behaviou... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 5, transform = "Fisher", sigma = 0.0, exog_count = 20, ar_order = 0); |
from CensusMapperFlask import app
from db_models import *
from flask import request, Flask, jsonify, render_template
@app.route('/map', methods = ['POST'])
def update_measure():
cartocss = "#censusgeo { polygon-fill: rgb(178,226,226); line-width: .1; line-color: #444444; polygon-opacity: 0; line-opacity: 0;[ measur... |
"""
test_encoders
----------------------------------
Tests for `standardjson.encoders` module.
"""
import unittest
from standardjson.encoder_funcs import encode_datetime, encode_date, encode_time, encode_decimal
import datetime
import json
import decimal
def test_encode_datetime():
""" encode_datetime() should retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.