code stringlengths 1 199k |
|---|
import argparse
from common_processing import *
import tarfile
import sys
import glob
def untar(ftp_link, out_folder):
tar = tarfile.open(out_folder + ftp_link.split("/")[-1])
tar.extractall(path=out_folder)
tar.close()
def process_nodes_dmp(out_folder):
"""
extract data from file:nodes.dmp
crea... |
import logging
import time
import knitting_plugin
class DummyKnittingPlugin(knitting_plugin.BaseKnittingPlugin):
"""Implements a sample knitting plugin that allows for simple operation emulation."""
__PLUGIN_NAME__ = u"dummy"
def __init__(self):
super(DummyKnittingPlugin, self).__init__()
base_log_string = ... |
"""This module holds the common test code.
.. seealso:: `pytest good practices
<https://pytest.org/latest/goodpractices.html>`__ for why this module exists.
"""
import os
import sys
HERE = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(HERE, "../.."))
__builtins__["HERE"] = HERE |
import re
import pydbus
BASE_PATH = '/org/chemlab/UChroma'
SERVICE = 'org.chemlab.UChroma'
class UChromaClient(object):
def __init__(self):
self._bus = pydbus.SessionBus()
def get_device_paths(self) -> list:
dm = self._bus.get(SERVICE)
return dm.GetDevices()
def get_device(self, iden... |
"""
WSGI config for CongCards project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ... |
"""An RFC 2821 smtp proxy.
Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]
Options:
--nosetuid
-n
This program generally tries to setuid `nobody', unless this flag is
set. The setuid call will fail if this program is not run as root (in
which case, use this fl... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hischool.settings")
# Add the "core" and "extensions" folders to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "extensions"))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import re
import csv
import struct
import socket
import itertools
import argparse
import xml.etree.cElementTree as ET
if (sys.version_info < (3, 0)):
izip = itertools.izip
fd_read_options = 'r... |
import os, sys
origin_dir = 'del_201304now/'
new_dir = 'freq_event_state/'
files = os.listdir(origin_dir)
state_dir = {}
country_dir = {}
for file in files:
with open(origin_dir + file) as f:
event_dir = {}
for line in f:
tmp_content = line.split('\t')
code = tmp_content[4]
... |
"""
Exim SES Transport Entry Points
"""
from transport import SesSender
def main():
SesSender().run() |
import django
from django.db import models
from pytigon_lib.schdjangoext.fields import *
from pytigon_lib.schdjangoext.models import *
import pytigon_lib.schdjangoext.fields as ext_models
from pytigon_lib.schtools import schjson
from django.utils.translation import gettext_lazy as _
from django.contrib import admin
imp... |
from gen_data_from_rbprm import *
from hpp.corbaserver.rbprm.tools.com_constraints import get_com_constraint
from hpp.gepetto import PathPlayer
from hpp.corbaserver.rbprm.state_alg import computeIntermediateState, isContactCreated
from numpy import matrix, asarray
from numpy.linalg import norm
from spline import bezie... |
import os
import sys
import time
import inspect
from pyo import *
def play_example(cls, dur=5, toprint=True, double=False):
"""
Execute the documentation example of the object given as an argument.
:Args:
cls: PyoObject class or string
Class reference of the desired object example. If th... |
from __future__ import unicode_literals
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import io
import re
import string
from youtube_dl.extractor import YoutubeIE
from youtube_dl.utils import compat_str, compat_urlretrieve
_TESTS = [
(
'... |
'''
Find the median element in an unsorted array
'''
import heapq
def find_median(arr):
# O(n)
heapq.heapify(arr)
num_elements = len(arr)
if num_elements % 2 != 0:
return arr[(num_elements + 1)/2 - 1]
else:
return (arr[num_elements/2 - 1] + arr[num_elements/2 + 1 - 1])/2.0
assert fin... |
"""Suit + values are ints"""
from random import shuffle
class Card:
suits = ("spades", "hearts", "diamonds", "clubs")
values = (None, None, '2', '3',
'4', '5', '6', '7',
'8', '9', '10',
'Jack','Queen',
'King', 'Ace')
def __init__(self, v, s):
s... |
__author__ = 'ralmn' |
import re
def twinkle_lights(instruction, lights):
tokens = re.split(r'(\d+)', instruction)
operation = tokens[0].strip()
if operation == 'turn on':
twinkle = lambda x: x + 1
elif operation == 'turn off':
twinkle = lambda x: max(x - 1, 0)
elif operation == 'toggle':
twinkle =... |
import os
import sys
from flask import Flask, request, render_template
isDev = os.environ["SERVER_SOFTWARE"].find('Development') == 0
app = Flask( __name__ )
@app.route('/')
def home():
return render_template( 'index.html', isDev=isDev )
@app.errorhandler(404)
def page_not_found(e):
"""Return a custom 404 error.""... |
sum = 1
curr = 3
for width in xrange(3,1002,2):
inc = width - 1
sum = sum + curr #bottom right
curr = curr + inc
sum = sum + curr #bottom left
curr = curr + inc
sum = sum + curr #top left
curr = curr + inc
sum = sum + curr #top right
curr = curr + inc + 2
print sum |
import sys
import time
def make(session):
session.execute("make (%(rnd_name.0)s)")
a_guid = session.message()[1][-1]
assert(session.message() is None)
return(a_guid)
def link(session, a, l, b):
session.execute("make %s -[%s]> %s" % (a, l, b))
assert(session.message() is None)
def kill(session, a... |
"""Helpers that help with state related things."""
import asyncio
import datetime as dt
import json
import logging
from collections import defaultdict
from types import TracebackType
from typing import ( # noqa: F401 pylint: disable=unused-import
Awaitable, Dict, Iterable, List, Optional, Tuple, Type, Union)
from ... |
'''
Created on Oct 3, 2012
Copyright © 2013
The Board of Trustees of The Leland Stanford Junior University.
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.apach... |
from __future__ import annotations
import dataclasses
import inspect
import json
from dataclasses import dataclass
from enum import Enum
from typing import Any, Callable, Dict, Generic, List, Optional, Tuple, Type, cast, get_type_hints
from pants.base import deprecated
from pants.engine.goal import GoalSubsystem
from p... |
"""
WSGI config for meetingroom 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... |
"""
Implementation of hooks and APIs for outputting log messages.
"""
import sys
import traceback
import inspect
import json as pyjson
from threading import Lock
from functools import wraps
from io import IOBase
from pyrsistent import PClass, field
from . import _bytesjson as bytesjson
from zope.interface import Interf... |
import argparse
import pprint
import logging
import time
import os
import mxnet as mx
from config.config import config, generate_config, update_config
from config.dataset_conf import dataset
from config.network_conf import network
from symbols import *
from dataset import *
from core.loader import TestDataLoader
from c... |
from __future__ import annotations
import json
import logging
import re
from collections import defaultdict
from dataclasses import dataclass
from typing import DefaultDict
from pants.backend.shell.lint.shellcheck.subsystem import Shellcheck
from pants.backend.shell.shell_setup import ShellSetup
from pants.backend.shel... |
import logging
import tarfile
import tempfile
import os
import fabric.api
import fabric.operations
import cloudenvy.envy
class Dotfiles(cloudenvy.envy.Command):
def _build_subparser(self, subparsers):
help_str = 'Upload dotfiles from your local machine to an Envy.'
subparser = subparsers.add_parser(... |
import pycparser
def main_eg():
parser = pycparser.CParser()
buf = '''
int main( int argc, char** argv ) {
j = p && r || q;
return j;
}
'''
t = parser.parse( buf, 'x.c' )
return t
if __name__ == "__main__":
t = main_eg()
t.show() |
import sys
import os
import shlex
from datetime import date
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
copyright = u'2010-' + str(date.today().year) + u', koyi Inc'
author = u'koyi Inc'
language = 'ja'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
keep_warnings... |
from gapit_test_framework import gapit_test, require, require_equal
from gapit_test_framework import GapitTest, require_not_equal
from vulkan_constants import VK_SUCCESS
@gapit_test("vkDeviceWaitIdle_test")
class WaitForSingleQueue(GapitTest):
def expect(self):
device_wait_idle = require(self.nth_call_of("v... |
__author__ = 'juan'
import json
from termcolor import colored
import mysql.connector
import time
config = {
'user': 'elec',
'password': 'elec',
'host': 'thor.deusto.es',
'database': 'eu_test2',
}
class database:
def __init__(self):
self.con = mysql.connector.connect(**config)
def insert(... |
from .column_pair_values_equal import ColumnPairValuesEqual
from .column_pair_values_greater import ColumnPairValuesAGreaterThanB
from .column_pair_values_in_set import ColumnPairValuesInSet |
import copy
import datetime
import logging
import math
import operator
import traceback
from collections import namedtuple
from typing import Any, Dict, Optional, Tuple
from pyparsing import (
CaselessKeyword,
Combine,
Forward,
Group,
Literal,
ParseException,
Regex,
Suppress,
Word,
... |
"""Contains tests related to MLPerf.
Note this test only passes if the MLPerf compliance library is installed.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import Counter
import logging
import re
import six
import tensorflow.compat.v1 ... |
import d1_test.d1_test_case
import d1_test.instance_generator.person
@d1_test.d1_test_case.reproducible_random_decorator("TestPerson")
class TestPerson(d1_test.d1_test_case.D1TestCase):
def test_1000(self):
"""generate()"""
person_list = [
d1_test.instance_generator.person.generate().tox... |
"""A collection of ORM sqlalchemy models for Caravel"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import re
import functools
import json
import logging
import re
import textwrap
from collections import namedtuple
... |
"""
This file contains various constants and helper code to generate constants
that are used in the Statistical Variable renaming.
"""
import pandas as pd
import collections
import re
def capitalizeFirst(word):
""" Capitalizes the first letter of a string. """
return word[0].upper() + word[1:]
def standard_... |
import base64
import httpretty
import pytest
from selenium.common.exceptions import InvalidArgumentException
from appium.webdriver.webdriver import WebDriver
from test.unit.helper.test_helper import android_w3c_driver, appium_command, get_httpretty_request_body
class TestWebDriverRemoteFs(object):
@httpretty.activa... |
from abc import ABC, abstractmethod
from typing import List, Dict
from apache_beam.coders import PickleCoder, Coder
from pyflink.common import Row, RowKind
from pyflink.common.state import ListState, MapState
from pyflink.fn_execution.coders import from_proto
from pyflink.fn_execution.operation_utils import is_built_in... |
"""
Tests For misc util methods used with compute.
"""
from nova import db
from nova import flags
from nova import context
from nova import test
from nova import log as logging
from nova import utils
import nova.image.fake
from nova.compute import utils as compute_utils
from nova.compute import instance_types
from nova... |
class Vehicle(object):
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def foo(self, a, b, c):
print 'does some work'
print a, b, c
class Car(Vehicle):
def __init__(self, doors, *args):
Vehicle.__init__(self, *args)
... |
"""The tests for the logbook component."""
import collections
from datetime import datetime, timedelta
import json
import unittest
import pytest
import voluptuous as vol
from homeassistant.components import logbook, recorder
from homeassistant.components.alexa.smart_home import EVENT_ALEXA_SMART_HOME
from homeassistant... |
from types import ModuleType
from distutils.version import StrictVersion
from neutron.plugins.ml2.drivers import type_tunnel
from neutron import version
NEUTRON_VERSION = StrictVersion(str(version.version_info))
NEUTRON_NEWTON_VERSION = StrictVersion('9.0.0')
NEUTRON_OCATA_VERSION = StrictVersion('10.0.0')
NEUTRON_PIKE... |
"""Code to handle a Hue bridge."""
import asyncio
from functools import partial
from aiohttp import client_exceptions
import aiohue
import async_timeout
import slugify as unicode_slug
import voluptuous as vol
from homeassistant import core
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.help... |
from __future__ import division, print_function
import os, json
from glob import glob
import numpy as np
from scipy import misc, ndimage
from scipy.ndimage.interpolation import zoom
import keras
from keras import backend as K
from keras.layers.normalization import BatchNormalization
from keras.utils.data_utils import g... |
from __future__ import print_function, absolute_import
import re
class CNFParser(object):
"""Stream parser for DIMACS format"""
def __init__(self, file_object):
self.file_object = file_object
self.var_count = 0
self.clauses = []
self.remove_doubles = re.compile(r'\s\s+')
... |
from . import app, db
from flask import request, g, session, redirect
from Lotus.model.user import User
from hashlib import md5
from Lotus.lib.msg_code import Msg
import json
@app.route('/user/login', methods=['POST'])
def user_login():
email = request.form.get('email', None)
psw = request.form.get('psw', None)... |
import os
import sys
import numpy as np
sys.path.insert(0, os.getcwd() + '/../../tools/')
import lstm
import wb
import wer
def rescore_all(workdir, nbestdir, config):
for tsk in ['nbestlist_{}_{}'.format(a, b) for a in ['dt05', 'et05'] for b in ['real', 'simu']]:
print('process ' + tsk)
nbest_txt = ... |
from base import *
class Quagga(Container):
CONTAINER_NAME = None
GUEST_DIR = '/root/config'
def __init__(self, host_dir, conf, image='bgperf/quagga'):
super(Quagga, self).__init__(self.CONTAINER_NAME, image, host_dir, self.GUEST_DIR, conf)
@classmethod
def build_image(cls, force=False, tag=... |
"""This example gets all networks.
"""
from googleads import ad_manager
def main(client):
# Initialize appropriate service.
network_service = client.GetService('NetworkService', version='v201805')
networks = network_service.getAllNetworks()
# Print out some information for each network.
for network in network... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import numpy as np
import tensorflow as tf
from google.protobuf import text_format
from waymo_open_dataset.metrics.ops import py_metrics_ops
from waymo_open_dataset.protos import motion_metrics_pb2
c... |
from __future__ import unicode_literals
import os
from mopidy import config, exceptions, ext
__version__ = '0.2.2'
class GMusicExtension(ext.Extension):
dist_name = 'Mopidy-GMusic'
ext_name = 'gmusic'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__... |
import types
import unittest
from collections import namedtuple
import mock
from plugins.systems.config_container_crawler import ConfigContainerCrawler
from plugins.systems.config_host_crawler import ConfigHostCrawler
from plugins.systems.connection_container_crawler import ConnectionContainerCrawler
from plugins.syste... |
from flask_security.utils import hash_password
from cloudify.cluster_status import (
DB_STATUS_REPORTER,
BROKER_STATUS_REPORTER,
MANAGER_STATUS_REPORTER,
MANAGER_STATUS_REPORTER_ID,
BROKER_STATUS_REPORTER_ID,
DB_STATUS_REPORTER_ID
)
from manager_rest.storage.models import Tenant, UserTenantAssoc... |
"""ONEDrive resolvers.""" |
from __future__ import absolute_import
import logging
import struct
import six
from six.moves import xrange
import kafka.common
import kafka.protocol.commit
import kafka.protocol.fetch
import kafka.protocol.message
import kafka.protocol.metadata
import kafka.protocol.offset
import kafka.protocol.produce
from kafka.code... |
import datetime
from django.test.utils import override_settings
from django.urls import reverse
from django.utils import encoding
from django.utils import timezone
from horizon.templatetags import sizeformat
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
from openstack_dashboar... |
import ast
import glob
import itertools
import mmap
import os
import unittest
from typing import List
from parameterized import parameterized
ROOT_FOLDER = os.path.realpath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir)
)
class TestProjectStructure(unittest.TestCase):
def test_... |
def aVeryBigSum(n, ar):
return sum(ar)
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
result = aVeryBigSum(n, ar)
print(result) |
from __future__ import print_function
import re
maxThreads = 5 # This value will be over-written by the global default and possibly a command-line argument
colorTitle = None
colorFlag = None
colorFrom = None
colorDate = None
colorSubjectSeen = None
colorSubjectUnseen = None
showFlags = None
def setOptions( configFile,... |
"""Tests for constructing supercell models."""
import itertools
import numpy as np
from numpy.testing import assert_allclose
import pytest
from parameters import KPT, T_VALUES
import tbmodels
def get_equivalent_k(k, supercell_size):
return itertools.product(
*[
(np.linspace(0, 1, s, endpoint=Fal... |
from .inception import InceptionDao
from .models import DataMaskingRules, DataMaskingColumns
from simplejson import JSONDecodeError
import simplejson as json
import re
inceptionDao = InceptionDao()
class Masking(object):
# 脱敏数据
def data_masking(self, cluster_name, db_name, sql, sql_result):
result = {'s... |
import Tkinter as tk
def foo(*args):
print "foo!", args
import sys; sys.stdout.flush()
def __extend__(app):
extension = KeywordExtension(app)
app.bind_class("all", "<F5>", extension.make_keyword)
# this needs to add something to the tools menu...
class KeywordExtension(object):
def __init__(self... |
"""This example demonstrates the usage of SigOpt with Ray Tune.
It also checks that it is usable with a separate scheduler.
"""
import sys
import time
from ray import tune
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.suggest.sigopt import SigOptSearch
def evaluate(step, width, height):
retu... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dannysite_web.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from hazelcast.protocol.builtin import FixSizedTypesCodec, CodecUtil
from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import END_FRAME_BUF, END_FINAL_FRAME_BUF, SIZE_OF_FRAME_LENGTH_AND_FLAGS, create_initial_buffer_custom
from hazelcast.sql import SqlColumnMetadata
from hazelcast.protoc... |
from collections import OrderedDict
import functools
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core.client_options import ClientOptions
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core... |
import unittest
import copy
import tempfile
from pyscf import lib, gto, scf
from pyscf.tools import cubegen
mol = gto.Mole()
mol.atom = '''
O 0.00000000, 0.000000, 0.119748
H 0.00000000, 0.761561, -0.478993
H 0.00000000, -0.761561, -0.478993 '''
mol.verbose = 0
mol.build()
mf = scf.RHF(mol).run()
def tearDownModule(... |
"""Tests in OpenHTF.
Tests are main entry point for OpenHTF tests. In its simplest form a
test is a series of Phases that are executed by the OpenHTF framework.
"""
import argparse
import collections
import logging
import os
import sys
import textwrap
import threading
from types import LambdaType
import uuid
import we... |
"""Component for interacting with a Lutron Caseta system."""
from __future__ import annotations
import asyncio
import contextlib
import logging
import ssl
import async_timeout
from pylutron_caseta import BUTTON_STATUS_PRESSED
from pylutron_caseta.smartbridge import Smartbridge
import voluptuous as vol
from homeassistan... |
"""Generate SystemVerilog designs from IpBlock object"""
import logging as log
import os
from typing import Dict, Optional, Tuple
from mako import exceptions # type: ignore
from mako.template import Template # type: ignore
from pkg_resources import resource_filename
from .ip_block import IpBlock
from .lib import chec... |
import json
from typing import Tuple
from great_expectations.core.id_dict import IDDict
class MetricConfiguration:
def __init__(
self,
metric_name: str,
metric_domain_kwargs: dict,
metric_value_kwargs: dict = None,
metric_dependencies: dict = None,
):
self._metric... |
class TimestampAntiStealingLinkConfig(dict):
def __init__(self, json):
if json is not None:
if 'enabled' in json.keys():
self.enabled = json['enabled']
else:
self.enabled = None
if 'primaryKey' in json.keys():
self.primary_key = json['primaryKey']
else:
self... |
__author__ = 'ahb108'
from PIL import Image # Pillow with libjpeg support
from PIL import ImageDraw
import urllib3
import json
import re
import numpy as np
import argparse
import os
import urllib2
import zipfile
parser = argparse.ArgumentParser(description='This is a script to combine vector polygon masks into a binar... |
import csv
import re
csvfile = open('beijing_jt.csv','r')
reader = csv.reader(csvfile)
next(reader)
jt_info = next(reader)
print(jt_info[1].decode('utf-8'))
csvfile.close()
station_pattern = (r'(?P<number>[0-9]+)\s(?P<name>\D+)')
station_list = []
stations = re.findall(station_pattern,jt_info[-1].decode('utf-8'))
for t... |
"""Defines dataloader functionalities."""
import re
from typing import Any, Callable, Optional, Tuple
from clu import deterministic_data
import jax
from lib.datasets import billiard
from lib.datasets import trafficsigns
from lib.preprocess import image_ops
from lib.preprocess import preprocess_spec
import numpy as np
i... |
import copy
import sys
import os
import operator
import shlex
import warnings
import heapq
import bisect
import random
from subprocess import Popen, PIPE
from threading import Thread
from collections import defaultdict
from itertools import chain
from functools import reduce
from math import sqrt, log, isinf, isnan, po... |
import mock
from jacket.compute import exception
from jacket.compute import test
from jacket.tests.compute.unit.virt.libvirt import fakelibvirt
from jacket.compute import utils
from jacket.compute.virt.libvirt import host
from jacket.compute.virt.libvirt.volume import volume
SECRET_UUID = '2a0a0d6c-babf-454d-b93e-9ac99... |
"""Forwarding Rules Rule Scanner Test"""
from builtins import object
import unittest.mock as mock
from tests.unittest_utils import ForsetiTestCase
from google.cloud.forseti.scanner.scanners import forwarding_rule_scanner
from tests.unittest_utils import get_datafile_path
from google.cloud.forseti.common.gcp_type import... |
""" Tokenization class for model DeBERTa."""
from typing import List, Optional
from ...tokenization_utils import AddedToken
from ...utils import logging
from ..gpt2.tokenization_gpt2 import GPT2Tokenizer
logger = logging.get_logger(__name__)
VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
... |
"""Support for LaMetric notifications."""
import logging
from requests.exceptions import ConnectionError as RequestsConnectionError
import voluptuous as vol
from homeassistant.components.notify import (
ATTR_DATA, ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService)
from homeassistant.const import CONF_ICON
impor... |
import json
import os
import sys
from argparse import ArgumentTypeError
from datetime import datetime, timedelta
from c7n import cli, version, commands
from c7n.resolver import ValuesFrom
from c7n.resources import aws
from c7n.schema import ElementSchema, generate
from c7n.utils import yaml_dump, yaml_load
from .common... |
import os
import subprocess
import json
import hashlib
import time
from autopkglib import Processor, ProcessorError
__all__ = ["VirusTotalAnalyzer"]
DEFAULT_API_KEY = "3858a94a911f47707717f6d090dbb8f86badb750b0f7bfe74a55c0c6143e3de6"
DEFAULT_SLEEP = 15
ALWAYS_REPORT_DEFAULT = False
AUTO_SUBMIT_DEFAULT = False
AUTO_SUBM... |
import os
import subprocess
import errno
from JumpScale import j
PIPE = subprocess.PIPE
if subprocess.mswindows:
from win32file import ReadFile, WriteFile
from win32pipe import PeekNamedPipe
import msvcrt
else:
import select
import fcntl
if j.core.platformtype.myplatform.isLinux():
try:
... |
class ZiplineError(Exception):
msg = None
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.message = str(self)
def __str__(self):
msg = self.msg.format(**self.kwargs)
return msg
__unicode__ = __str__
__repr__ = __str__
class Wron... |
import itertools
import os
import struct
import json
import errno
from math import isnan
from os.path import isdir, exists, join, dirname, abspath, getsize, getmtime
from glob import glob
from bisect import bisect_left
izip = getattr(itertools, 'izip', zip)
try:
import fcntl
CAN_LOCK = True
except ImportError:
CA... |
from google.cloud import domains_v1
def sample_delete_registration():
# Create a client
client = domains_v1.DomainsClient()
# Initialize request argument(s)
request = domains_v1.DeleteRegistrationRequest(
name="name_value",
)
# Make the request
operation = client.delete_registration(... |
from Bio import SeqIO
import sys, string
fasta_file = "/Users/saljh8/GitHub/altanalyze/AltDatabase/EnsMart72/Hs/SequenceData/Homo_sapiens.GRCh37.72.cdna.all.fa" # Input fasta file
result_file = "/Users/saljh8/GitHub/altanalyze/AltDatabase/EnsMart72/Hs/SequenceData/Homo_sapiens.GRCh37.72.cdna.all.filtered.fa" # Output f... |
def getitem(v,d):
"Returns the value of entry d in v"
assert d in v.D
return v.f[d] if d in v.f else 0
def setitem(v,d,val):
"Set the element of v with label d to be val"
assert d in v.D
v.f[d] = val
def equal(u,v):
"Returns true iff u is equal to v"
assert u.D == v.D
union = set(u.f... |
import os
from oslo.config import cfg
from quantum.agent.linux import ip_lib
from quantum.agent.linux import utils
from quantum.openstack.common import log as logging
LOG = logging.getLogger(__name__)
OPTS = [
cfg.StrOpt('external_pids',
default='$state_path/external/pids',
help=_('Loc... |
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Sequence,
Tuple,
Optional,
Iterator,
)
from google.cloud.compute_v1.types import compute
class ListPager:
"""A pager for iterating through ``list`` requests.
This class thinly wraps an initial
:class:`google.cloud.... |
"""Tests for the Microsoft Office MRUs Windows Registry plugin."""
import unittest
from plaso.formatters import officemru # pylint: disable=unused-import
from plaso.formatters import winreg # pylint: disable=unused-import
from plaso.lib import eventdata
from plaso.lib import timelib
from plaso.parsers.winreg_plugins ... |
from mox import IsA # noqa
from django.core.urlresolvers import reverse # noqa
from django.core.urlresolvers import reverse_lazy # noqa
from django import http
from horizon.workflows import views
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
from openstack_dashboard.dashboa... |
"""Test classes for code snippet for modeling article."""
from appengine.ndb.modeling import relation_model_models as models
from google.appengine.ext import ndb
from tests import AppEngineTestbedCase
class ContactTestCase(AppEngineTestbedCase):
"""A test case for the Contact model with relationship model."""
d... |
import os.path
from uuid import uuid4
import shutil
import logging
logger = logging.getLogger(__name__)
_MARKER = object()
class FileUploadTempStore(object):
session_storage_slug = 'websauna.tempstore'
def __init__(self, request):
self.tempdir = request.registry.settings['websauna.uploads_tempdir']
... |
import ast
import types
import decimal
import unittest
a_global = 'global variable'
class TestCase(unittest.TestCase):
def assertAllRaise(self, exception_type, regex, error_strings):
for str in error_strings:
with self.subTest(str=str):
with self.assertRaisesRegex(exception_type,... |
import tensorflow as tf
import os
import sys
from copy import copy
from model.pipeline import Pipeline
from tensorflow.python import debug as tf_debug
if __name__ == "__main__":
num_keypoints = 30
patch_feature_dim = 8
decoding_levels = 5
kp_transform_loss = 1e4
base_recon_weight = 0.1
recon_wei... |
from tempest.api.compute.floating_ips import base
from tempest import config
from tempest.lib.common.utils import data_utils
from tempest.lib import decorators
from tempest.lib import exceptions as lib_exc
CONF = config.CONF
class FloatingIPDetailsNegativeTestJSON(base.BaseFloatingIPsTest):
"""Negative tests of flo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.