content stringlengths 4 20k |
|---|
from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
__author__ = "bigfatnoob"
import random
from collections import OrderedDict
import numpy as np
from utils.lib import O
from technix.tech_utils import Point, three_others, choice, S... |
DATE_FORMAT = 'l, j F, Y'
TIME_FORMAT = 'h:i:s a'
DATETIME_FORMAT = 'j F, Y h:i:s a'
YEAR_MONTH_FORMAT = 'F, Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'j.M.Y'
SHORT_DATETIME_FORMAT = 'j.M.Y H:i:s'
FIRST_DAY_OF_WEEK = 1 # (Monday)
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://d... |
"""
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import importlib
import os
import time
from django.conf import... |
# -------------------------- Write fixtures ---------------------------
# To regression test our wrappers we need examples. This script
# generates files. We save these files once, and regression_test.py
# re-generates these files to tests them for identicality with the
# presaved examples (fixtures). If they are found... |
from openid import message as message_module
class Extension(object):
"""An interface for OpenID extensions.
@ivar ns_uri: The namespace to which to add the arguments for this
extension
"""
ns_uri = None
ns_alias = None
def getExtensionArgs(self):
"""Get the string arguments t... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
def execute(filters=None):
if not filters: filters = {}
columns = get_columns(filters)
item_map = get_item_details(filters)
iwb_map = get_item_warehouse_map(filters)
data = []
for company in sorted(iwb_map):... |
"""Python 'uu_codec' Codec - UU content transfer encoding.
This codec de/encodes from bytes to bytes.
Written by Marc-Andre Lemburg (<EMAIL>). Some details were
adapted from uu.py which was written by Lance Ellinghouse and
modified by Jack Jansen and Fredrik Lundh.
"""
import codecs
import binascii
from io import By... |
import hashlib, hmac, os, struct, xbmc, xbmcgui, time
# Had to use this while loop to get the HDD key as it will be Busy for a second or two.
dialog = xbmcgui.Dialog()
hashlibsha1 = hashlib.sha1
Select_Folder = dialog.browse( 3,"Select folder to hash",'files','' )
contextmetafile = os.path.join( Select_Folder,'con... |
"""Multiple-producer-multiple-consumer signal-dispatching
dispatcher is the core of the PyDispatcher system,
providing the primary API and the core logic for the
system.
Module attributes of note:
Any -- Singleton used to signal either "Any Sender" or
"Any Signal". See documentation of the _Any class.
... |
from django.conf import settings
from django.contrib.sessions.backends.base import CreateError, SessionBase
from django.core.cache import caches
from django.utils.six.moves import range
KEY_PREFIX = "django.contrib.sessions.cache"
class SessionStore(SessionBase):
"""
A cache-based session store.
"""
... |
# coding: utf-8
from django.conf.urls import patterns, url
from app.floorMap import views
urlpatterns = patterns(
'',
# Floor map page
url(r'^$', views.FloorMapIndex.as_view(), name='index'),
# Settings page
url(r'^settings$', views.SettingsUpdate.as_view(), name='settings'),
# Forms for r... |
import sys
import os
import os.path
import json
import yaml
import filelock
from flask import jsonify, request
import minemeld.loader
from . import config
from .utils import running_config, committed_config
from .aaa import MMBlueprint
from .logger import LOG
__all__ = ['BLUEPRINT']
PROTOTYPE_ENV = 'MINEMELD_PRO... |
"""
Some unit tests for the S3Connection
"""
import time
import os
import urllib
from boto.s3.connection import S3Connection
from boto.exception import S3PermissionsError
# this test requires a devpay product and user token to run:
AMAZON_USER_TOKEN = '{UserToken}...your token here...'
DEVPAY_HEADERS = { 'x-amz-sec... |
import logging
import archinfo
import cle
from ....engines import SimEngineVEX
from .resolver import IndirectJumpResolver
l = logging.getLogger("angr.analyses.cfg.indirect_jump_resolvers.x86_elf_pic_plt")
class X86ElfPicPltResolver(IndirectJumpResolver):
"""
In X86 ELF position-independent code, PLT stubs... |
"""Base actions for the players to take."""
from csrv.model.actions import action
from csrv.model import cost
from csrv.model import errors
from csrv.model import events
from csrv.model import game_object
from csrv.model import parameters
class InstallUpgrade(action.Action):
DESCRIPTION = '[click]: Install an age... |
import numpy as np
from numpy.random import randn
from datetime import timedelta
import pandas as pd
import pandas.util.testing as tm
from pandas import (PeriodIndex, period_range, DataFrame, date_range,
Index, to_datetime, DatetimeIndex)
def _permute(obj):
return obj.take(np.random.permutati... |
from ctypes import *
import os
import sys
import unittest
import test.support
from ctypes.util import find_library
libc_name = None
def setUpModule():
global libc_name
if os.name == "nt":
libc_name = find_library("c")
elif os.name == "ce":
libc_name = "coredll"
elif sys.platform == "cy... |
import math
from .exceptions import *
def format_option_for_cfour(opt, val):
"""Function to reformat value *val* for option *opt* from python
into cfour-speak. Arrays are the primary target.
"""
text = ''
# Transform list from [[3, 0, 1, 1], [2, 0, 1, 0]] --> 3-0-1-1/2-0-1-0
if isinstance(va... |
"""Support for the PRT Heatmiser themostats using the V3 protocol."""
import logging
import voluptuous as vol
from homeassistant.components.climate import ClimateDevice, PLATFORM_SCHEMA
from homeassistant.components.climate.const import (
SUPPORT_TARGET_TEMPERATURE)
from homeassistant.const import (
TEMP_CELS... |
import sqlalchemy as sa
from neutron.common import exceptions
from neutron.db import model_base
from neutron.db import models_v2
class Quota(model_base.BASEV2, models_v2.HasId):
"""Represent a single quota override for a tenant.
If there is no row for a given tenant id and resource, then the
default for... |
from copy import deepcopy
DEFAULTS = dict(
color=dict(mag='darkblue', grad='b', eeg='k', eog='k', ecg='m', emg='k',
ref_meg='steelblue', misc='k', stim='k', resp='k', chpi='k',
exci='k', ias='k', syst='k', seeg='saddlebrown', dbs='seagreen',
dipole='k', gof='k', bio='k'... |
import errno
import os
import socket
import sys
from TTransport import *
class TSocketBase(TTransportBase):
def _resolveAddr(self):
if self._unix_socket is not None:
return [(socket.AF_UNIX, socket.SOCK_STREAM, None, None,
self._unix_socket)]
else:
return socket.getaddrinfo(self.... |
from __future__ import unicode_literals
from __future__ import absolute_import
from tg import tmpl_context as c, app_globals as g
from alluratest.tools import assert_equal
from alluratest.controller import setup_basic_test, setup_global_objects
from allura import model as M
from allura.lib import security
from allura... |
import res_partner
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
import os
import unittest
from ..deserializers import CoverageDeserializer
from ..deserializers import NosetestDeserializer
from ..parsers import NosetestParser
from ..parsers import RadonParser
def _get_data_filename(filename):
return os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'... |
#!/usr/bin/env python3
import logging
import re
import subprocess
from functools import wraps
from string import Template
from flask import abort, request
TOKENS = []
REGEX_USERNAME = re.compile('^\w{1,20}$')
logger = logging.getLogger(__name__)
def authorize_badtoken(f):
@wraps(f)
def check_token(*args, ... |
import os
import sys
import install_venv_common as install_venv # noqa
def print_help(venv, root):
help = """
OpenStack development environment setup is complete.
OpenStack development uses virtualenv to track and manage Python
dependencies while in development and testing.
To activate the Ope... |
import json
import math
from dojo.models import Finding
class PhpSecurityAuditV2(object):
def __init__(self, filename, test):
tree = filename.read()
try:
data = json.loads(str(tree, 'utf-8'))
except:
data = json.loads(tree)
dupes = dict()
for filepa... |
#!/usr/bin/env python
"""
Example script to control a Scrapy server using its JSON-RPC web service.
It only provides a reduced functionality as its main purpose is to illustrate
how to write a web service client. Feel free to improve or write you own.
Also, keep in mind that the JSON-RPC API is not stable. The recomm... |
"""
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
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOU... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: meraki_vlan
short_description: Manage VLANs in the Meraki cloud
version_added: "2.7"
d... |
from PWGJE.EMCALJetTasks.Tracks.analysis.base.struct.THnSparseWrapper import THnSparseWrapper,AxisFormat
from copy import copy,deepcopy
class AxisFormatClustersOld(AxisFormat):
'''
Axis format for old cluster THnSparse
'''
def __init__(self):
'''
Constructor
'''
Axi... |
from unittest import TestCase
from . import BackendTestMixin
from embed_video.backends import YoutubeBackend, UnknownIdException
class YoutubeBackendTestCase(BackendTestMixin, TestCase):
urls = (
('http://youtu.be/jsrRJyHBvzw', 'jsrRJyHBvzw'),
('http://youtu.be/n17B_uFF4cA', 'n17B_uFF4cA'),
... |
from flask import Blueprint, flash, redirect, render_template, request, url_for, jsonify
import braintree
import os
from os.path import join, dirname
from dotenv import load_dotenv, find_dotenv
blueprint = Blueprint('payments', __name__, static_folder='../static')
# dotenv_path = join('..', '..', dirname(__file__), '... |
"""Launch a local http server, then launch a executable directed at the server.
This command creates a local server (on port 5103 by default) then runs:
<executable> <args..> http://localhost:<port>/<page>.
Where <page> can be set by -P, or uses index.html by default.
"""
import argparse
import copy
import getos
i... |
#! /usr/bin/python
"""
led_adc_example.py
By Paul Malmsten, 2010
<EMAIL>
A simple example which sets up a remote device to read an analog value
on ADC0 and a digital output on DIO1. It will then read voltage
measurements and write an active-low result to the remote DIO1 pin.
"""
from xbee import XBee
import serial... |
import abc
import functools
import os
import tempfile
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils
import six
from nova.i18n import _LE, _LW
from nova import utils
LOG = logging.getLogger(__name__)
libvirt_opts = [
c... |
import subprocess
import collections
import itertools
import yaml
from ansible import utils, errors
from ansible.runner import return_data
class ActionModule (object):
BYPASS_HOST_LOOP = True
NEEDS_TMPPATH = False
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, mo... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError
from itertools import chain
class Group:
''' a group of ansible hosts '''
# __slots__ = [ 'name', 'hosts', 'vars', 'child_groups', 'parent_groups', 'depth', '_hosts_cache' ]
... |
"""Impact HTML5 Gaming benchmark.
Tests one very specific use case: smooth running games rendered with the
<canvas> element. The score for the HTML5-Benchmark takes the total time the
browser spent rendering frames (formula is 1000000/(sqrt(totalTime) + lagTime *
0.1)). The benchmark automatically runs at a reasonable... |
"""Utility library containing various helpers used by the API.
Contains miscellaneous functions used internally by the API.
"""
__author__ = '<EMAIL> (David Byttow)'
import document
CUSTOM_SERIALIZE_METHOD_NAME = 'Serialize'
def IsListOrDict(inst):
"""Returns whether or not this is a list, tuple, set or dict ... |
import warnings
from django.forms import models as model_forms
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseRedirect
from django.utils.encoding import force_text
from django.views.generic.base import TemplateResponseMixin, ContextMixin, View
from django.views.generic.deta... |
"""Implements a time series model with seasonality, trends, and transients."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.timeseries.python.timeseries.state_space_models import level_trend
from tensorflow.contrib.timeseries.pyth... |
import volatility.plugins.addrspaces.paged as paged
import volatility.obj as obj
import struct
ptrs_page = 2048
entry_size = 8
pde_shift = 21
ptrs_per_pde = 512
page_shift = 12
ptrs_per_pae_pgd = 512
ptrs_per_pae_pte = 512
class AMD64PagedMemory(paged.AbstractWritablePagedMemory):
""" Standard AMD 64-bit address... |
"""_mysql_exceptions: Exception classes for _mysql and MySQLdb.
These classes are dictated by the DB API v2.0:
http://www.python.org/topics/database/DatabaseAPI-2.0.html
"""
from exceptions import Exception, StandardError, Warning
class MySQLError(StandardError):
"""Exception related to operation with ... |
# -*- coding: utf-8 -*-
"""
wechatpy.messages
~~~~~~~~~~~~~~~~~~
This module defines all the messages you can get from WeChat server
:copyright: (c) 2014 by messense.
:license: MIT, see LICENSE for more details.
"""
import copy
from wechatpy.fields import BaseField, DateTimeField, FieldDescriptor... |
import doctest
import os
import unittest
from babel import core
from babel.core import default_locale
class DefaultLocaleTest(unittest.TestCase):
def setUp(self):
self._old_locale_settings = self._current_locale_settings()
def tearDown(self):
self._set_locale_settings(se... |
import json
import random
import subprocess
import unittest
import requests
import mock
from swift.common.swob import Request
from swifthlm import middleware as swifthlm
class FakeApp(object):
def __init__(self, headers=None):
if headers:
self.headers = headers
else:
self... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
"""
This is a very trivial example of how any callback function can get at play and task objects.
play will be 'None' for runner in... |
import os
import re
from enum import Enum
from .. import utilities
from ..board import VariantBoard
from ..snapshot import Snapshot
from ..tessellation import Tessellation
from .puzzle import Puzzle, PuzzleSnapshot
class SOKFileFormat:
@classmethod
def read(cls, src_stream, dest_collection, tessellation_hint... |
from __future__ import unicode_literals
import datetime
import json
import re
import sys
import time
from email.header import Header
from django.conf import settings
from django.core import signals, signing
from django.core.exceptions import DisallowedRedirect
from django.core.serializers.json import DjangoJSONEncode... |
#! /usr/bin/env python
from __future__ import division
import pyaudio
import wave
import sys
import scipy
import numpy as np
import struct
CHUNK = 2**10
#from scikits.audiolab import flacread
from numpy.fft import rfft, irfft
from numpy import argmax, sqrt, mean, diff, log
import matplotlib
from scipy.signal import... |
from couchpotato.core.helpers.variable import splitString
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
import pynma
import six
log = CPLog(__name__)
class NotifyMyAndroid(Notification):
def notify(self, message = '', data = None, listener = None):
... |
from __future__ import print_function, absolute_import, division
from mdtraj.utils.six.moves import xrange
import os
import mdtraj as md
import numpy as np
import tables
import warnings
from mdtraj import io
import logging
logger = logging.getLogger(__name__)
def _setup_containers(project, assignments_fn, distances_... |
import codecs
from collections import OrderedDict
import datetime
import os
import platform
import re
import shutil
class Model: pass
def fix_filename_for_system(fname):
if platform.system() == "Windows":
return re.sub("[?\[\]/\\=+<>:;\"\*]", "_", fname)
if platform.system() == "Linux":
retur... |
from keras.models import Model, Sequential
from keras.layers import Input
from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D, UpSampling2D
from keras.layers.normalization import BatchNormalization
from keras.layers.core import Layer, Activation, Reshape, Permute
def set_architecture(n_classes,... |
"""Fixer for intern().
intern(s) -> sys.intern(s)"""
# Local imports
from .. import pytree
from .. import fixer_base
from ..fixer_util import Name, Attr, touch_import
class FixIntern(fixer_base.BaseFix):
BM_compatible = True
order = "pre"
PATTERN = """
power< 'intern'
trailer< lpar='('
... |
from spack import *
class PyCython(PythonPackage):
"""The Cython compiler for writing C extensions for the Python language."""
homepage = "https://pypi.python.org/pypi/cython"
url = "https://pypi.io/packages/source/c/cython/Cython-0.25.2.tar.gz"
version('0.25.2', '642c81285e1bb833b14ab3f43996408... |
def get_fake_test_case():
return {
"total": {
"failures": 1,
"tests": 2,
"errors": 0,
"time": 1.412},
"test_cases": {
"fake.failed.TestCase.with_StringException[gate,negative]": {
"name":
"fake.failed.Tes... |
import importlib
import logging
import threading
from telegram.conf.settings import SETTINGS
from telegram.core.bot import BOT
from telegram.core.message import RequestMessage, ResponseMessage
class RequestQueue(object):
def __init__(self):
self.requests_list = []
self.requests_list_condition = t... |
import uuid
import datetime
import bson
from st2tests import DbTestCase
from st2common.util import date as date_utils
from tests.unit.base import FakeModel, FakeModelDB
class TestPersistence(DbTestCase):
@classmethod
def setUpClass(cls):
super(TestPersistence, cls).setUpClass()
cls.access =... |
from mymongo import MyMongo
from dnsclient import DNSClient
import random, time
import os, sys
import datetime
import re
dns_username = os.environ['FDNS_UN']
dns_password = os.environ['FDNS_PW']
print dns_username
print dns_password
mandrill_1 = os.environ['MANDRILL_1']
mandrill_2 = os.environ['MANDRILL_2']
dns = DNSC... |
"""
Schelling's segregation model.
"""
import random
from indra.agent import Agent
from indra.composite import Composite
from indra.display_methods import RED, BLUE
from indra.env import Env
from registry.registry import get_env, get_prop
from registry.registry import run_notice
from indra.utils import init_props
MO... |
# -*- encoding: utf-8 -*-
from supriya.tools.ugentools.MultiOutUGen import MultiOutUGen
class Balance2(MultiOutUGen):
r'''A stereo signal balancer.
::
>>> left = ugentools.WhiteNoise.ar()
>>> right = ugentools.SinOsc.ar()
>>> balance_2 = ugentools.Balance2.ar(
... left=le... |
'''
Monitor module
==============
The Monitor module is a toolbar that shows the activity of your current
application :
* FPS
* Graph of input events
Usage
-----
For normal module usage, please see the :mod:`~kivy.modules` documentation.
'''
__all__ = ('start', 'stop')
from kivy.uix.label import Label
from kivy.... |
"""A program to update /etc/hosts from our defintions"""
from __future__ import print_function
import os
import sys
def parse_line(line):
parts = line.split()
ip, names = parts[0], parts[1:]
return ip, names
def format_line(ip, names):
if names is None:
return str(ip)
names = sorted(list... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('fluent_pages', '0001_initial'),
('icekit', '0006_auto_20150911_0744'),
... |
"""
===================
Universal Functions
===================
Ufuncs are, generally speaking, mathematical functions or operations that are
applied element-by-element to the contents of an array. That is, the result
in each output array element only depends on the value in the corresponding
input array (or arrays) a... |
import numpy as np
import matplotlib.pyplot as plt
import essentia.standard as ess
M = 1024
N = 1024
H = 512
fs = 44100
spectrum = ess.Spectrum(size=N)
window = ess.Windowing(size=M, type='hann')
spectralPeaks = ess.SpectralPeaks()
hpcp = ess.HPCP()
x = ess.MonoLoader(filename = '../../../sounds/cello-double.wav', sam... |
"""One of the tests of the Face layer of RPC Framework."""
import unittest
from grpc_test._adapter import _face_test_case
from grpc_test.framework.face.testing import event_invocation_synchronous_event_service_test_case as test_case
class EventInvocationSynchronousEventServiceTest(
_face_test_case.FaceTestCase,... |
import logging
import string
import datetime
import re
_logger = logging.getLogger(__name__)
try:
import vatnumber
except ImportError:
_logger.warning("VAT validation partially unavailable because the `vatnumber` Python library cannot be found. "
"Install it to support... |
from django.db.backends.mysql.base import DatabaseOperations
from django.contrib.gis.db.backends.adapter import WKTAdapter
from django.contrib.gis.db.backends.base import BaseSpatialOperations
class MySQLOperations(DatabaseOperations, BaseSpatialOperations):
compiler_module = 'django.contrib.gis.db.models.sql.co... |
'''Extend Mock class with dictionary behavior.
Call it as:
mocked_dict = MockDict()
mocked_dict.add_dict_methods()'''
import mock
MagicMock__init__ = mock.MagicMock.__init__
class MockDict(mock.MagicMock):
def __init__(self, *args, **kwargs):
MagicMock__init__(self, *args, **kwargs)
... |
"""A simple web server for testing purpose.
It serves the testing html pages that are needed by the webdriver unit tests."""
import logging
import os
import socket
import threading
from io import open
try:
from urllib import request as urllib_request
except ImportError:
import urllib as urllib_request
try:
... |
import cherrypy
# 這是 MAN 類別的定義
'''
# 在 application 中導入子模組
import programs.cdag30.man as cdag30_man
# 加入 cdag30 模組下的 man.py 且以子模組 man 對應其 MAN() 類別
root.cdag30.man = cdag30_man.MAN()
# 完成設定後, 可以利用
/cdag30/man/assembly
# 呼叫 man.py 中 MAN 類別的 assembly 方法
'''
class MAN(object):
# 各組利用 index 引導隨後的程式執行
@cherrypy.expo... |
import sys
from paravistest import datadir, pictureext, get_picture_dir
from presentations import CreatePrsForFile, PrsTypeEnum
import pvserver as paravis
# Create presentations
myParavis = paravis.myParavis
# Directory for saving snapshots
picturedir = get_picture_dir("DeformedShape/B2")
file = datadir + "cube_he... |
import six
from webob import exc
from heat.api.openstack.v1 import util
from heat.common import param_utils
from heat.common import serializers
from heat.common import wsgi
from heat.rpc import api as rpc_api
from heat.rpc import client as rpc_client
class SoftwareConfigController(object):
"""WSGI controller for... |
from importlib import import_module
from django.apps import apps
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from .models import Proxy, UserProxy
update_proxy_permissions = import_module('django.contrib.auth.migra... |
from celery.states import ALL_STATES
def test_abstract_model_implementations(sa_session, sa_schedule, sa_child_news):
assert(isinstance(sa_schedule.id, int))
assert(isinstance(sa_child_news.id, int))
def test_abstract_schedule_implementation(
sa_scheduler, sa_session, sa_owner_model, sa_schedule):
... |
# coding: utf-8
# ## More solving the problem with some code before I write the code.
#
# 
#
# This post is a [continuation on solving a problem before writing the code]({filename}../meditations/mongodb-geojson/solving-a-ftlpd-data-delivery-problem-before-i-wri... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from tagging.models import Tag,TaggedItem
class TagVote(models.Model):
"""
Ho... |
"""Support for consuming values for the Volkszaehler API."""
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PORT, CONF_MONITORED_CONDITIONS, POWER_WATT,
ENERGY_WATT_... |
import argparse
import os
import platform
import shutil
import subprocess
import sys
import tarfile
from distutils.spawn import find_executable
wpt_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
sys.path.insert(0, os.path.abspath(os.path.join(wpt_root, "tools")))
from . import b... |
"""Decorators to categorize pofilter checks."""
from functools import wraps
#: Quality checks' failure categories
class Category(object):
CRITICAL = 100
FUNCTIONAL = 60
COSMETIC = 30
EXTRACTION = 10
NO_CATEGORY = 0
def critical(f):
@wraps(f)
def critical_f(self, *args, **kwargs):
... |
"""Simple examples of the REINFORCE algorithm."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
distributions = tf.contrib.distributions
sg = tf.contrib.bayesflow.stochastic_graph
st = tf.contrib.bayesflow.stochastic_tensor
def... |
"""Updates a physical network"""
from baseCmd import *
from baseResponse import *
class updatePhysicalNetworkCmd (baseCmd):
typeInfo = {}
def __init__(self):
self.isAsync = "true"
"""physical network id"""
"""Required"""
self.id = None
self.typeInfo['id'] = 'uuid'
... |
DEFAULT_CONF_FILENAME = None
DEFAULT_DIRS = ['logs', 'tftp-root']
DEFAULT_CMD_BINARY = 'in.tftpd'
DEFAULT_CMD_USER = 'nobody'
DEFAULT_CMD_GROUP = 'nogroup'
DEFAULT_CMD_TEMPLATE = \
'''
touch {{ log_file }}
sudo chown {{ user }}:{{ group }} {{ log_file }}
chmod -R 777 {{ tftp_root }}
sudo chown -R {{ user }}:{{ group }}... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from librar... |
"""
This test file will test registration, login, activation, and session activity timeouts
"""
import datetime
import time
import unittest
import mock
from ddt import data, ddt, unpack
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.url... |
"""
Functions for working with "safe strings": strings that can be displayed safely
without further escaping in HTML. Marking something as a "safe string" means
that the producer of the string has already turned characters that should not
be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
"""
... |
#!/usr/bin/env python
from flask import Flask, render_template, request
from flask_assets import Environment
from controller import get_rooms, get_word_counter_processed, get_room_name, get_username, process_word_cnts
from flask_socketio import SocketIO, join_room, send, emit
# Set this variable to "threading", "event... |
from threading import Event
from twitter.common import log
from twitter.common.quantity import Amount, Time
from apache.aurora.admin.admin_util import format_sla_results, print_results
from apache.aurora.client.api import AuroraClientAPI
from apache.aurora.client.base import DEFAULT_GROUPING, check_and_log_response, ... |
from coalib.bearlib.languages import Language
from .taste import TasteError
class aspectbase:
"""
Base class for aspectclasses with common features for their instances.
Derived classes must use
:class:`coalib.bearlib.aspects.meta.aspectclass` as metaclass.
This is automatically handled by
:m... |
# -*- coding: utf-8 -*-
"""
test/socket
~~~~~~~~~~~
Test the BufferedSocket implementation in hyper.
"""
import pytest
import hyper.common.bufsocket
from hyper.common.bufsocket import BufferedSocket
from hyper.common.exceptions import ConnectionResetError, LineTooLongError
# Patch the select method in bufsocket to m... |
from collections import OrderedDict
from typing import Dict, Type
from .base import ConversionAdjustmentUploadServiceTransport
from .grpc import ConversionAdjustmentUploadServiceGrpcTransport
# Compile a registry of transports.
_transport_registry = (
OrderedDict()
) # type: Dict[str, Type[ConversionAdjustmentU... |
import urllib, urlparse, re
from HTMLParser import HTMLParser
class miniHTMLParser( HTMLParser ):
viewedQueue = []
instQueue = []
def setBaseUrl(self, url):
self.baseUrl = url
def getNextLink( self ):
if self.instQueue == []:
return None
else:
return self.instQueue.pop(0)
def han... |
from django.utils.translation import ugettext_lazy as _
from openstack_dashboard.dashboards.project.routers import tables
class DeleteRouter(tables.DeleteRouter):
redirect_url = "horizon:project:network_topology:router"
class RoutersTable(tables.RoutersTable):
class Meta(object):
name = "Routers"
... |
"""
Registry's Client API
"""
import json
import os
from oslo.config import cfg
from glance.common import exception
import glance.openstack.common.log as logging
from glance.registry.client.v1 import client
LOG = logging.getLogger(__name__)
registry_client_ctx_opts = [
cfg.BoolOpt('send_identity_headers', defa... |
'''
SASSIE Copyright (C) 2011 Joseph E. Curtis
This program comes with ABSOLUTELY NO WARRANTY;
This is free software, and you are welcome to redistribute it under certain
conditions; see http://www.gnu.org/licenses/gpl-3.0.html for details.
'''
# System imports
from distutils.core import *
from distut... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/getall... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.