content string |
|---|
#!/usr/bin/
#-*- coding: iso-8859-1 -*-
#===============================================================================
# __________ ________________ __ _______
# / ____/ __ \/ ____/ ____/ __ )/ / / / ___/
# / /_ / /_/ / __/ / __/ / __ / / / /\__ \
# / __/ / _, _/ /___/ /___/ /_/ / /_/ /___/ /... |
#!usr/bin/env python3
"""Class for creating device web pages."""
import textwrap
import os
import time
# PIP3 imports
from flask_table import Table, Col
# Import switchmap.libraries
from switchmap.topology.translator import Translator
from switchmap.utils import general
from switchmap.utils import log
class _RawCo... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Less Frequently Used (LFU) Windows Registry plugin."""
import unittest
from dfdatetime import filetime as dfdatetime_filetime
from dfwinreg import definitions as dfwinreg_definitions
from dfwinreg import fake as dfwinreg_fake
from plaso.formatters import win... |
#!/usr/bin/env python
import sys
with open(sys.argv[2]) as f:
try:
sol = [int(x) for x in f.readline().split()]
if sol == [0]:
print("No satisfying valuation found")
sys.exit(1)
assert all(-x not in sol for x in sol)
except (ValueError, AssertionError):
... |
# -*- coding: utf-8 -*-
"""
pygments.regexopt
~~~~~~~~~~~~~~~~~
An algorithm that generates optimized regexes for matching long lists of
literal strings.
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from re import esc... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
"""
Aleph communicator. This daemon provides AMQP API for
:mod:`edeposit.amqp.aleph` module.
"""
# Imports =====================================================================
import os
import sys
import os.path
import argparse
from... |
import tensorflow as tf
import numpy as np
import collections
import time
import util
from .variational_inference import VariationalInference
from inferences import proximity_statistics
fw = tf.contrib.framework
layers = tf.contrib.layers
dist = tf.contrib.distributions
class ProximityVariationalInference(Variatio... |
import dbus
import re
from decorator import decorator
try:
from ovirt.node.utils.console import TransactionProgress
except ImportError as e:
import sys
import traceback
sys.stderr.write('FATAL: ovirt.node.utils.console.TransactionProgress '
'could not be imported. Is ovirt-node-li... |
"""Adding doi field"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '292944a24fd7'
down_revision = 'f1489c70a2c7'
branch_labels = ()
depends_on = None
def upgrade():
"""Upgrade database."""
# ### commands auto generated by Alembic - please adjust! ###
... |
import random
import treeclassification as e
import exercise1 as ex1
import exercise2 as ex2
import crossvalidation as cv
print "===Entropy==="
print "===ex1==="
tree = e.buildtree(ex1.train_colors)
e.printtree(tree)
print "===prune==="
e.prune(tree, 0.1)
e.printtree(tree)
print "===ex2==="
tree = e.buildtree(ex1.tr... |
import mox
import unittest
from zoom.agent.predicate.zkgut import ZookeeperGoodUntilTime
class ZookeeperGoodUntilTimeTest(unittest.TestCase):
def setUp(self):
self.mox = mox.Mox()
self.interval = 0.1
def tearDown(self):
self.mox.UnsetStubs()
def test_start(self):
pred =... |
from kafkatest.services.performance import PerformanceService
from kafkatest.services.kafka.directory import kafka_dir
from kafkatest.utils.security_config import SecurityConfig
import os
class ConsumerPerformanceService(PerformanceService):
"""
See ConsumerPerformance.scala as the source of truth on the... |
#! /usr/bin/env python3
from abc import ABCMeta, abstractmethod
import csv
import os
import re
import subprocess
import sys
import plaid2text.config_manager as cm
from plaid2text.interact import separator_completer, prompt
class Entry:
"""
This represents one entry (transaction) from Plaid.
"""
def... |
from PyQt4 import QtGui
from ltmt.ui.edit.Ui_listItemWidget import Ui_listItemWidget
class ListItemWidget(QtGui.QWidget):
"""Creates the QListWidgetItem widget of a module into cateogory"""
def __init__(self, module, moduleparser, parent=None):
"""Instantiate a ListItemWidget widget
containing a option in cate... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# Parámetros de configuración (kodi)
#------------------------------------------------------------
# pelisalacarta
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------... |
from typing import Tuple, List
import numpy
from overrides import overrides
from .question_passage_instance import QuestionPassageInstance, IndexedQuestionPassageInstance
from ..data_indexer import DataIndexer
class CharacterSpanInstance(QuestionPassageInstance):
"""
A CharacterSpanInstance is a QuestionPas... |
# Thank you to iAcquire for sponsoring development of this module.
import sys
import time
try:
import boto
import boto.ec2
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def create_image(module, ec2):
"""
Creates new AMI
module : AnsibleModule object
ec2: authenticated ec2 con... |
{
'name': 'Sales commissions',
'version': '8.0.2.3.0',
'author': 'Pexego, '
'Savoire-faire linux, '
'Avanzosc, '
'Abstract, '
'Serv. Tecnol. Avanzados - Pedro M. Baeza, '
'Odoo Community Association (OCA)',
"category": "Sales Manageme... |
import socket
class UDP(object):
def Server(IPaddress,Port,SendData):
udp_server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
serverinfo = (IPaddress,Port)
udp_server.bind(serverinfo)
dt , udp_client = udp_server.recvfrom(int(5000))
udp_server.sen... |
import os
import re
import select
import termios
from sys import version_info
from termcolors.colors import RGBAColor
#######################################################################
# Query-related error conditions
class TerminalQueryError(Exception):
'''
Base class for the other exceptions.
''... |
from .models.boolean_object_value import BooleanObjectValue
from .models.contact_object_value import ContactObjectValue
from .models.date_object_value import DateObjectValue
from .models.duration import Duration
from .models.multi_contact_object_value import MultiContactObjectValue
from .models.multi_picklist_object_va... |
"""This example updates a line item to add custom criteria targeting.
To determine which line items exist, run get_all_line_items.py. To determine
which custom targeting keys and values exist, run
get_all_custom_targeting_keys_and_values.py.
"""
import pprint
# Import appropriate modules from the client library.
fr... |
# -*- coding: utf-8 -*-
print(__doc__)
# License: MIT
# ANALYSE DES DONNEES: VISUALISATION DES DATAS EN 2D
import os
import pandas as pd
import matplotlib.pyplot as plt
# Simulation à etudier
SIM = 'SIM3'
TR_GEN_METH = 'GAUS'
STATE = 'INIT'
# Analyser la fonction F(X) = Y
# X est
X_LAB = 'Essai'
# Y est
Y_LAB = ... |
"""
Classes for making VMware VI SOAP calls.
"""
import httplib
import time
import urllib2
import decorator
from oslo.config import cfg
import suds
from nova.i18n import _
from nova import utils
from nova.virt.vmwareapi import error_util
RESP_NOT_XML_ERROR = 'Response is "text/html", not "text/xml"'
CONN_ABORT_ERRO... |
"""
Unit tests for scripts
@author: Kenneth Hoste (Ghent University)
"""
import os
import re
import shutil
import tempfile
from test.framework.utilities import EnhancedTestCase
from unittest import TestLoader, main
import vsc
import easybuild.framework
from easybuild.framework.easyconfig.easyconfig import EasyConfig... |
# coding=utf-8
import os
import re
def main():
if not os.path.isdir(os.getcwd() + "/ROOT"):
os.mkdir("ROOT")
os.chdir(os.getcwd() + "/ROOT")
root_dir = os.getcwd()
db_filename = '../pci.csv'
print "open ", db_filename
pci_db = open(db_filename) # www.pcidatabase.com/reports.php?type=... |
from sos.plugins import Plugin, RedHatPlugin
import os
YUM_PLUGIN_PATH = "/usr/lib/yum-plugins/"
class Yum(Plugin, RedHatPlugin):
"""yum information
"""
plugin_name = 'yum'
profiles = ('system', 'packagemanager', 'sysmgmt')
files = ('/etc/yum.conf',)
packages = ('yum',)
verify_packages ... |
from __future__ import absolute_import
from collections import deque
import txaio
txaio.use_asyncio()
from autobahn.wamp import websocket
from autobahn.websocket import protocol
try:
import asyncio
from asyncio import iscoroutine
from asyncio import Future
except ImportError:
# Trollius >= 0.3 was r... |
import argparse
import logging
import os
from packaging_tools.drop_tools import build_package_from_pr_number
_LOGGER = logging.getLogger(__name__)
def generate_main():
"""Main method"""
parser = argparse.ArgumentParser(description="Build package.", formatter_class=argparse.RawTextHelpFormatter)
parser.... |
from datetime import datetime as dt
import numpy as np
import pytest
from arctic.date import DateRange, CLOSED_OPEN, mktz
from arctic.exceptions import NoDataFoundException
def test_delete(tickstore_lib):
DUMMY_DATA = [
{'a': 1.,
'b': 2.,
'index': dt(2013, 1, 1, tzinf... |
#!/usr/bin/env python
import os
import IO
from ReframeServer import ReframeServer
from ReframeData import dummy_data_provider
def hashState(frame): # TODO this is somewhat inefficient, but more advanced methods of data reduction are in the pipelne
"""
Note only skeleton descriptor data, etc, are use in this hash fun... |
import amulet
import re
import unittest
class TestDeploy(unittest.TestCase):
"""
Smoke test for Apache Bigtop Zeppelin using remote Spark resources.
"""
@classmethod
def setUpClass(cls):
cls.d = amulet.Deployment(series='xenial')
cls.d.add('zeppelin')
cls.d.add('spark')
... |
from __future__ import print_function
import io
import os
import subprocess
import sys
import re
import string
import optparse
import pygments.lexers
from pygments.token import Token
EXUBERANT_CTAGS = "ctags.exe"
# In most cases, lexers can be looked up with lowercase form of formal
# language names. This dictionary ... |
from keras.layers import Input, Dense
from keras.models import Model
import numpy as np
encoding_dim = 32
input_img = Input(shape=(16384,))
encoded = Dense(encoding_dim, activation='relu')(input_img)
decoded = Dense(16384, activation='sigmoid')(encoded)
autoencoder = Model(input_img, decoded)
encoder = Model(input_... |
import argparse
import collections
import os
import sys
from tripleo_common.utils import roles as rolesutils
__tht_root_dir = os.path.dirname(os.path.dirname(__file__))
__tht_roles_dir = os.path.join(__tht_root_dir, 'roles')
def parse_opts(argv):
parser = argparse.ArgumentParser(
description='Generate r... |
from pyparsing import stringEnd, ParseException
from pyzebos.parsers.config.accesslist import accessList
import pytest
accessListParser = accessList + stringEnd
accesslist_statements = [
# Standard access list
'access-list 50 deny 10.0.0.0 0.0.0.255',
'access-list 50 deny 5.6.7.8',
'access-list 50 de... |
import sqlalchemy
from sqlalchemy import Column, Boolean, Integer, Float, String, DateTime, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, Session, sessionmaker
from sqlalchemy.orm.attributes import InstrumentedAttribute
__all__ = ['engine', 'DatabaseObject'... |
import numpy as np
map_coordinates = None # expensive, from scipy.ndimage
from menpo.external.skimage._warps_cy import _warp_fast
from menpo.transform import Homogeneous
# Store out a transform that simply switches the x and y axis
xy_yx = Homogeneous(np.array([[0., 1., 0.],
[1., 0., 0.]... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'reportsdialog.ui'
#
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def... |
""""""
from datetime import datetime
from flask import request
from flask_login import current_user
from flask_sqlalchemy import BaseQuery
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String
from sqlalchemy.orm import relation
from abilian.core.extensions import db
from abilian.core.models.subjects i... |
import sublime
import sublime_plugin
class UnderlinerCommand(sublime_plugin.TextCommand):
replacements = {
' ': '_',
'_': ' ',
}
names = {
' ': 'spaces',
'_': 'underlines',
}
def run(self, edit):
sels = self.view.sel()
replace_char = self.get_prev... |
import json
import copy
from collections import OrderedDict
from datetime import datetime
from ciscosparkapi.helperfunc import sparkParseTime, sparkISO8601
def _priv(item):
return '_' + item
def _addValueFn(className, item, docstring):
attrName = _priv(item)
def fnGet(self):
return getattr(self... |
"""Implements CgminerInfo Class for gathering stats from cgminers.
The statistics are obtained by connecting to and querying the api
of local and/or remote cgminer
"""
import re
import util
from pycgminer import CgminerAPI
__author__ = "Elbandi"
__copyright__ = "Copyright 2015, Elbandi"
__credits__ = []
__license__... |
import logging
import os
import re
import shutil
import time
import pyauto_functional # Must be imported before pyauto
import pyauto
import test_utils
from selenium.webdriver.common.keys import Keys
from webdriver_pages import settings
class FullscreenMouselockTest(pyauto.PyUITest):
"""TestCase for Fullscreen and... |
#!/usr/bin/env python
"""
Collection of tools for plotting descriptive statistics of a catalogue
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm, Normalize
from math import log10
from openquake.hmtk.seismicity.occurrence.utils import get_completeness_counts
# Def... |
from __future__ import unicode_literals
from django.test import TestCase
from django.db import IntegrityError
from tests.models import Band, BandMember, Restaurant, Review, Album, \
Article, Author, Category
class ClusterTest(TestCase):
def test_can_create_cluster(self):
beatles = Band(name='The Bea... |
"""
Morse Clock
"I'm sending our time logs for the last expedition to HQ, but with this
equipment it's no easy task..." the pilot grumbled. "Can you imagine that with
all the computer power at our disposal, I STILL have to convert this message to
Morse-code using only an on/off button... Hrmph... what a colossal pain.... |
# -*- coding: utf-8 -*-
'''Base TestCase class for OSF unittests. Uses a temporary MongoDB database.'''
import os
import re
import shutil
import logging
import unittest
import functools
import datetime as dt
from json import dumps
import blinker
import httpretty
from webtest_plus import TestApp
from webtest.utils impo... |
import os
import re
from datetime import datetime
from glob import glob
import llnl.util.tty as tty
from llnl.util.filesystem import working_dir
import spack.paths
from spack.util.executable import which
description = "debugging commands for troubleshooting Spack"
section = "developer"
level = "long"
def setup_par... |
from survox_api.resources.base import SurvoxAPIBase
from survox_api.resources.exception import SurvoxAPIRuntime, \
SurvoxAPIMissingParameter, SurvoxAPINotFound
from survox_api.resources.valid import valid_url_field
class SurvoxAPIClientCredentialList(SurvoxAPIBase):
def __init__(self, client, base_url=None, h... |
"""Support for UpCloud."""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.const import (
CONF_USERNAME, CONF_PASSWORD, CONF_SCAN_INTERVAL,
STATE_ON, STATE_OFF, STATE_PROBLEM)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Sala.valida'
db.add_column(u'salas_sala', 'valida',
... |
import ctypes as ct
import logging
import numpy as np
import os
import atexit
from neon import NervanaObject
from neon.data.datasets import Dataset
from neon.data.dataiterator import NervanaDataIterator
logger = logging.getLogger(__name__)
class ImageLoader(NervanaDataIterator):
"""
Encapsulates the data lo... |
"""Functions for evaluations."""
import collections
from typing import Dict, List
from nltk.translate import bleu_score
from rouge import rouge_scorer
def coco_evaluate(references, hypothesis):
"""Evaluate the hypothesis against the references for COCO scores.
Args:
references: A list of reference string.
... |
# -*- coding: utf-8 -*-
"""
utils
Some random utils which dont fit anywhere
:copyright: (c) 2011 by Douglas Morato
:license: BSD, see LICENSE for more details.
"""
from trytond.model import ModelSQL
from trytond.model.fields import (Integer, BigInteger, Boolean, DateTime,
Numeric, Float, Char, ... |
import datetime
from typing import Generator, List
__all__ = ["daterange", "prev_days"]
def daterange(a_date, b_date, step=1, desc=False) -> Generator[datetime.date, None, None]:
"""
Generator returning dates from lower to higher
date if `desc` is False or from higher to lower
if `desc` is True.
... |
# Program to test/demonstrate consistency of results from getcal()
from array import array
from ds3231_pb import DS3231
# This takes 12.5 hours to run: to sve you the trouble here are results from one sample of Pyboard.
# Mean and standard deviation of RTC correction factors based on ten runs over different periods.
... |
#!usr/bin/python
# -*- coding: utf-8 -*-
__plugins__ = ('Video', )
__version__ = '2011-03-20'
__author__ = 'Karol Będkowski'
__copyright__ = "Copyright (c) Karol Będkowski, 2011"
import Image
import ImageFilter
import ImageEnhance
import ImageDraw
import ImageChops
from photomagick.common import curves
from photomag... |
import re
import unittest
from mock import Mock
from robot.parsing.settings import Fixture, Documentation, Timeout, Tags, Return
from robot.utils.asserts import assert_equals, assert_true, assert_false
from robot.parsing.model import TestCaseFile
from robotide.controller.filecontrollers import TestCaseFileController
f... |
# -*- coding: utf-8 -*-
import telebot
import codecs
import time
import threading
from hashlib import sha256
import string
import random
import urllib.request
import os
from datetime import datetime, timedelta
from settings import *
from logic.user import User
from logic.event import Event
bot = tel... |
import collections
from eventlet import queue
__all__ = ['Pool', 'TokenPool']
# have to stick this in an exec so it works in 2.4
try:
from contextlib import contextmanager
exec('''
@contextmanager
def item_impl(self):
""" Get an object out of the pool, for use with with statement.
>>> from eventlet ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" ib.ext.cfg.EClientSocket -> config module for EClientSocket.java.
"""
from java2python.config.default import modulePrologueHandlers
from java2python.config.default import methodPrologueHandlers
from java2python.mod.basic import maybeSynchronizedMethod
from cfg import o... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'acq4/modules/TaskRunner/analysisModules/Uncaging/UncagingTemplate.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
... |
import os
import logging
import json
from djpcms import forms
from djpcms.forms import form_kwargs
from djpcms.utils import force_str
from djpcms.utils.text import capfirst, nicename
from djpcms.utils.formjson import form2json
_plugin_dictionary = {}
_wrapper_dictionary = {}
def ordered_generator(di):
cmp = lam... |
#!/usr/bin/env/python
"""
types_filter.py -- Create a types value for managing people types. This is a bit of nasty business. Person
types consists of different kinds of information, all rolled in to a "types" field that is multi-valued. The
source data is authoritative for two concepts -- the type of th... |
#!/usr/bin/python
from os import curdir, sep
import random
import cgi
import os
from HTMLParser import HTMLParser
import uuid
#~ import cgitb
#~ cgitb.enable()
#~ import sys
#~ sys.stderr = sys.stdout
#~ print "Content-Type: text/plain"
#~ print
startdir = os.path.abspath('../pads/')
parser = HTMLParser()
form = ... |
"""Routines that bypass file-system checks."""
import errno
import os
from oslo_utils import fileutils
from nova import exception
import nova.privsep
@nova.privsep.sys_admin_pctxt.entrypoint
def readfile(path):
if not os.path.exists(path):
raise exception.FileNotFound(file_path=path)
with open(path... |
"""
Django settings for image_app project.
Generated by 'django-admin startproject' using Django 1.10.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import ... |
import os
import sys
import hginit
if os.environ.get('HGUNICODEPEDANTRY', False):
reload(sys)
sys.setdefaultencoding("undefined")
libdir = '@LIBDIR@'
if libdir != '@' 'LIBDIR' '@':
if not os.path.isabs(libdir):
libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
... |
"""
biclustlib: A Python library of biclustering algorithms and evaluation measures.
Copyright (C) 2017 Victor Alexandre Padilha
This file is part of biclustlib.
biclustlib is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by... |
from django import forms
from webui.models import Branch, BuildConfiguration, PackageNameMapping
class BranchForm(forms.ModelForm):
class Meta:
model = Branch
fields = ['name', 'path', 'maintainer', 'is_virtual']
CONF_TYPE = (
("deb", "Debian package"),
("remote", "Remote script"),
)
c... |
#! /usr/bin/env python
from setgame.models import SetDeck
from setgame.models import is_set
from itertools import product
from collections import defaultdict
def simulate_games(seeds=[None]):
set_found_at = defaultdict(int)
remaining_cards = defaultdict(int)
for seed in seeds:
sd = SetDeck(seed)
... |
__author__ = 'Oliver Lindemann'
import numpy as np
import logging
from .._lib.timer import Timer
from ._config import NUM_SAMPS_PER_CHAN, TIMEOUT, NI_DAQ_BUFFER_SIZE
class DAQReadAnalog(object):
NUM_SAMPS_PER_CHAN = NUM_SAMPS_PER_CHAN
TIMEOUT = TIMEOUT
NI_DAQ_BUFFER_SIZE = NI_DAQ_BUFFER_SIZE
DAQ_TYPE... |
from abc import ABCMeta, abstractmethod
class BaseClient(metaclass=ABCMeta):
connected = False
closed = False
def connect(self):
'''
Connect to the drone.
:raises RuntimeError: if the drone is connected or closed already.
'''
if self.connected:
raise ... |
from ..base.frame import FrameBase
from .header import GSBHeader
from .payload import GSBPayload
__all__ = ['GSBFrame']
class GSBFrame(FrameBase):
"""Frame encapsulating GSB rawdump or phased data.
For rawdump data, lines in the timestamp file are associated with single
blocks of raw data. For phased ... |
import os, stat
import logging
from StringIO import StringIO
from lxml import etree
from lib.ddbb import DDBB
from lib.uc import UC
class Profile:
def __init__(self, environment, data_path = None, parent = None):
logging.debug(">>")
self.environment = environment
self.pytrainer_main = pare... |
"""
This package contains directive implementation modules.
"""
__docformat__ = 'reStructuredText'
import re
import codecs
import sys
from docutils import nodes
from docutils.utils import split_escaped_whitespace, escape2null, unescape
from docutils.parsers.rst.languages import en as _fallback_language_module
if sys... |
# encoding: utf-8
# py3k support
from __future__ import print_function
#import setuptools # for bdist_egg and console_scripts entry point
from setuptools import setup,Extension
#import distutils.command.install_scripts
#import distutils.command.sdist
#import distutils.command.build_ext
import os.path, os, shutil, re, ... |
import pygame
import math
import numpy
class Static:
def __init__(self, xpos, ypos):
self.physics = dict(
x = xpos,
y = ypos
)
class LightMap:
def __init__(self, screen, alpha):
self.screen = screen
self.alpha = alpha
self.tiles = []
se... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
import time
from pymongo import MongoClient
import gridfs
import yara
from utils import get_file, clean_data, Config
JOBNAME = 'YARA'
SLEEPTIME = 1
# create logger
logger = logging.getLogger(JOBNAME)
logger.setLevel(logging.DEBUG)
# create console handler ... |
from unittest import TestCase
import json
class JSONTestObject:
pass
class RecursiveJSONEncoder(json.JSONEncoder):
recurse = False
def default(self, o):
if o is JSONTestObject:
if self.recurse:
return [JSONTestObject]
else:
return 'JSONTe... |
import os
from setuptools import setup
#from setuptools import find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'SQLAlchemy',
'zope.interface', # Used by zope.sqlalchem... |
import psutil
from opencensus.metrics.export.gauge import DerivedDoubleGauge
class ProcessorTimeMetric(object):
NAME = "\\Processor(_Total)\\% Processor Time"
@staticmethod
def get_value():
cpu_times_percent = psutil.cpu_times_percent()
return 100 - cpu_times_percent.idle
def __call... |
__doc__ = """This is the implementation of an Email-Token, that sends OTP
values via SMTP.
The following config entries are used:
* email.validtime
* email.identifier
The identifier points to a system wide SMTP server configuration.
See :ref:`rest_smtpserver`.
The system wide SMTP server configuration was introdu... |
from __future__ import absolute_import, print_function
import collections
import time
from pymel.core import dt, polyColorPerVertex, polyCylinder, polyUnite, PyNode, selected, xform
def numf(num):
''' Display floats nicely.
'''
return '{0:>5.2f}'.format(num)
def matrixDisplay(o, ws=False):
... |
import mock
from neutron_lib.api.definitions import portbindings
from neutron_lib.callbacks import events
from neutron_lib.callbacks import registry
from neutron_lib.callbacks import resources
from neutron_lib.plugins import directory
import testtools
from neutron.objects import trunk as trunk_objects
from neutron.ser... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# Conector Idtbox By Alfa development Group
# --------------------------------------------------------
import re
from core import httptools, scrapertools
from platformcode import logger, platformtools
data = ""
def test_video_exists(pa... |
import turtle
my_screen = turtle.Screen()
bob = turtle.Turtle()
#I'm too lazy to start from scratch so this is all the code from the assignment we did
def rectangle(l,w):
bob.fd(w)
bob.rt(90)
bob.fd(l)
bob.rt(90)
bob.fd(w)
bob.rt(90)
bob.fd(l)
bob.rt(90)
def eq_triangle(s):
bob.fd(... |
import numpy as np
from astropy.table import Table
from astropy.io import fits
import matplotlib.pyplot as plt
import matplotlib
import pickle
from os.path import isfile, join
from os import listdir
import os
from astropy.time import Time
mypath = "/Users/caojunzhi/Desktop/Data/dr13_red_clump/"
mypath_ori = "/Volum... |
import click
from netCDF4 import Dataset, MFDataset, num2date
import matplotlib as mpl
mpl.use('Qt5Agg')
#%matplotlib inline
import matplotlib.pylab as plt
import numpy as np
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cmocean import cm as cmo
from matplotlib import cm
import sys, os
sys.path.app... |
"""Tests for initializers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import tensorflow as tf
gaussian_conjugate_posteriors = tf.contrib.distributions.gaussian_conjugate_posteriors # pylint: disable=line-too-long
class GaussianTest(... |
from owslib.waterml.wml import SitesResponse, TimeSeriesResponse, VariablesResponse, namespaces
from owslib.etree import etree, ElementType
def ns(namespace):
return namespaces.get(namespace)
class WaterML_1_1(object):
def __init__(self, element):
if isinstance(element, ElementType):
se... |
from troposphere import (
Parameter,
Ref,
Output,
Tags,
GetAtt,
Base64,
Join,
Equals,
cloudwatch as cw,
ec2,
elasticloadbalancing as elb,
autoscaling as asg
)
from utils.cfn import get_recent_ami
from utils.constants import (
ALLOW_ALL_CIDR,
EC2_INSTANCE_TYPES,
... |
from ichnaea.api.locate.ocid import OCIDPositionSource
from ichnaea.api.locate.result import ResultList
from ichnaea.api.locate.tests.base import BaseSourceTest
from ichnaea.tests.factories import (
OCIDCellAreaFactory,
OCIDCellFactory,
)
class TestOCIDPositionSource(BaseSourceTest):
TestSource = OCIDPos... |
########################################################################
# This program illustrate many approaches to solve ODEs. In this case
# we use the simple pendulum as the system.
#
# This module implements all the classes and functions for the problem.
#
# Marina von Steinkirch, spring/2013
# (based ... |
import pandas as pd
import numpy as np
from sklearn import preprocessing, cross_validation, neighbors
from sklearn.feature_selection import SelectKBest, chi2, VarianceThreshold
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_sel... |
"""Deletes all certificates and generates a new server SSL certificate."""
from googlecloudsdk.api_lib.sql import errors
from googlecloudsdk.api_lib.sql import operations
from googlecloudsdk.api_lib.sql import validate
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
class _BaseResetSslCo... |
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from collections import Counter
try:
from queue import Queue
except ImportError:
from Queue import Queue
from poultry import consumers
from poultry.tweet import Tweet
import pytest
from pytest import raises
def from_ite... |
from django.views.generic import TemplateView
from django.conf import settings
from .forms import DemoForm
class Index(TemplateView):
template_name = 'demo/index.html'
class DemoBase(TemplateView):
form_class = DemoForm
form_1 = None
form_2 = None
form_3 = None
def get(self, request, *args,... |
#!/usr/bin/env python
#---coding=utf8---
from HomeHandler import HomeHandler
from LoginHandler import LoginHandler
from LogoutHandler import LogoutHandler
from ArchivesHandler import ArchivesHandler
from CategoryHandler import CategoryHandler
from TagHandler import TagHandler
from PageHandler import PageHandler
from Se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.