code stringlengths 1 199k |
|---|
from django.utils.translation import ugettext_lazy as _
import horizon
class AlarmsVitrage(horizon.Panel):
name = _("Alarms")
slug = "vitragealarms" |
"""
.. module: lemur.authorizations.models
:platform: unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Netflix Secops <secops@netflix.com>
"""
from sqlalchemy import Column, Integer, String
from sqlalchemy_utils import JSONType... |
import json
from tests import base
from girder import events
from girder.constants import AccessType
from server import constants
def setUpModule():
base.enabledPlugins.append('provenance')
base.startServer()
def tearDownModule():
base.stopServer()
class ProvenanceTestCase(base.TestCase):
def setUp(self... |
""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import Glob... |
DOCUMENTATION = '''
---
module: ec2_ami_find
version_added: 2.0
short_description: Searches for AMIs to obtain the AMI ID and other information
description:
- Returns list of matching AMIs with AMI ID, along with other useful information
- Can search AMIs with different owners
- Can search by matching tag(s), by ... |
"""Tests for common notifications."""
import copy
from oslo.config import cfg
from nova.compute import flavors
from nova.compute import task_states
from nova.compute import vm_states
from nova import context
from nova import db
from nova.network import api as network_api
from nova import notifications
from nova import ... |
import diventi.accounts.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0050_auto_20190421_2252'),
]
operations = [
migrations.AlterModelManagers(
name='diventiuser',
managers=[
('objects', ... |
import logging
from django.conf import settings
from django.http import HttpResponseRedirect
from common import api
from common import exception
class VerifyInstallMiddleware(object):
def process_request(self, request):
logging.info("VerifyInstallMiddleware")
logging.info("Path %s" % request.path)
if not ... |
"""schmankerl URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
from __future__ import absolute_import, division, print_function
from contextlib import closing
import os
import socket
from tornado.concurrent import Future
from tornado.netutil import bind_sockets, Resolver
from tornado.queues import Queue
from tornado.tcpclient import TCPClient, _Connector
from tornado.tcpserver imp... |
import logging
from taskflow.patterns import linear_flow
from pumphouse import exceptions
from pumphouse import events
from pumphouse import task
LOG = logging.getLogger(__name__)
class RetrieveUser(task.BaseCloudTask):
def execute(self, user_id):
user = self.cloud.keystone.users.get(user_id)
self.c... |
"""Profiler to check if there are any bottlenecks in your code."""
import logging
import os
from abc import ABC, abstractmethod
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Callable, Dict, Generator, Iterable, Optional, TextIO, Union
from pytorch_lightning.utilities.cloud_io im... |
__author__ = 'mwn'
import os
import sys
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
app = Flask(__name__)
app.config.from_object('config')
handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.DEBUG)
app.logger.add... |
'''
@author: sheng
@license:
'''
SPELL=u'láogōng'
CN=u'劳宫'
NAME=u'laogong21'
CHANNEL='pericardium'
CHANNEL_FULLNAME='PericardiumChannelofHand-Jueyin'
SEQ='PC8'
if __name__ == '__main__':
pass |
{
'!langcode!': 'bg',
'!langname!': 'Български',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN',
'"User Exception" debug mode. ': '"User... |
from flask import Flask, jsonify, request, abort, make_response
from futu_server_api import *
from db import save_update_token
from db import delete_tokens
from db import list_cards
import logging
import logging.config
import json
app = Flask(__name__)
logging.config.fileConfig('./conf/log.ini')
no_db_logger = logging.... |
import json
import logging
import os
import unittest
import datetime
import MySQLdb
import environment
import tablet
import vtbackup
import utils
from mysql_flavor import mysql_flavor
use_mysqlctld = False
use_xtrabackup = False
stream_mode = 'tar'
tablet_master = None
tablet_replica1 = None
tablet_replica2 = None
back... |
import os
from django.core.management.color import supports_color
from django.utils import termcolors
class VerboseCommandMixin(object):
def __init__(self, *args, **kwargs):
super(VerboseCommandMixin, self).__init__(*args, **kwargs)
self.dry_run = False
if supports_color():
opts ... |
import time
from pynfcreader.sessions.iso14443.iso14443a import Iso14443ASession
def test_iso_14443_a_card_1_generic(hydranfc_connection):
hn = Iso14443ASession(drv=hydranfc_connection, block_size=120)
hn.connect()
hn.field_off()
time.sleep(0.1)
hn.field_on()
hn.polling()
r = hn.send_apdu("0... |
"""This code example creates new proposals.
To determine which proposals exist, run get_all_proposals.py.
"""
import uuid
from googleads import ad_manager
ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID... |
__author__ = 'Javier'
class Project(object):
def __init__(self, forks, stars, watchs):
self._forks = int(forks)
self._stars = int(stars)
self._watchs = int(watchs)
@property
def forks(self):
return self._forks
@property
def stars(self):
return self._stars
... |
import uuid
import mox
from oslo.config import cfg
from quantumclient.v2_0 import client
from nova.compute import instance_types
from nova import context
from nova import exception
from nova.network import model
from nova.network import quantumv2
from nova.network.quantumv2 import api as quantumapi
from nova import tes... |
"""
.. py:currentmodule:: FileFormat.SimulationParameters
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
MCXRay simulation parameters input file.
"""
__author__ = "Hendrix Demers (hendrix.demers@mail.mcgill.ca)"
__version__ = ""
__date__ = ""
__copyright__ = "Copyright (c) 2012 Hendrix Demers"
__licen... |
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head: return None
p = head
listLen = 0 # calculate list length
while p:
p = p.next
listLen += 1
k = k % listLen # now k < listLen
if k == 0:
return head
p1 = head; ... |
test = {
'name': 'Question 2',
'points': 2,
'suites': [
{
'type': 'sqlite',
'setup': r"""
sqlite> .open hw1.db
""",
'cases': [
{
'code': r"""
sqlite> select * from colors;
red|primary
blue|primary
green|secondary
... |
import time, logging
from artnet import dmx, fixtures, rig
from artnet.dmx import fades
log = logging.getLogger(__name__)
r = rig.get_default_rig()
g = r.groups['all']
def all_red():
"""
Create an all-red frame.
"""
g.setColor('#ff0000')
g.setIntensity(255)
return g.getFrame()
def all_blue():
"""
Create an all-... |
"""Tests for config_path."""
from absl.testing import absltest
from absl.testing import parameterized
from ml_collections.config_flags import config_path
from ml_collections.config_flags.tests import fieldreference_config
from ml_collections.config_flags.tests import mock_config
class ConfigPathTest(parameterized.TestC... |
"""Create an API definition by interpreting a discovery document.
This module interprets a discovery document to create a tree of classes which
represent the API structure in a way that is useful for generating a library.
For each discovery element (e.g. schemas, resources, methods, ...) there is
a class to represent i... |
"""Training utility functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six import string_types
import random
import re
import json
import numpy as np
import traceback
from cognitive import stim_generator as sg
import cognitive.constants as con... |
"""Reach oracle element used for configuration."""
import dataclasses
from pyreach.gyms import reach_element
@dataclasses.dataclass(frozen=True)
class ReachOracle(reach_element.ReachElement):
"""A Reach Oracle configuration class.
Attributes:
reach_name: The name of the Oracle.
task_code: The task code stri... |
import apache_beam as beam
import logging
from typing import List, Dict, Any
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils as utils
from models.execution import DestinationType, AccountConfig
from models.oauth_credentials import ... |
import sys
sys.path.insert(1, "../../../")
import h2o
def link_functions_tweedie_basic(ip,port):
# Connect to h2o
h2o.init(ip,port)
print "Read in prostate data."
hdf = h2o.upload_file(h2o.locate("smalldata/prostate/prostate_complete.csv.zip"))
print "Testing for family: TWEEDIE"
print "Set vari... |
__author__ = 'Autio'
from distutils.core import setup
import py2exe
setup(windows=['ShitCrimson.py']) |
def test_dummy_request():
from rasa.nlu.emulators.no_emulator import NoEmulator
em = NoEmulator()
norm = em.normalise_request_json({"text": ["arb text"]})
assert norm == {"text": "arb text", "time": None}
norm = em.normalise_request_json({"text": ["arb text"], "time": "1499279161658"})
assert no... |
from boundary import ApiCli
class SourceList(ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.path = "v1/account/sources/"
self.method = "GET"
def getDescription(self):
return "Lists the sources in a Boundary account" |
# Задача 2. Вариант 8.
#Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Лао-Цзы. Не забудьте о том, что автор должен быть упомянут на отдельной строке.
# Ionova A. K.
#30.04.2016
print("Нельзя обожествлять бесов.\n\t\t\t\t\t\t\t\tЛао-цзы")
inp... |
from fruits import validate_fruit
fruits = ["banana", "lemon", "apple", "orange", "batman"]
print fruits
def list_fruits(fruits, byName=True):
if byName:
# WARNING: this won't make a copy of the list and return it. It will change the list FOREVER
fruits.sort()
for index, fruit in enumerate(fruit... |
from airflow import AirflowException
from airflow.contrib.hooks.gcp_compute_hook import GceHook
from airflow.contrib.utils.gcp_field_validator import GcpBodyFieldValidator
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class GceBaseOperator(BaseOperator):
"""
Abstrac... |
import cherrypy
import functools
import logging
import logging.handlers
import os
import six
import sys
import traceback
from girder.constants import LOG_ROOT, MAX_LOG_SIZE, LOG_BACKUP_COUNT, TerminalColor, VERSION
from girder.utility import config, mkdir
from girder.utility._cache import cache, requestCache, rateLimit... |
"""
Copyright 2016 Andrea McIntosh
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 w... |
"""Tests for the Windows Setupapi log parser."""
from __future__ import unicode_literals
import unittest
from plaso.parsers import setupapi
from tests.parsers import test_lib
class SetupapiLogUnitTest(test_lib.ParserTestCase):
"""Tests for the Windows Setupapi log parser.
Since Setupapi logs record in local time, t... |
"""
crawler.py
~~~~~~~~~~~~~~
A brief description goes here.
"""
import csv
import urllib2
import urllib
import re
import os
import urlparse
import threading
import logging
import logging.handlers
import time
import random
import bs4
MINIMUM_PDF_SIZE = 4506
TASKS = None
def create_logger(filename, logger_na... |
from functools import partial
from typing import Callable, Iterable, Optional, Tuple, Union
from absl import logging
import numpy as np
from jax import core
from jax.interpreters import ad
from jax.interpreters import partial_eval as pe
from jax.interpreters import mlir
from jax.interpreters import pxla
from jax.interp... |
"""End-to-end test for the streaming wordcount example."""
from __future__ import absolute_import
import logging
import unittest
import uuid
from builtins import range
from hamcrest.core.core.allof import all_of
from nose.plugins.attrib import attr
from apache_beam.examples import streaming_wordcount
from apache_beam.i... |
import unittest
from elasticmagic.types import Integer, Float, Boolean
from elasticmagic.ext.queryfilter.codec import SimpleCodec
class SimpleCodecTest(unittest.TestCase):
def test_decode(self):
codec = SimpleCodec()
self.assertEqual(
codec.decode({'country': ['ru', 'ua', 'null']}),
... |
from transformers import RobertaTokenizerFast
import scattertext as st
tokenizer_fast = RobertaTokenizerFast.from_pretrained(
"roberta-base", add_prefix_space=True)
tokenizer = st.RobertaTokenizerWrapper(tokenizer_fast)
df = st.SampleCorpora.ConventionData2012.get_data().assign(
parse = lambda df: df.text.apply... |
print("###################################################")
print("Quadrant Finder 1.0")
print("Enter the x and y coordinates to find the quadrant!")
print("Type [exit] to quit the program")
print("###################################################")
xValue = None
yValue = None
while True:
# Get the input values ... |
import datetime
from unittest import mock
import ddt
from novaclient import client as nova_client
from novaclient import exceptions as nova_exceptions
from oslo_config import cfg
from oslo_config import fixture as conf_fixture
import testtools
from blazar import context
from blazar.db import api as db_api
from blazar.d... |
__source__ = 'https://leetcode.com/problems/equal-tree-partition/discuss/'
import unittest
class Solution(object):
pass # your function here
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
/**
* Definition for... |
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
... |
from xml.parsers.expat import ParserCreate
class DefaultSaxHandler(object):
def start_element(self, name, attrs):
print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))
def end_element(self, name):
print('sax:end_element: %s' % name)
def char_data(self, text):
print('sax:char... |
import http.server
import http.client
import json
import socketserver
class testHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
OPENFDA_API_URL = "api.fda.gov"
OPENFDA_API_EVENT = "/drug/event.json"
OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10'
def get_main_page(... |
import psutil
from ajenti.api import *
from ajenti.ui import *
@plugin
class NetworkManager (BasePlugin):
def get_devices(self):
return psutil.net_io_counters(pernic=True).keys()
@interface
class INetworkConfig (object):
interfaces = {}
@property
def interface_list(self):
return self.int... |
from keras import backend as K
class Config:
def __init__(self):
self.verbose = True
self.network = 'resnet50'
# setting for data augmentation
self.use_horizontal_flips = True
self.use_vertical_flips = True
self.rot_90 = True
# anchor box scales
self.anchor_box_scales = [1, 2, 4, 8, 16, 32, 64, 124, 25... |
"""Class representing the mapper for the parser init files."""
from plasoscaffolder.bll.mappings import base_mapping_helper
from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping
from plasoscaffolder.model import init_data_model
class ParserInitMapping(
base_sqliteplugin_mapping.BaseSQLitePluginMapper):... |
"""Python Library Boilerplate contains all the boilerplate you need to create a Python package."""
__author__ = 'Michael Joseph'
__email__ = 'michaeljoseph@gmail.com'
__url__ = 'https://github.com/michaeljoseph/sealeyes'
__version__ = '0.0.1'
def sealeyes():
return 'Hello World!' |
ADDRESS_GROUP = 'address_group'
AGENT = 'agent'
FLOATING_IP = 'floatingip'
LOCAL_IP_ASSOCIATION = 'local_ip_association'
NETWORK = 'network'
NETWORKS = 'networks'
PORT = 'port'
PORTS = 'ports'
PORT_BINDING = 'port_binding'
PORT_DEVICE = 'port_device'
PROCESS = 'process'
RBAC_POLICY = 'rbac-policy'
ROUTER = 'router'
ROU... |
import json
import os
from pprint import pprint as pp
from f5_cccl.resource.ltm.pool import *
from mock import MagicMock
import pytest
bigip_pools_cfg = [
{'description': None,
'partition': 'Common',
'loadBalancingMode': 'round-robin',
'monitor': '/Common/http ',
'membersReference': {
'... |
"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storag... |
from setuptools import setup, find_packages
setup(
name='trainer',
version='1.0.0',
packages=find_packages(),
description='Google Cloud Datalab helper sub-package',
author='Google',
author_email='google-cloud-datalab-feedback@googlegroups.com',
keywords=[
],
license="Apache Software License",
long_d... |
from panda3d.core import Camera
from direct.task.Task import Task
from otp.avatar import Emote
from toontown.television.TVScenes import *
from toontown.television.TVEffects import *
from toontown.suit.Suit import Suit
from toontown.suit.BossCog import BossCog
from toontown.suit.SuitDNA import SuitDNA
from toontown.toon... |
import cs50
import sys
def main():
if len(sys.argv) != 2:
print("You should provide cmd line arguments!")
exit(1)
#if sys.argv[1].isalpha() == False:
#print("You should provide valid key!")
#exit(1)
kplainText = int(sys.argv[1])
cipher = []
plainText = cs50.get_string... |
from voltha.protos.events_pb2 import AlarmEventType, AlarmEventSeverity, AlarmEventCategory
from voltha.extensions.alarms.adapter_alarms import AlarmBase
class OltLosAlarm(AlarmBase):
def __init__(self, alarm_mgr, intf_id, port_type_name):
super(OltLosAlarm, self).__init__(alarm_mgr, object_type='olt LOS',
... |
"""
osisoftpy.factory
~~~~~~~~~~~~
"""
from __future__ import (absolute_import, division, unicode_literals)
from future.builtins import *
from future.utils import iteritems
def create(factory, thing, session, webapi=None):
"""
Return an object created with factory
:param webapi:
:param factory:
:par... |
"""
This example loads the pre-trained SentenceTransformer model 'nli-distilroberta-base-v2' from the server.
It then fine-tunes this model for some epochs on the STS benchmark dataset.
Note: In this example, you must specify a SentenceTransformer model.
If you want to fine-tune a huggingface/transformers model like be... |
import unohelper
from com.sun.star.frame import XController, XTitle, XDispatchProvider
from com.sun.star.lang import XServiceInfo
from com.sun.star.task import XStatusIndicatorSupplier
class MRIUIController(unohelper.Base,
XController, XTitle, XDispatchProvider,
XStatusIndicatorSupplier, XServiceInfo):
""" ... |
"""Classes for converting the Code2Seq dataset to a PLUR dataset.
"""
import os
import tarfile
import apache_beam as beam
from plur.stage_1.plur_dataset import Configuration
from plur.stage_1.plur_dataset import PlurDataset
from plur.utils import constants
from plur.utils import util
from plur.utils.graph_to_output_exa... |
from pwn import *
exe = context.binary = ELF('./vuln')
def start(argv=[], *a, **kw):
'''Start the exploit against the target.'''
if args.GDB:
return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)
else:
return process([exe.path] + argv, *a, **kw)
gdbscript = '''
break *0x{exe.sym... |
"""Provides the setup for the experiments."""
from pytorch_pretrained_bert import modeling
from pytorch_pretrained_bert import tokenization
import torch
import embeddings_helper
def setup_uncased(model_config):
"""Setup the uncased bert model.
Args:
model_config: The model configuration to be loaded.
Returns:... |
"""Tests for suggestion registry classes."""
from __future__ import annotations
import datetime
import os
from core import feconf
from core import utils
from core.domain import config_services
from core.domain import exp_domain
from core.domain import exp_fetchers
from core.domain import exp_services
from core.domain i... |
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import dict
import os
import pytest
from mariobros import mariofile
SIMPLE_MARIOFILE = """[section_one]
text one
[section_two]
text two
"""
COMPLEX_MARIOFILE = """default text
[section] \ntext section
"""
GARBAGE_MARIOFI... |
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
volume = test_lib.lib_get_specific_stub('e2e_mini/volume', 'volume')
volume_ops = None
vm_ops = None
volume_name = 'volume-' + volume.get_time_postfix()
backup_name = 'backup-' + volume.get_time_postfix()
def test():
global ... |
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path):
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
... |
import copy
import os
from django.contrib import auth
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models import QuerySet
from django.test import TestCase, Client, mock
from django.urls import reverse
from ..forms import AddBookForm
from ..mode... |
print("\nназвание одного из двух спутников Марса:")
import random
satellite=["Фобос", "Деймос"]
s=random.choice(satellite)
print(s)
input("Нажмите Enter для выхода") |
def test_signal_wikidata_url(ranker):
rank = lambda url: ranker.client.get_signal_value_from_url("wikidata_url", url)
assert rank("http://www.douglasadams.com") > 0.5
assert rank("http://www.douglasadams.com/?a=b") > 0.5
assert rank("http://www.douglasadams.com/page2") == 0. # TODO, check domain?
a... |
DOCUMENTATION = '''
module: mt_system.py
author:
- "Valentin Gurmeza"
version_added: "2.4"
short_description: Manage mikrotik system endpoints
requirements:
- mt_api
description:
- manage mikrotik system parameters
options:
hostname:
description:
- hotstname of mikrotik router
required: True
use... |
"""Simple utility to merge multiple Kerberos keytabs into one.
This also cleans out duplicate and old keytab entries.
"""
import functools
import struct
ETYPES = {
1: 'des-cbc-crc',
2: 'des-cbc-md4',
3: 'des-cbc-md5',
4: None,
5: 'des3-cbc-md5',
6: None,
7: 'des3-cbc-sha1',
9: 'dsaWithSH... |
import time
import json
import base64
import requests
import subprocess
import pyVmomi
from pyVim import connect
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vmodl, vim
from heat.engine import constraints, properties, resource
from heat.openstack.common import log as logging
from neutronclient... |
from sqlalchemy import *
import hf
metadata = MetaData()
engine = None
def connect(implicit_execution=False):
config = dict(hf.config.items("database"))
hf.database.engine = engine_from_config(config, prefix="")
if implicit_execution:
metadata.bind = hf.database.engine
def disconnect():
pass |
from pylastica.query import Query
from pylastica.aggregation.min import Min
from pylastica.aggregation.nested import Nested
from pylastica.doc_type.mapping import Mapping
from pylastica.document import Document
from tests.base import Base
__author__ = 'Joe Linn'
import unittest
class NestedTest(unittest.TestCase, Base)... |
from __future__ import absolute_import
from __future__ import print_function
import getopt
import sys
import set_test_path
from happy.Utils import *
import WeavePing
if __name__ == "__main__":
options = WeavePing.option()
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:s:c:tuwqp:i:a:e:n:CE:T:",
... |
from sklearn.model_selection import StratifiedKFold
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier
from sklearn.metrics import confusion_matrix
from tools import ConfusionMatrixUtils
import pydotplus
import numpy as np
import matplotlib.pyp... |
"""Tests for DLT2T.registry."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from DLT2T.utils import modality
from DLT2T.utils import registry
from DLT2T.utils import t2t_model
import tensorflow as tf
class ModelRegistryTest(tf.test.TestCase):
def setUp(... |
from __future__ import absolute_import
from pychron.hardware.core.core_device import CoreDevice
class TempHumMicroServer(CoreDevice):
"""
http://www.omega.com/Manuals/manualpdf/M3861.pdf
iServer MicroServer
tested with iTHX-W
"""
scan_func = 'read_temperature'
def read_temperature(self, **kw... |
from onmetal_scripts.lib import states
from onmetal_scripts import reboot_unprovisioned
from onmetal_scripts.tests import base
import mock
class TestRebootUnprovisioned(base.BaseTest):
def setUp(self):
self.script = reboot_unprovisioned.RebootUnprovisioned()
self.script.get_argument = mock.Mock()
... |
"""Voluptuous schemas for the KNX integration."""
import voluptuous as vol
from xknx.devices.climate import SetpointShiftMode
from homeassistant.const import (
CONF_ADDRESS,
CONF_DEVICE_CLASS,
CONF_ENTITY_ID,
CONF_HOST,
CONF_NAME,
CONF_PORT,
CONF_TYPE,
)
import homeassistant.helpers.config_v... |
class DN(object):
def __init__(self, dn):
self._dn = dn.replace(',dn', '')
self._cn = []
self._displayName = []
self._givenName = []
self._homePhone = []
self._homePostalAddress = []
self._mail = []
self._mobile = []
self._o = []
self._objectClass = []
self._sn = []
sel... |
import re
userInput = raw_input("input equation\n")
numCount = 0
operandCount = 0
entryBracketCount = 0
exitBracketCount = 0
charCount = 0
endOfLine = len(userInput) - 1
for i in range(len(userInput)):
if (re.search('[\s*a-z\s*A-Z]+', userInput[i])):
charCount = charCount + 1
print operandCount, " 1"
elif (re.sea... |
"""
Support for KNX/IP climate devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.knx/
"""
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.climate import (
PLATFORM_SCHEMA, SUPPO... |
"""
WSGI config for comic project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` set... |
import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Reque... |
"""
Overview of all settings which can be customized.
"""
from django.conf import settings
from parler import appsettings as parler_appsettings
FLUENT_CONTENTS_CACHE_OUTPUT = getattr(settings, 'FLUENT_CONTENTS_CACHE_OUTPUT', True)
FLUENT_CONTENTS_PLACEHOLDER_CONFIG = getattr(settings, 'FLUENT_CONTENTS_PLACEHOLDER_CONFI... |
def permute1(seq):
if not seq: # Shuffle any sequence: list
return [seq] # Empty sequence
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute1(rest... |
from __future__ import absolute_import, unicode_literals
import django
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .managers import QueueManager, MessageManager
class Queue(models.Model):
name = models.CharField(_('name'), max_length=200, unique=True)
objects = Queu... |
from givabit.backend.charity import Charity
from givabit.backend.errors import MissingValueException, MultipleValueException
from givabit.test_common import test_data
from givabit.test_common import test_utils
class CharityRepositoryTest(test_utils.TestCase):
def setUp(self):
super(CharityRepositoryTest, se... |
from google.appengine.ext import db
import mc_unittest
from rogerthat.models import CompressedIntegerListExpando
class TestCase(mc_unittest.TestCase):
l = [1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1]
def setUp(self, datastore_hr_probability=0):
mc_unittest.TestCase.setUp(self, datastore_hr_probability=datast... |
from __future__ import absolute_import, division, print_function
import collections
from contextlib import contextmanager
import pytest
import six
from cryptography.exceptions import UnsupportedAlgorithm
import cryptography_vectors
HashVector = collections.namedtuple("HashVector", ["message", "digest"])
KeyedHashVector... |
"""FixMatch with Distribution Alignment and Adaptative Confidence Ratio.
"""
import os
import sys
from typing import Callable
import jax
import jax.numpy as jn
import objax
from absl import app
from absl import flags
from absl.flags import FLAGS
from objax.typing import JaxArray
from semi_supervised_domain_adaptation.l... |
import unittest
from mock import Mock
from mock import patch
from airflow import configuration
from airflow.contrib.hooks.jira_hook import JiraHook
from airflow import models
from airflow.utils import db
jira_client_mock = Mock(
name="jira_client"
)
class TestJiraHook(unittest.TestCase):
def setUp(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.