code stringlengths 1 199k |
|---|
""" VoiceApp base class
This is just a first cut at the VoiceApp. Do NOT assume that
the interfaces here won't be entirely rewritten in the future.
In fact, ASSUME that they will be rewritten entirely. Repeatedly.
"""
from shtoom.doug.events import TimeoutEvent, CallStartedEvent
from shtoom.doug.events impo... |
import __builtin__
import importlib
import inspect
import pkgutil
import etcd
import maps
import sys
import time
from tendrl.commons import flows
from tendrl.commons import objects
from tendrl.commons.utils.central_store import utils as cs_utils
from tendrl.commons.objects import BaseAtom
from tendrl.commons.utils impo... |
import mysql
from mysql import connector
def init():
try:
cursor.execute("""CREATE DATABASE IF NOT EXISTS sms DEFAULT CHARSET utf8 COLLATE utf8_general_ci""")
#conn.select_db("sms")
cursor.execute("""
CREATE TABLE `sms`.`tosend`(
`mid` int NOT NULL UNIQUE AUTO_INCREMENT,
... |
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
from collections import UserList
from sqlalchemy import and_, distinct
from sqlalchemy import case
from sqlalchemy import func
from sqlalchemy import or_
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarat... |
from easy import Mapping
import numpy as np
import math
class DistanceMapping(Mapping):
'''a hooke-like distance mapping:
f(p1, p2) = norm(p2 - p1) - rest_length
'''
# TODO add pairs
def __init__(self, node, **kwargs):
Mapping.__init__(self, node, **kwargs)
self.rest_length = 0
d... |
import sys
from JSBSim_utils import CreateFDM, Table, SandBox
sandbox = SandBox('check_cases', 'orbit')
fdm = CreateFDM(sandbox)
fdm.load_script(sandbox.path_to_jsbsim_file('scripts', 'ball_orbit.xml'))
fdm.run_ic()
while fdm.run():
pass
ref, current = Table(), Table()
ref.ReadCSV(sandbox.elude(sandbox.path_to_jsbs... |
from tendrl.commons import singleton
import sys
def test_to_singleton():
cls_body = dict(__doc__='docstring', __name__='Dummy class', __module__='modname')
cls = type('Dummy', (object,), cls_body)
ret = singleton.to_singleton(cls)
retClass = ret()
assert isinstance(retClass,cls)
ret_class = ret(... |
"""Basic widgets and various utility functions.
"""
import pyj2d as pygame
from const import *
import widget
from errors import PguError
def parse_color(desc):
if (is_color(desc)):
# Already a color
return desc
elif (desc and desc[0] == "#"):
# Because of a bug in pygame 1.8.1 we need to... |
from pycp2k.inputsection import InputSection
from ._hf6 import _hf6
from ._ri_g0w03 import _ri_g0w03
from ._im_time3 import _im_time3
from ._ri_axk3 import _ri_axk3
class _ri_rpa3(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Quadrature_points = None
self.Size_freq_inte... |
from statistics_tester import StatisticsTester
def run( args = [] ):
StatisticsTester().run()
if __name__ == "__main__":
import sys
run( sys.argv ) |
import numpy as np
from matplotlib import pyplot as plt
def make_default_q_curve(Snom, Qmin, Qmax, n=3):
"""
Compute the generator capability curve
:param Snom: Nominal power
:param Qmin: Minimum reactive power
:param Qmax: Maximum reactive power
:param n: number of points, at least 3
:retur... |
import sys
_msg = '''
--------------------------------------------------------------------------------
WARNING: saga-python is deprecated!
Your application will still work - but "saga-python" has been renamed to
"radical.saga". Please change your imports from
import saga
to
import radic... |
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import os
import re
import time
import datetime
import textwrap
import getpass
import readline
import django
import paramiko
import errno
import pyte
import operator
import struct, fcntl, signal, socket, select
from io import open as copen
import uuid
os.environ['DJ... |
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from rest_framework import status
from coreapi import Client
from coreapi.exceptions import ErrorMessage
from wsse import settings
from wsse.compat import reverse_lazy
from wsse.server.django.wsse.models ... |
import os
from copy import copy
from threading import RLock
from weboob.capabilities.base import BaseObject, Capability, FieldNotFound, NotAvailable, NotLoaded
from weboob.exceptions import ModuleInstallError
from weboob.tools.compat import basestring, getproxies
from weboob.tools.log import getLogger
from weboob.tools... |
import os
import shutil
import tempfile
from auto_vot_extract_features import *
from helpers.utilities import *
if __name__ == "__main__":
# parse arguments
parser = argparse.ArgumentParser(description='Train a classifier to automatically measure VOT, using manually '
... |
from numpy import zeros
from dolfin import Constant, FunctionSpace, split, TestFunction, TrialFunction
from rbnics.backends.dolfin.wrapping.expression_replace import replace
from rbnics.backends.dolfin.wrapping.dirichlet_bc import DirichletBC
from rbnics.utils.decorators import overload
def assemble_operator_for_restri... |
from qtaste import *
def step1():
"""
@step Check that variable myVariable is not defined
@expected Variable myVariable is not defined
"""
try:
myVariable
except NameError:
pass
else:
testAPI.stopTest(Status.FAIL, "Variable myVariable is already defined.")
def step2()... |
from twisted.internet import epollreactor
epollreactor.install()
from twisted.internet import protocol,reactor,ssl
from twisted.protocols.basic import LineReceiver
from twisted.application.service import Application
from twisted.application import internet,app
from twisted.web import http,server
from twisted.web.proxy ... |
import os
from werkzeug.datastructures import FileStorage
from flask_restful import reqparse
from flask import current_app
from brainminer.base.api import HtmlResource
from brainminer.compute.dao import SessionDao
from brainminer.base.util import generate_string, get_x
from brainminer.base.api import HtmlResource
impor... |
import math
import pytest
import psi4
import forte
def test_spinorbital_mp2():
import forte
import forte.utils
from math import isclose
import numpy as np
geom = """0 1
H
F 1 1.0
symmetry c1
"""
basis = '6-31g'
Escf, wfn = forte.utils.psi4_scf(geom, basis, 'rhf')
forte_ob... |
APPS = [
"schbuilder",
"_schtools.schauth",
"schcomponents.standard_components",
"_schtools.schcommander",
"_schtools.schtools",
"_schtools.schtasks",
"_schtools.schsimplescripts",
]
APPS_EXT = []
PUBLIC = True
MAIN_PRJ = False
GUI_COMMAND_LINE = "--no_splash --websocket_id=/schbuilder/clock... |
import configparser
import ast
from PyQt5.QtGui import QOpenGLShader, QOpenGLShaderProgram, QVector2D, QVector3D, QVector4D, QMatrix4x4, QColor, QImage, QOpenGLTexture, QOpenGLVertexArrayObject, QOpenGLBuffer
from UM.Logger import Logger
from UM.Math.Vector import Vector
from UM.Math.Matrix import Matrix
from UM.Math.C... |
from pycp2k.inputsection import InputSection
from ._each76 import _each76
class _program_run_info10(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
self.Filename = None
... |
import unittest
import os
import datetime
import tempfile
from cStringIO import StringIO
from pysheets.exceptions import IntegrityError, InvalidFileError
from pysheets.writers.csv import CSVWriter
from pysheets.sheet import Sheet
class CSVWriterTest(unittest.TestCase):
""" Tests for :py:class:`pysheets.writers.csv.... |
"""
Automatic concatenation of multiple cubes over one or more existing dimensions.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
import six
from collections import defaultdict, namedtuple
from copy import deepcopy
import biggus
imp... |
import os, inspect
currentdir = os.path.dirname(os.path.realpath(os.path.abspath(inspect.getfile(inspect.currentframe()))))
fenrirPath = os.path.dirname(currentdir)
from configparser import ConfigParser
from fenrirscreenreader.core import debugManager
from fenrirscreenreader.core import memoryManager
from fenrirscreenr... |
import arctic
import numpy as np
from astropy.io import fits
hdulist = fits.open('../demo/jbke01rkq_drkA.fits')
hdulist.info()
data = hdulist[0].data
header = hdulist[0].header
date = hdulist[0].header['DATE']
date += +2452334.5
print( data.shape )
c = arctic.cte_image_neo()
p = c.parameters
print( 'express=%i' % p.e... |
from lunchinator.plugin import iface_db_plugin, lunch_db
import sys, sqlite3, threading, Queue, datetime, os
from lunchinator import get_server, get_settings, convert_raw
from lunchinator.plugin.iface_plugins import PasswordOption
from db_SQLite.multithreaded_sqlite import MultiThreadSQLite
class db_MySQL(iface_db_plug... |
import zmq
conteudo = zmq.Context()
print("Conectando com o servidor MQL...")
socket = conteudo.socket(zmq.REQ)
socket.connect("tcp://192.168.1.4:5555")
while (True):
socket.send("fibonacci")
arquivo = open('fibonacci.txt','w')
# Recebendo uma mensagem
mensagem = socket.recv()
print("Resposta do se... |
"""Определяет схемы URL для пользователей"""
from django.conf.urls import url
from django.contrib.auth.views import login
from . import views
urlpatterns = [
# Страница входа
url(r'^login/$', login, {'template_name': 'users/login.html'},
name='login'),
url(r'^logout/$', views.logout_view, name='logout')... |
def main(m, limit):
sols = [0]*(m*2)
sols[m] = 1
total_len = m+1
while sols[total_len-1] + 1 < limit:
if total_len == len(sols) - 2:
sols = double_list_size(sols)
for start_pos in range(0,total_len - (m-1)):
for l in range(m,total_len - start_pos + 1):
... |
from __future__ import division, unicode_literals
import base64
import io
import itertools
import os
import time
import xml.etree.ElementTree as etree
from .common import FileDownloader
from .http import HttpFD
from ..compat import (
compat_urlparse,
compat_urllib_error,
)
from ..utils import (
struct_pack,... |
import os
import subprocess
import argparse
def setoptconsts(opts):
opts.VERSION = '0.0.0'
return opts
def parseargs():
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--sep', type=int, default=1, help='Define columns space')
parser.add_argument('-w', '--width', type=int, default=0, he... |
import unittest
from typing import List
import utils
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
result = 0
lo = 0x7FFFFFFF
for price in prices:
if price < lo:
lo = price
else:
profit = price - lo - fee
... |
from django.contrib.auth.models import User
class EmailAuthBackend(object):
def authenticate(self, request, username=None, password=None):
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
return None
except... |
import pygame
from pygame.locals import *
import Menu_Object
from image_loader import get_image
class menu(object):
def __init__(self, screen): #surface, color, x, y, length, height, width, text, text_color, font size
self.screen = screen
self.SP_button = Menu_Object.Button(screen, (135, 12, 12), 10... |
"""
Simple Network Management Protocol (TCP/IP protocol stack)
""" |
"""
Support for functionality to interact with FireTV devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.firetv/
"""
import functools
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
MediaPl... |
import setuptools
version = '0.1.3'
setuptools.setup(
name='rax_default_network_flags_python_novaclient_ext',
version=version,
url='http://pypi.python.org/packages/source/r/rax_default_network_flags_python_novaclient_ext/rax_default_network_flags_python_novaclient_ext-%s.tar.gz' % version,
license='Apac... |
from __future__ import division
import os
import sys
import xml.dom.minidom
import re
import math
from svg_regex import svg_parser
from svg_transform import svg_transform_parser
import optparse
from yocto_css import parseCssString
try:
from decimal import *
except ImportError:
print >>sys.stderr, "Scour requires ... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('people', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Tweet',
fields=[
('id', models.AutoField... |
"""
This component provides basic support for the Philips Hue system.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/hue/
"""
import ipaddress
import logging
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const impor... |
from random import shuffle
from tsptest import test
def randomised(distances, names, drunk_factor):
shuffle(names)
names.append(names[0])
return names
test(randomised) |
import json
import re
from tempest import config
from tempest import exceptions
from tempest.lib.common.utils import test_utils
from tempest.scenario import manager
from tempest import test
CONF = config.CONF
class TestServerBasicOps(manager.ScenarioTest):
"""The test suite for server basic operations
This smok... |
from __future__ import absolute_import, division, print_function
import errno
import os
import os.path
import requests
import shutil
import sys
import re
try:
# Python 3
from urllib.request import urlretrieve
except ImportError:
# Python 2
from urllib import urlretrieve
def mkdir_p(dir, clobber=False):
if clobber ... |
"""
Monkey Patch script for mbed build options
"""
import workspace_tools.options
class MbedOptionsOverride(object):
def newoptparse(self):
parser = self.oldfunc()
# Add some of our own options
# This is just to avoid option parser from bombing out
# when it sees options it doesn't ... |
import collections
import inspect
import sys
import types
import uuid
import eventlet
import eventlet.event
from oslo_log import log as logging
import yaql.context
from murano.common.i18n import _LW
import murano.dsl.attribute_store as attribute_store
import murano.dsl.dsl_exception as dsl_exception
import murano.dsl.e... |
import warnings
import numpy as np
import layers
from framework import Program, Variable, program_guard
import unique_name
from layer_helper import LayerHelper
from initializer import Constant
__all__ = [
'Accuracy',
'ChunkEvaluator',
'EditDistance',
'DetectionMAP',
]
def _clone_var_(block, var):
as... |
from django.conf import settings
from django.urls import reverse
from daiquiri.core.constants import ACCESS_LEVEL_PUBLIC
from daiquiri.metadata.models import Schema
from daiquiri.registry.vo import get_curation
from .serializers import SchemaSerializer
def get_resource():
return {
'service': 'tap',
... |
import logging
from django.core.mail import send_mail
from django.core.management.base import BaseCommand
from uw_space import Facilities
from myuw.models import CampusBuilding
from myuw.util.settings import get_cronjob_recipient, get_cronjob_sender
BUILDING_CODES = [
"AAB",
"AAC",
"ACC",
"ADA",
"AD... |
"""Feature testing utilities."""
import distutils
import distutils.spawn
import os
from typing import Text
def _has_command(command: Text) -> bool:
"""Determines whether a command is available in the user's shell.
Args:
command: The name of the command.
Returns:
Whether the command exists.
"""
return ... |
__version__ = '0.3.1' |
import copy
import fixtures
import mock
from neutron_lib import context
from neutron_lib.db import api as db_api
from neutron_lib.db import constants as db_const
from neutron_lib.exceptions import flavors as flav_exc
from neutron_lib.plugins import constants
from oslo_config import cfg
from oslo_utils import uuidutils
... |
"""Constants for the Gree Climate integration."""
COORDINATORS = "coordinators"
DATA_DISCOVERY_SERVICE = "gree_discovery"
DATA_DISCOVERY_INTERVAL = "gree_discovery_interval"
DISCOVERY_SCAN_INTERVAL = 300
DISCOVERY_TIMEOUT = 8
DISPATCH_DEVICE_DISCOVERED = "gree_device_discovered"
DISPATCHERS = "dispatchers"
DOMAIN = "gr... |
import logging
log = logging.getLogger(__name__)
class Kestrel(object):
def __init__(self, redis):
self.redis = redis
def job_id(self):
p = self.redis.pipeline()
p.incr('jobs:next_id', 1)
p.get('jobs:next_id')
result = p.execute()
return result[1]
def register... |
from neutron.db import model_base
from neutron.db import models_v2
import sqlalchemy as sa
class HPSwitchLAGPort(model_base.BASEV2, models_v2.HasId):
"""Define HP switch LAG port properties."""
external_lag_id = sa.Column(sa.String(255))
class HPSwitchPort(model_base.BASEV2, models_v2.HasId):
"""Define HP s... |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath( path.dirname( __file__ ) )
with open( path.join( here, 'README.md' ), e... |
from ceilometerclient import client as ceclient
import ceilometerclient.v2.client as ceclient_v2
from unittest import mock
from cinderclient import client as ciclient
from cinderclient.v3 import client as ciclient_v3
from glanceclient import client as glclient
from gnocchiclient import client as gnclient
from gnocchicl... |
import datetime
import random
import csv
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from models import TimeStamp, SensorDescription, SensorData
def index(request):
"""
Lists latest instrument measurements
"""
try:
latestStamp = TimeStamp.... |
"""This module contains `Module` attribute representing a module which contains other models or callables."""
import inspect
import sys
from types import ModuleType
from typing import Any
from typing import Callable as CallableT
from typing import List
from typing import Optional
from typing import Union
from .. import... |
from django.conf.urls import url
from django.utils import timezone
from django.views.generic import RedirectView
from . import views
def get_current_date_str():
now = timezone.now()
return timezone.template_localtime(now).strftime("%Y-%m-%d")
urlpatterns = [
url(r'^$', views.index, name='index'),
# ex: ... |
import json
import os
import re
import sys
import csv
import datetime
from collections import OrderedDict
reload(sys)
sys.setdefaultencoding('utf8')
_TOP_LEVEL_DIRECTORY = "C:/Path/To/Repository/Parent"
_CONTENT_DIRECTORY = "./rutherford-content/content"
ignore_biology = True
video_regex = re.compile(r'([\&\?]v=|/embed... |
import os
from oslo_log import log as logging
from oslo_config import cfg
from suds.client import Client as SudsClient
from suds.transport.https import HttpAuthenticated
from designate import exceptions
from designate import utils
from designate.backend import base
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
WSDL... |
import unittest
import numpy
from pyscf import lib
from pyscf.pbc.df import df
import pyscf.pbc.gto as pgto
from pyscf.pbc.lib import kpts_helper
from pyscf import ao2mo
L = 5.
n = 3
cell = pgto.Cell()
cell.a = numpy.diag([L,L,L])
cell.mesh = numpy.array([n,n,n])
cell.atom = '''He 3. 2. 3.
He... |
import os
import sys
import time
import eventlet
from oslo.config import cfg
import pyudev
from quantum.agent.linux import ip_lib
from quantum.agent.linux import utils
from quantum.agent import rpc as agent_rpc
from quantum.agent import securitygroups_rpc as sg_rpc
from quantum.common import config as logging_config
fr... |
import pytest
import enums_test
def test_total_ordering_w_same_enum_type():
to_compare = enums_test.OneEnum.SOME_VALUE
for item in enums_test.OneEnum:
if item.value < to_compare.value:
assert not to_compare == item
assert to_compare != item
assert not to_compare < ite... |
class TbpScraperPipeline(object):
def process_item(self, item, spider):
return item |
from contextlib import contextmanager
print("Imported contextmanager!: %r" % contextmanager) |
import matlab.engine
import numpy
import oct2py
import os
def setroot(engine, root=None):
engine.addpath(os.path.join(*[p for p in [os.path.dirname(os.path.dirname(__file__)), root] if p]))
class OctaveWithMatlabInterface:
def __init__(self, engine):
self.engine = engine
def __getattr__(self, name):... |
from nltk.book import *
print sorted(set(text3))
print len(set(text3)) |
"""Support for exposing Home Assistant via Zeroconf."""
from __future__ import annotations
import asyncio
from contextlib import suppress
from dataclasses import dataclass
import fnmatch
from ipaddress import IPv4Address, IPv6Address, ip_address
import logging
import socket
import sys
from typing import Any, Final, cas... |
input = """
% Example Input
% t(1,5).
% t(2,3).
% t(3,1).
% t(4,4).
% t(5,2).
% p(1,2).
% p(2,3).
% p(3,1).
% patternlength(3).
% Guess suitable subsequence
%1 <= { subt(K,I,E) : t(I,E) } <= 1 :- K=1..L, patternlength(L).
kval(1).
kval(N+1) :- kval(N), N < L, patternlength(L).
1 <= { subt(K,I,E) : t(I,E) } <= 1 :- kval... |
"""Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... |
from flask import render_template, request, redirect, g, flash, url_for, jsonify
from flask_login import login_required
from flask_babel import lazy_gettext, gettext
from datetime import datetime, timedelta
from web import app, admin_permission, get_backup_directory, is_usb_storage_connected
from services.milkcollectio... |
from sqlalchemy import and_
from sqlalchemy import or_
from ggrc.models import person
from ggrc import db
from ggrc.models import relationship
"""Contains the Assignable mixin. This allows adding various assignee types
to the object, like Verifier, Requester, etc.
"""
class Assignable(object):
ASSIGNEE_TYPES = set(... |
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from account.models import User
class CustomUserAdmin(UserAdmin):
list_display = ('email', 'fullname', 'date_joined', 'is_staff')
list_filter = ('is_staff', 'is_superuser', 'is_active')
s... |
class POI(object):
def __init__(self, id, name, type, lat=None, lon=None, type_name=None, identifiers=None, short_name=None,
distance=0, address="", phone="", website="", opening_hours="", collection_times="",
parent=None, children=None, alternative_names=None, shape="", name_sort=... |
from oslo_config import cfg
from oslo_log import log
from neutron_lib.api.definitions import port as p_api
from neutron_lib.api.definitions import portbindings
from neutron_lib.api.definitions import trunk as t_api
from neutron_lib.api.definitions import trunk_details as td_api
from neutron_lib.callbacks import events
... |
from pyspark.context import SparkContext
from pyspark.sql.dataframe import DataFrame
from pyspark.rdd import RDD
from pyspark.sql import SQLContext
from h2o.frame import H2OFrame
from pysparkling.utils import FrameConversions as fc
import warnings
try:
import h2o
from h2o.frame import H2OFrame
has_h2o = Tru... |
import os, sys
from ConfigParser import SafeConfigParser
CONFIG_DIR = os.getenv("HOME") + "/.dockery"
CONFIG_FILE = "default.config"
CREDENTIALS_FILE_CONTENT = """\
[xap.default]
username=gigaspace
[xap.prod]
username=vilu02
"""
class Settings(object):
def __init__(self, environment):
self.environment = env... |
import logging
import sys
import threading
import time
import xml.etree.ElementTree as ET
class _TextRecorder(object):
"""Record test result to stdout.
"""
def __init__(self, opts, logger):
self._opts = opts
self._logger = logger
def start(self, case):
if case == 1:
s... |
'''
Created on 28 Mar 2014
@author: davesnowdon
'''
import urllib2
import json
import collections
import random
import os
import mailchimp
import kivy
kivy.require('1.7.1')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.spinn... |
"""Evaluation functions for IPDF models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import io
from absl import logging
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_graphics.geometry.transformation as tfg... |
from __future__ import absolute_import
import pytest
import numpy as np
import nnabla as nn
import nnabla.experimental.graph_converters as GC
from nnabla.ext_utils import get_extension_context
from .ref_graphs.resnets import small_cl_resnet, small_cf_resnet
from nbla_test_utils import list_context
ctxs = list_context('... |
from __future__ import unicode_literals
from boxsdk.network.default_network import DefaultNetwork
from pprint import pformat
from box_manage_users.util import setup_logging
class LoggingNetwork(DefaultNetwork):
"""
SDK Network subclass that logs requests and responses.
"""
def __init__(self):
su... |
import PIL
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
import sys
import codecs
import commands
reload(sys)
sys.setdefaultencoding('utf-8')
def GenerateTxt2Pic(files):
"""
将文本文件转换成图片
"""
###以下几行是将windows格式的文件转换成linux可以cat的
stat,res = commands.getstatusoutput('file %s' % files)
... |
import os
import sys
import argparse
from tempest_parser import const
from tempest_parser.reports import reporter
from tempest_parser.reports.csv_reporter import CSVReporter
from tempest_parser.manager.test_manager import TestsManager
from tempest_parser.parser.tempest_log_parser import TempestLogParser
from tempest_pa... |
import requests
import json
from insights.client.connection import InsightsConnection
from mock.mock import MagicMock, Mock, patch
@patch("insights.client.connection.generate_machine_id", return_value='xxxxxx')
@patch("insights.client.connection.InsightsConnection._init_session")
@patch("insights.client.connection.Insi... |
from collections import OrderedDict
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_cor... |
"""Helper functions and classes."""
import os
from .universal import *
from .vsenv import setup_vsenv
if os.name == 'posix':
from .posix import *
elif os.name == 'nt':
from .win32 import *
else:
from .platform import * |
from indy import ledger, signus
from indy.error import ErrorCode, IndyError
import json
import pytest
@pytest.mark.asyncio
async def test_submit_request_works(pool_handle):
request = {
"reqId": 1491566332010860,
"identifier": "Th7MpTaRZVRYnPiabds81Y",
"operation": {
"type": "105"... |
from django.db import models
from core.models import TimeStampedModel
from subjects.models import Subject
from researchers.models import Researcher
from surveys.models import Survey
class Treatment(TimeStampedModel):
name = models.CharField(max_length=150)
description = models.CharField(max_length=1024)
par... |
import json
import uuid
import scrapy
import logging
from scrapy.http import Request
from scrapy.conf import settings
from lxmlhtml import LxmlLinkExtractor as LinkExtractor
from crawler.items.rawresponse import RawResponseItem
from redis_spider import RedisSpider
class LinkSpider(RedisSpider):
'''
A spider tha... |
from pandaharvester.harvestercore import core_utils
from .base_stager import BaseStager
baseLogger = core_utils.setup_logger('rse_direct_stager')
class RseDirectStager(BaseStager):
"""In the workflow for RseDirectStager, workers directly upload output files to RSE
and thus there is no data motion in Harvester."... |
"""Model transformations."""
import json
from collections.abc import Iterator
from json.decoder import JSONDecodeError
from ..utils.functions import asymmetric_decrypt, asymmetric_encrypt, unique, uuid, DecryptionError
from ..utils.type import EditScope, ItemId
from .iterators import sources as iter_sources
from .queri... |
import sys
import os
import sphinx_rtd_theme
extensions = [
'sphinx.ext.autodoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Quick.JS'
copyright = u'2016, Michael Krause'
author = u'Michael Krause'
version = u'0.6.1b'
release = u'v0.6.1-beta'
language = None
exclude_pa... |
# File: genetic.py
import random
import statistics
import sys
import time
from bisect import bisect_left
from enum import Enum
from math import exp
def _generar_padre(longitud, geneSet, obtener_aptitud):
genes = []
while len(genes) < longitud:
tamañoMuestral = min(longitud - len(genes), len(geneSet))
... |
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
@login_required
def home(request):
return HttpResponse('<h1>blog.objcc.com</h1>') |
import argparse
from unittest.mock import patch
import pytest
from runners.pyocd import PyOcdBinaryRunner
from conftest import RC_BUILD_DIR, RC_GDB, RC_KERNEL_HEX, RC_KERNEL_ELF
TEST_PYOCD = 'test-pyocd'
TEST_ADDR = 0xadd
TEST_BOARD_ID = 'test-board-id'
TEST_FREQUENCY = 'test-frequency'
TEST_DAPARG = 'test-daparg'
TEST... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.