content stringlengths 4 20k |
|---|
"""
This file is used for logging purposes. The messages send here will be
printed to the log file and when run from a command UI, will be printed
in a color.
"""
# Total imports
import logging
from logging.handlers import WatchedFileHandler
# Local imports
from plebnet.settings import plebnet_settings
suppress_prin... |
config = {
"interfaces": {
"google.cloud.kms.v1.KeyManagementService": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": []
},
"retry_params": {
"default": {
"initia... |
import insn
import bbl
from pygraph.classes.digraph import digraph
from pygraph.classes.graph import graph
from pygraph.algorithms.searching import depth_first_search
from pygraph.algorithms.searching import breadth_first_search
from pygraph.algorithms.filters.null import null as null_filter
class _use_filter(null_f... |
#-*- encoding:utf8 -*-
import cStringIO
import poplib
import re
#import base64
from eml import Eml
class Fetcher:
def __init__(self, user, passwd, pserver, pport, bssl, writer=None):
self.pserver = pserver
self.pport = pport
self.writer = writer
if bssl:
self.mclient = poplib.POP3_... |
#!/usr/bin/env python3
# encoding: utf-8
"""
survivalvolume/test_plot.py
Functions and classes for plotting tumour volume vs time and survival endpoints based on volume thresholds
Created by Matthew Wakefield.
Copyright (c) 2016 Matthew Wakefield, The Walter and Eliza Hall Institute and The University of Melbourne. ... |
import os
import numpy as np
# DEPENDS ON
# array2pil()
# batch2grid()
# ==============================================================================
# VIZ_SAMPLE_AUGMENTATIONS
# ==============================================================================
def ... |
from __future__ import absolute_import
import hmac
import os
import sys
import warnings
from binascii import hexlify, unhexlify
from hashlib import md5, sha1, sha256
from ..exceptions import (
InsecurePlatformWarning,
ProxySchemeUnsupported,
SNIMissingWarning,
SSLError,
)
from ..packages import six
fr... |
import mock
from nose import tools as nt
from django.test import RequestFactory
from django.core.urlresolvers import reverse
from django.core.exceptions import PermissionDenied
from django.contrib.auth.models import Permission
from tests.base import AdminTestCase
from tests.factories import AuthUserFactory, ProjectFac... |
#!/usr/bin/env python2
# coding=utf8
import collections
import os.path
import re
from gnuradio import gr, blocks
from gnuradio import uhd
import osmosdr
import lora
LoRaReceiver = collections.namedtuple('LoRaReceiver', ['name', 'available'])
class LoRaReceiveAll:
def __init__(self, receiver, spreadingFactor = 7... |
import re
import time
import random
import feedparser
from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger
from mycroft.skills.audioservice import AudioService
__author__ = 'jdorleans' , "jarbas", "chrison999"
LOGGER = getLogger(__name__)
class ... |
import os
import re
import weakref
from trac.config import ListOption
from trac.core import *
from trac.db.api import IDatabaseConnector
from trac.db.util import ConnectionWrapper, IterableCursor
from trac.util import get_pkginfo, getuser
from trac.util.translation import _
_like_escape_re = re.compile(r'([/_%])')
_... |
import socket
import thread
import echo_client
import time
buffersize = 8
def start_server():
server_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP
)
server_socket.bind(('127.0.0.1', 50000))
server_socket.listen(1)
try:
while True:... |
"""
Tests For Scheduler weighers.
"""
from manila.scheduler.weighers import base
from manila import test
from manila.tests.scheduler import fakes
class TestWeightHandler(test.TestCase):
def test_get_all_classes(self):
namespace = "manila.tests.scheduler.fakes"
handler = base.BaseWeightHandler(
... |
import os
from os.path import join
from enot.utils.file_utils import read_file
# read application config file. Return application name, version, applications and if it contains jinja2 templates
def parse_app_config(path: str, suffix='.app.src') -> (str, str or None, list or None, bool):
file = find_app_file(path... |
from distutils.core import setup
from distutils.command.install import INSTALL_SCHEMES
import os
import sys
def fullsplit(path, result=None):
"""
Split a pathname into components (the opposite of os.path.join) in a
platform-neutral way.
"""
if result is None:
result = []
head, tail = os... |
import json
import urllib
from tempest.api_schema.response.compute.v2 import floating_ips as schema
from tempest.common import rest_client
from tempest import config
from tempest import exceptions
CONF = config.CONF
class FloatingIPsClientJSON(rest_client.RestClient):
def __init__(self, auth_provider):
... |
import re
import warnings
from django.db.backends.base.introspection import (
BaseDatabaseIntrospection, FieldInfo, TableInfo,
)
from django.utils.deprecation import RemovedInDjango21Warning
field_size_re = re.compile(r'^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$')
def get_field_size(name):
""" Extract the size ... |
import asyncio, asyncssh, hashlib, random, socket, threading, tiocache, traceback, websockets, zlib
cache_file = '/srv/var/cache/tiows'
def _counter():
counter = 0
while True:
counter += 1
yield counter
counter = _counter()
async def auto_save():
while True:
await asyncio.sleep(600)
cache.save_to(cache_f... |
import sys
import math
class NumberGuesser:
def __init__(self, lower_bound, upper_bound):
self.lower_bound = lower_bound
self.upper_bound = upper_bound
def get_guess(self):
return int(math.ceil((self.lower_bound + self.upper_bound) / 2.0))
def has_solutions(self):
return sel... |
"""
Clone client Model Three
Author: Min RK <<EMAIL>
"""
import random
import time
import zmq
from kvsimple import KVMsg
def main():
# Prepare our context and subscriber
ctx = zmq.Context()
snapshot = ctx.socket(zmq.DEALER)
snapshot.linger = 0
snapshot.connect("tcp://localhost:5556")
s... |
"""GO terms
Resources: geneontology.org and godb Python package from endrebak user (Bakken).
https://github.com/endrebak/godb/
"""
import urllib
import os
from collections import defaultdict
from biokit import biokitPATH
import pandas as pd
__all__ = ['num2goid', 'GOId', 'GODB', 'GOTerm']
def num2goid(value):
... |
import pytest
from unittest import mock
from share.regulate.regulator import Regulator, Steps, InfiniteRegulationError, RegulatorConfigError
from share.regulate.steps import NodeStep, GraphStep, ValidationStep
from share.util.graph import MutableGraph
@pytest.mark.parametrize('num_node_steps', [0, 1, 5])
@pytest.mar... |
"""
Tests for pulp_rpm.plugins.migrations.0001_puppet_module_unit_checksum
"""
import unittest
from mock import patch
from pulp.server.db.migrate.models import _import_all_the_way
from pulp.devel.mock_cursor import MockCursor
from pulp_puppet.common import constants
class Test0001PuppetModuleUnitChecksum(unittest.T... |
import bpy
from bpy.props import *
def draw(layout, context):
if not context.active_bone is None:
column = layout.column(align=True)
column.label("Active Bone:")
column.menu("roboteditor.bonemenu", text = context.active_bone.name)
column.separator()
column.prop(con... |
import argparse
import sys
import os
import ConfigParser
class Config(object):
def __init__(self, argv):
self.version = "0.3.2"
self.rev = 452
self.argv = argv
self.action = None
self.createParser()
self.createArguments()
def createParser(self):
# Crea... |
from marionette_driver import By, Wait
from ...base import UIBaseLib
class Deck(UIBaseLib):
def _create_panel_for_id(self, panel_id):
"""Creates an instance of :class:`Panel` for the specified panel id.
:param panel_id: The ID of the panel to create an instance of.
:returns: :class:`Pa... |
import rebound
import unittest
import math
import rebound.data
class TestIntegrator2(unittest.TestCase):
def test_whfast_verylargedt(self):
sim = rebound.Simulation()
sim.add(m=1.)
sim.add(m=1e-3, a=1.)
sim.move_to_com()
sim.integrator = "whfast"
yr = sim.particles[1... |
# -*- coding: utf-8 -*-
import unittest
import cine
import numpy as np
class Test(unittest.TestCase):
def __init__(self, *args, **kwargs):
"""
Handle the arguments using TestCase
"""
super(Test, self).__init__(*args, **kwargs)
self.g = cine.fluorescence.pumping('HDO', 7)
... |
from bdc.bdcutil import VariableSubstituterParseError, VariableSubstituter
import pytest
def test_variable_substition():
template = '$foo $$ ${bar} ${a == "hello" ? "woof" : "x"}'
v = VariableSubstituter(template)
assert v.template == template
assert v.substitute({"foo": "FOO", "bar": "BAR", "a": "he... |
#!/usr/bin/env python
# We represent directions by (dx, dy), so that updating (x, y) will be
# a matter of simple addition.
emiter2dxdy = {'>': (1, 0), '<': (-1, 0), 'v': (0, 1), '^': (0, -1)}
def find_emitter(room):
"""Return (x, y, dx, dy)"""
for y, line in enumerate(room):
for x, char in enumerat... |
"""
This script process a full RDF dump and filters it to create three files with much reduced content.
After the filtered files have been created, this script may upload into a treode movies server.
filter command
requires:
- a full RDF dump from freebase in gzip format.
produces:
- film.filtered.data.rdf -> has a... |
import pygame as pg
from settings import *
from tilemap import collide_hit_rect
vec = pg.math.Vector2
class Player(pg.sprite.Sprite):
def __init__(self, game, x, y):
self.groups = game.all_sprites
pg.sprite.Sprite.__init__(self, self.groups)
self.game = game
self.image = game.player... |
''' Position module '''
from random import random
from karmaserver.data.models import db
class Position(db.Model):
''' Observation Position implementation '''
observation_id = db.Column(db.String(64), db.ForeignKey('observation._id'),
primary_key=True)
x_position = db.Column... |
import os
import tempfile
from findex_gui.main import python_env
class CronController:
@staticmethod
def has_cronjob():
crontab = os.popen("crontab -l").read()
cronjob = CronController.generate_cronjob()
if cronjob in crontab:
return True
return
@staticmethod
... |
'''Describe GL types.'''
import platform
from stdapi import *
GLboolean = Enum("GLboolean", [
"GL_TRUE",
"GL_FALSE",
])
GLvoid = Alias("GLvoid", Void)
GLbyte = Alias("GLbyte", SChar)
GLshort = Alias("GLshort", Short)
GLint = Alias("GLint", Int)
GLint64 = Alias("GLint64", Int64)
GLubyte = Alias("GLubyte", ... |
""" Module for translating ONNX operators into Mxnet operatoes"""
# pylint: disable=unused-argument,protected-access
from . import translation_utils
from .... import symbol
# Method definitions for the callable objects mapped in the import_helper module
def identity(attrs, inputs, cls):
"""Returns the identity fu... |
#!/usr/bin/env python
# -*- coding: utf-8
# ----------------------------------------------------------------------
# Extracts pitch
# ----------------------------------------------------------------------
# Ivan Vladimir Meza-Ruiz/ ivanvladimir at turing.iimas.unam.mx
# 2015/IIMAS/UNAM
# -------------------------------... |
"""Base classes and utilities for self-testing LISA's wlgen packages"""
import os
import shutil
from unittest import TestCase
from devlib import LocalLinuxTarget, Platform
dummy_calibration = {}
class TestTarget(LocalLinuxTarget):
"""
Devlib target for self-testing LISA
Uses LocalLinuxTarget configured... |
__author__ = 'Elliot'
from subprocess import call
from platform import system
def clear_screen():
if system() == "Windows":
call("cls")
elif system() == "Darwin" or system() == "Linux":
call("clear")
# Sets up a multi platform clear screen function for Windows, OS X and Linux
def installsamba... |
__author__ = 'Mark'
import numpy
import cv2
import os
import errno
def load_face_vectors_from_disk(image_numbers, img_size, show=True):
"""
Loads images from disk, detects faces from them, resizes the face images to common size, vectorizes the face image
and stores it in a dictionary with key (pers_no, s... |
#### For all old messages and new messages
__author__ = 'asifj'
import logging
from kafka import KafkaConsumer
import json
import traceback
from bson.json_util import dumps
logging.basicConfig(
format='%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(message)s',
level=logging... |
import tensorflow as tf
import numpy as np
from sklearn.cross_validation import train_test_split
import random
import time
import sys
#load training data
args = (sys.argv)
num_gpus = int(args[1])
batch_size = int(args[2])
input = np.load('X_train.npy')
input = input.transpose(0,2,3,1)
labels = np.genfromtxt('./data/... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'RelationsHistory'
db.create_table('twitter_relations_history_relationshistory', (
... |
"""Trains and Evaluates the MNIST network using a feed dictionary.
TensorFlow install instructions:
https://tensorflow.org/get_started/os_setup.html
MNIST tutorial:
https://tensorflow.org/tutorials/mnist/tf/index.html
"""
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ impo... |
"""Minify Javascript and CSS with YUI Compressor. This filter defaults to
JS mode, but it is recommended that you use the 'yui_js' and 'yui_css'
filters instead.
YUI Compressor is an external tool, which needs to be available (also, java
is required).
You can define a YUI_COMPRESSOR_PATH setting that points to... |
''' TraceEventImporter imports TraceEvent-formatted data
into the provided model.
This is a port of the trace event importer from
https://code.google.com/p/trace-viewer/
'''
import copy
import json
import re
import telemetry.timeline.async_slice as tracing_async_slice
import telemetry.timeline.flow_event as tracing_f... |
# coding=utf-8
import typing
class _TypedProperty:
"""
Actual descriptor object created during TypedProperty.__call___ below.
Accessing a _MetaProperty from the META class itself (SomeMeta._TypedProperty) gives access to the object itself,
with "default", "type", "__doc__", "key" and "func".
"... |
from aqt.qt import *
import aqt
from aqt.utils import showInfo, showWarning
from anki.consts import *
RADIO_NEW = 1
RADIO_REV = 2
RADIO_FORGOT = 3
RADIO_AHEAD = 4
RADIO_PREVIEW = 5
RADIO_CRAM = 6
TYPE_NEW = 0
TYPE_DUE = 1
TYPE_ALL = 2
class CustomStudy(QDialog):
def __init__(self, mw):
QDialog.__init__(s... |
from nepi.execution.ec import ExperimentController
from nepi.execution.resource import ResourceAction, ResourceState
import os
# Create the EC
exp_id = "test_blacklist"
ec = ExperimentController(exp_id)
pl_user = os.environ.get("PL_USER")
pl_password = os.environ.get("PL_PASS")
#username = os.environ.get("PL_SLICE")... |
"""
This is the main class for etlTest. All other code is kicked off from here.
"""
#!/usr/bin/python
__author__ = 'coty, ameadows'
import sys
import argparse
import os
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from etltest.utilities.settings_manager import SettingsManager
from etltest.data_connector imp... |
from django.template import loader, RequestContext
from django.core.exceptions import ImproperlyConfigured
from django.http import (HttpResponse, HttpResponseRedirect, Http404,
HttpResponseForbidden)
from django.db.models import get_model
from django.db.models.base import ModelBase
from django... |
#!/usr/bin/python
"""This module requires libvhdio support: it assumes the libraries libvhd.so and libvhdio.so
are installed on the system. These libraries are provided by the blktap RPM package."""
import os
import random
import util
import sys
import subprocess
import logging
import re
PATTERN_EMPTY ... |
"""Various tools for use with PyFEHM."""
"""
Copyright 2013.
Los Alamos National Security, LLC.
This material was produced under U.S. Government contract DE-AC52-06NA25396 for
Los Alamos National Laboratory (LANL), which is operated by Los Alamos National
Security, LLC for the U.S. Department of Energy. The U.S. Go... |
"""Tests for client module."""
import cookielib
import httplib
import StringIO
import time
import urllib2
from absl.testing import absltest
import mock
import oauth2client.client
from cauliflowervest.client import base_client
def GetArgFromCallHistory(mock_fn, call_index=0, arg_index=0):
return mock_fn.call_ar... |
from mininet.topo import Topo
class MininetTopo(Topo):
def __init__(self,**opts):
Topo.__init__(self, **opts)
host1 = self.addHost('h1')
host2 = self.addHost('h2')
host3 = self.addHost('h3')
host4 = self.addHost('h4')
self.switch = {}
for s in range(1,23):
self.switch[s-1] = self.ad... |
import logging
import collections
from sortedcontainers import SortedDict
import networkx
from ...errors import SimEngineError
from ..plugin import KnowledgeBasePlugin
from .function import Function
l = logging.getLogger("angr.knowledge.function_manager")
class FunctionDict(SortedDict):
"""
FunctionDict is... |
#!/usr/bin/env python
# pylint: disable=W0201
# Attribute defined outside __init__: custom commands require breaking this
import datetime
import glob
import fnmatch
import os
import sys
import unittest
from distutils.core import Command, setup
from distutils.command.build import build
from distutils.command.install ... |
# -*- coding: utf-8 -*-
import pendulum
import pytest
def test_to_string():
d = pendulum.datetime(1975, 12, 25, 0, 0, 0, 0, tz="local")
assert str(d) == d.to_iso8601_string()
d = pendulum.datetime(1975, 12, 25, 0, 0, 0, 123456, tz="local")
assert str(d) == d.to_iso8601_string()
def test_to_date_stri... |
import requests
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import ctypes
import sys
import traceback
#
# A simple MARY TTS client (5.x) in Python, only generates intermidate MARY TTS phoneme format.
# This class reuses connections with the request framework (esp. helpful ... |
"""
WebDAV XML elements.
"""
__all__ = [
"WebDAVDocument",
"dav_namespace",
"twisted_dav_namespace",
"twisted_private_namespace",
"WebDAVElement",
"PCDATAElement",
"WebDAVOneShotElement",
"WebDAVUnknownElement",
"WebDAVEmptyElement",
"WebDAVTextElement",
"WebDAVDateTimeEleme... |
import Briefing
import Director
import VS
import debug
import unit
import universe
import vsrandom
def formatSystemName(ship):
where=ship.rfind("/")
if (where!=-1):
ship=ship[where+1:]
return ship.capitalize()
class go_to_adjacent_systems:
def InSystem(self):
return self.arrivedsys
... |
#!/usr/bin/env python
import check_env
NUMBER_OF_EPOCHS = 10
from img_lib import display_images_and_labels, load_data, normalize
import warnings
warnings.filterwarnings('ignore')
import os
print ("Loading data")
# Load datasets.
ROOT_PATH = "./data"
# data_dir = os.path.join(ROOT_PATH, "speed-limi... |
"""
Here we show an example of using the greedy algorithm to perform feature
selection for Naive Bayes. We use two lists from the 20newsgroups dataset and
select k << D features to use for a NB classifier.
==============
Copyright Info
==============
This program is free software: you can redistribute it and/or modify... |
# import the necessary packages
from __future__ import print_function
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2
import time
import sys
# funciton to draw head and shoulders of human
def draw_Head_shoulders(frame):
... |
# coding: utf-8
"""
weasyprint.tests.stacking
-------------------------
:copyright: Copyright 2011-2014 Simon Sapin and contributors, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import division, unicode_literals
from ..stacking import StackingContext
from .test_boxes imp... |
import os, sys, unittest
sys.path.append(os.path.join(os.getcwd(), os.path.pardir))
from data_structures.lists.double_list import DoubleList
class TestLists(unittest.TestCase):
def test_double_list(self):
dl = DoubleList()
dl.insert_head(4)
dl.insert_head(3)
dl.insert_head(2)
... |
from sklearn.cluster import MiniBatchKMeans
import numpy as np
import cv2
import sys
import os
class data_extraction():
def __init__(self):
self.sift = cv2.SIFT()
self.dilation_kernel = np.ones((5,5),np.uint8)
def distance(self,point1,point2):
distance = 0
for p2,p1 in zip(point2,point1):
distance += (p... |
import subprocess
import time
import microstackcommon.core
import os
EDGE = 1
OUT = "out"
IN = "in"
RISING = "rising"
FALLING = "falling"
BOTH = "both"
PULLDOWN = "pulldown"
PULLUP = "pullup"
GPIO_DIR = "/sys/class/gpio/"
class PinAPI(object):
def __init__(self, pin_num):
self.pin_num = pin_num
... |
from numpy import *
import numpy as np
import itertools
import time
import sys
import cPickle as pickle
# Import NN utils
from nn.base import NNBase
from nn.math import softmax, sigmoid, sigmoidGrad,make_onehot
from nn.math import MultinomialSampler, multinomial_sample
from misc import random_weight_matrix
class RNNL... |
#!/usr/bin/env python3
import sys
def check(tree, weights, root):
if not tree[root]: return weights[root]
kids_weights = [check(tree, weights, k) for k in tree[root]]
right = kids_weights[0]
if not all(w == right for w in kids_weights):
# For my original version I didn't actually solve the pr... |
#!/usr/bin/env python
"""
Implementation of the hyperref package
TO DO:
- \autoref doesn't look for \*autorefname, it only looks for \*name
- Layouts
- Forms optional parameters
"""
from plasTeX import Command, Environment
from plasTeX.Base.LaTeX.Crossref import ref, pageref
import urlparse
def addBaseURL(self, ur... |
"""
This module provides the main Circuit class for the eispice simulator. The
Circuit class holds the netlist, device models, and is used to run sims
on a specific circuit instance.
Classes:
Circuit -- an eispice circuit
"""
from scipy import interpolate
import units
from simulator_ import Circuit_
import subckt
C... |
"""Grabber for collecting data"""
import urllib2
from random import sample
from veliberator.settings import PROXY_SERVERS
class Grabber(object):
"""Url encapsultation for making request throught HTTP"""
page = None
data = None
def __init__(self, url, proxies=PROXY_SERVERS):
"""Init the grabb... |
from lmfit import Parameter, Parameters
def convert_to_parameter(obj, name):
"""
Converts a numeric parameter to an lmfit Parameter
"""
return Parameter(name = name,
value = obj.value,
vary = obj.vary,
min = obj.minimum,
... |
from scipy import stats
import math
_THRESHOLD = 1e-10
def scale(a, mul):
return [x*mul for x in a]
def cmp(a, b):
return stats.ttest_ind(a, b)
def speedup(new, old):
s0, p0 = cmp(new, old)
if math.isnan(p0): return 0
if s0 == 0: return 0
if p0 > _THRESHOLD: return 0
if s0 < 0:
pct = 1
while p... |
#From https://gist.github.com/EndingCredits/b5f35e84df10d46cfa716178d9c862a3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state... |
data = (
'bbess', # 0x00
'bbeng', # 0x01
'bbej', # 0x02
'bbec', # 0x03
'bbek', # 0x04
'bbet', # 0x05
'bbep', # 0x06
'bbeh', # 0x07
'bbyeo', # 0x08
'bbyeog', # 0x09
'bbyeogg', # 0x0a
'bbyeogs', # 0x0b
'bbyeon', # 0x0c
'bbyeonj', # 0x0d
'bbyeonh', # 0x0e
'bbyeo... |
import re
import IECore
import Gaffer
import GafferUI
class PathParameterValueWidget( GafferUI.ParameterValueWidget ) :
def __init__( self, parameterHandler, **kw ) :
self.__pathWidget = GafferUI.PathPlugValueWidget(
parameterHandler.plug(),
self._path(),
pathChooserDialogueKeywords = self._pathChoos... |
import sys
import subprocess as sp
import time
from datetime import datetime
usage_message = """
Usage: {} <script.py>
where <script.py> is a python script to be kept alive
"""
crash_message = """
Daemon crashed:
Uptime: {}
Waiting a moment before restarting..."""
if len(sys.argv) < 2:
print(usage_message.forma... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'core'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.junos import juno... |
'''event_looper.py'''
import time
import traceback
import sys
from abc import abstractmethod
from heapq import heappush, heappop
from heron.common.src.python.utils.log import Log
class EventLooper:
"""EventLooper is a Python implementation of WakeableLooper.java
EventLooper is a class for scheduling recurring t... |
from msrest.serialization import Model
class SmsReceiver(Model):
"""An SMS receiver.
Variables are only populated by the server, and will be ignored when
sending a request.
:param name: The name of the SMS receiver. Names must be unique across all
receivers within an action group.
:type nam... |
import re
import datetime
import csv
# from openpyxl.workbook import Workbook
# from openpyxl.styles import numbers, is_date_format
# from openpyxl.utils.datetime import to_excel
#import gen_functions
class Linewriter:
def __init__(self, lines):
self.lines = lines
self.current_workbook = False
... |
import os, sys, re, time
from buildslave.scripts import base
from twisted.python import usage
# the create/start/stop commands should all be run as the same user,
# preferably a separate 'buildbot' account.
# Note that the terms 'options' and 'config' are used interchangeably here - in
# fact, they are interchanged s... |
class UnsupportedCodecError(Exception):
pass
class MKVTrack():
number = 0
mkvtoolnix_id = 0
uid = track_type = language = codec_id = ""
default = True
log = None
codec_table = {
"A_AC3": ".ac3",
"A_EAC3": ".eac3", # mplayer should play EAC3 correctly
... |
'''
Use this script from terminal / console with
./python sisostudy.py --file_storage=my_runs
Will create an output with all the necessary information
'''
# Import the pacakges
# Numpy for numerical methods
import numpy as np
# Python Control for SISO creation etc.
import control as cn
# Pandas for Data Storage
im... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
1935. Tears of Drowned
Time limit: 1.0 second
Memory limit: 64 MB
[Description]
Old Captain Jack Sparrow’s friend Tia Dalma, the fortuneteller and prophetess, often makes potions. She has an
outstanding collection of the rarest ingredients such as rat tails, fingers of d... |
import sys
import unittest
from ipaddress import AddressValueError
from golem.network.transport.tcpnetwork import SocketAddress
class TestSocketAddressParsing(unittest.TestCase):
"""Test suite for SocketAddress.parse()"""
def __expect_exception(self, value, exception):
try:
SocketAddress... |
import shutil
from tqdm import tqdm
from SiteFab.Plugins import SitePreparsing
from SiteFab.SiteFab import SiteFab
class CopyDir(SitePreparsing):
"""
Copy directories
"""
def process(self, unused, site, config):
""" Process the content of the site once
:param FabSite site: the site ... |
import pytest
from six import PY2
from datadog_checks.amazon_msk import AmazonMskCheck
from datadog_checks.amazon_msk.metrics import (
JMX_METRICS_MAP,
JMX_METRICS_OVERRIDES,
METRICS_WITH_NAME_AS_LABEL,
NODE_METRICS_MAP,
NODE_METRICS_OVERRIDES,
)
from .common import METRICS_FROM_LABELS
pytestmark... |
from sys import exit, argv
import os
import argparse
import db_api
import quiz_csv
import quiz_sql
import configure
from configobj import ConfigObj
def set_default(value=False):
config = ConfigObj()
config.filename = configure.settings_path
configure.conf()
choice = None
value = None
if va... |
# -*- coding: utf-8 -*-
"""
Project name: Open Methodology for Security Tool Developers
Project URL: https://github.com/cr0hn/OMSTD
Copyright (c) 2014, cr0hn<-AT->cr0hn.com
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following ... |
import re
from weboob.tools.backend import Module, BackendConfig
from weboob.capabilities.paste import CapPaste, BasePaste
from weboob.tools.capabilities.paste import image_mime
from weboob.tools.compat import urljoin
from weboob.tools.value import Value
from .browser import LutimBrowser
__all__ = ['LutimModule']
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Benjamin Milde'
import requests
import json
import redis
import re
from timer import Timer
red = redis.StrictRedis()
#Todo: refactor. This has been mved to the relevant event generator
def idFromTitle(title):
return re.sub(r'[^\w]', '_', title.replace(... |
from tuskarclient.tests import utils as tutils
from tuskarclient.common import http
import mock
fixtures = {}
class HttpClientUrlGenerationTest(tutils.TestCase):
def test_url_generation_trailing_slash_in_base(self):
client = http.HTTPClient('http://localhost/')
url = client._make_connection_ur... |
"""
Finite element mesh classes
"""
import unittest
import fluidity.diagnostics.debug as debug
try:
import numpy
except:
debug.deprint("Warning: Failed to import numpy module")
import fluidity.diagnostics.bounds as bounds
import fluidity.diagnostics.calc as calc
import fluidity.diagnostics.elements as elements
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 12 17:03:55 2015
@author: q
"""
#%%
#def debug():
# from PyQt4.QtCore import pyqtRemoveInputHook
# from pdb import set_trace
# pyqtRemoveInputHook()
# set_trace()
class MyDebugger(object):
@classmethod
def debug(self):
'''Set a ... |
import pecan
from oslo_log import log as logging
from designate.api.v2.controllers import rest
from designate.api.admin.views.extensions import reports as reports_view
LOG = logging.getLogger(__name__)
class TenantsController(rest.RestController):
_view = reports_view.TenantsView()
@pecan.expose(template=... |
import mock
from os_brick.initiator import connector
from nova.tests.unit.virt.libvirt.volume import test_volume
from nova.virt.libvirt.volume import hgst
# Actual testing of the os_brick HGST driver done in the os_brick testcases
# Here we're concerned only with the small API shim that connects Nova
# so these will... |
from django.conf import settings
from django.conf.urls import include, patterns, url
from django.contrib import admin
from django.views.decorators.cache import cache_page
import apps.api.urls
from apps.core.views import (HomePageView, JobDetailView, JobHistoryView,
JobsDiffView, JobsListVi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.