content stringlengths 4 20k |
|---|
from __future__ import print_function, division
import matplotlib
import logging
from sys import stdout
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import (Net, RealApplianceSource,
BLSTMLayer, DimshuffleLayer,
Bidirectio... |
# coding: utf8
from __future__ import unicode_literals
from cytoolz import partition_all, concat
from .._messages import Messages
from ...compat import json_dumps, path2str
from ...util import prints
from ...gold import iob_to_biluo
def iob2json(input_path, output_path, n_sents=10, *a, **k):
"""
Convert IOB ... |
#Python file to fetch specific jobs, cvs, categories in command line
# Example usage:
# python3 -u fetch.py 0 542 "description" > output.txt
from pathlib import Path
import sys
import json
import os
def process(jeysan, property_name):
if property_name == "all":
print(json.dumps(jeysan))
os._exit(0)
... |
from msrest.serialization import Model
class ExpressRouteCircuitsRoutesTableSummaryListResult(Model):
"""Response for ListRoutesTable associated with the Express Route Circuits
API.
:param value: A list of the routes table.
:type value: list of :class:`ExpressRouteCircuitRoutesTableSummary
<azur... |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v8.errors",
marshal="google.ads.googleads.v8",
manifest={"AdCustomizerErrorEnum",},
)
class AdCustomizerErrorEnum(proto.Message):
r"""Container for enum describing possible ad customizer errors. """
class... |
import clang.cindex
from .extract_functions import extract_functions
import extract_macros
import collections
import blist
import itertools
class FeatureExtractor(object):
"""This object is the interface to all of this module's functions. Usage is simple; instanciate it with a ist of files, and then use the function... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (<EMAIL>)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, e... |
import sys
try:
import rdpy.core.log as log
from PyQt4 import QtGui
from rdpy.protocol.rdp import rdp
from rdpy.ui.qt4 import RDPBitmapToQtImage
from rdpy.core.error import RDPSecurityNegoFail
except ImportError:
print '[*] RDP libraries not found.'
print '[*] Please run the script in the ... |
#!/usr/bin/env python
"""
################################################################################
# #
# shijian_examples_slugify #
# ... |
"""
Starter module for the Pomidorka app - the support tool for pomodoro technique
"""
__author__ = 'Andrey Vasilev <<EMAIL>>'
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import logging
from pomidorka import gui
if __name__ == '__main__':
app_license = '''
Pomidorka - the support tool fo... |
#!/usr/bin/python
import sys, os, pylab, numpy, matplotlib, math
import cPickle as pickle
""" pickle format
(int) start_time: The timestamp of the first user stream during the experiment.
start = pickle.load(f)
(int) end_time: The timestamp of the last user stream during the experiment.
end = pickle.load(f)
(list) co... |
from pagina import pagina
import subprocess as sp
import os
#per avviare ed uccidere un processo
#import subprocess as sp
#import signal
#
#child = sp.Popen( cmd , preexec_fn = os.setsid )
class pagina7 ( pagina ) :
def __init__ ( self, parent , grandParent , index ) :
pagina.__init__ ( self, parent , grandParen... |
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - SecurityPolicy implementing auto admin rights for some users and some groups.
AutoAdminGroup page contains users which automatically get admin rights
on their homepage and subpages of it. E.g. if ThomasWaldmann is in
AutoAdminGroup (or in a group contai... |
import click
import os
import shutil
from subprocess import Popen
import tempfile
REQUIREMENTS_FILE = "real-requirements.txt"
DEFAULT_OUTPUT_FILE = "requirements.hippo.txt"
class VirtualenvError(Exception):
pass
class PipError(Exception):
pass
class Sandbox(object):
def __init__(self):
self.l... |
# -*- coding: utf-8 -*-
from gi.repository import GdkPixbuf, GObject, Gtk, Gdk
from xlgui import icons
class CellRendererToggleImage(Gtk.CellRendererToggle):
"""
Renders a toggleable state as an image
"""
__gproperties__ = {
'icon-name': (
GObject.TYPE_STRING,
'i... |
"""A middleware that turns exceptions into parsable string.
Inspired by Cinder's faultwrapper.
"""
import sys
import traceback
from oslo_config import cfg
from oslo_utils import reflection
import six
import webob
from heat.common import exception
from heat.common import serializers
from heat.common import wsgi
cl... |
from __future__ import unicode_literals
from indico.modules.admin.views import WPAdmin
from indico.modules.events.management.views import WPEventManagement
from indico.modules.events.views import WPConferenceDisplayBase
class WPPaymentAdmin(WPAdmin):
template_prefix = 'events/payment/'
class WPPaymentEventMana... |
from django.test import TestCase
from corehq.apps.app_manager.dbaccessors import (
domain_has_apps,
get_all_app_ids,
get_all_built_app_ids_and_versions,
get_app,
get_apps_in_domain,
get_brief_apps_in_domain,
get_build_doc_by_version,
get_built_app_ids_for_app_id,
get_built_app_ids_wi... |
import sys
sys.path.insert(1, "../../../")
import h2o
def shuffling_large(ip,port):
print("Reading in Arcene training data for binomial modeling.")
train_data = h2o.upload_file(path=h2o.locate("smalldata/arcene/shuffle_test_version/arcene.csv"))
train_data_shuffled = h2o.upload_file(path=h2o.loc... |
#
# this file has no deps on Scorpion
#
import os
import re
import time
import json
import decimal
import md5
import pdb
import psycopg2
import traceback
from collections import *
from datetime import datetime
from scorpionsql.errfunc import *
from scorpionsql.sql import *
# JSON Encoder
class SummaryEncoder(json.... |
import argparse
import operator
import itertools
import datetime
import re
import sys
import os
try:
import columnize
except ImportError:
print 'Please install pycolumnize first -> sudo yum -y install pycolumnize'
import yum
try:
import git
except ImportError:
print 'Please install GitPython first -> su... |
from setuptools import setup
import imp
version = imp.load_source('trolldb.version', 'trolldb/version.py')
# requirements = ['geoalchemy2', 'sqlalchemy>=1.3.0', 'pyorbital',
# 'posttroll', 'shapely', 'psycopg2', 'paramiko',
# 'pymongo']
requirements = ['pymongo', 'pyyaml', 'posttroll... |
#TODO- learning chunks from wounds, process of recombination
#### 2014/2015 - node replaced in nltk 3.0 with label()
# 1-text becomes instructions (as chunks) becomes/generates text
# 2-also as genetic algo.
# so: how to train on wounds...? tag it first
# and what we expect to achieve? by training rather than just r... |
import numpy as np
import tvm
from tvm.contrib import graph_runtime
import nnvm.symbol as sym
import nnvm.compiler
from nnvm.testing.config import ctx_list
def test_update():
w = sym.Variable("w")
w2 = sym.Variable("w2")
w = sym._assign(w, w + 1)
w2 = sym._assign(w2, w + 1)
dshape = (5, 3, 18, ... |
from oie_readers.oieReader import OieReader
from oie_readers.extraction import Extraction
class PropSReader(OieReader):
def __init__(self):
self.name = 'PropS'
def read(self, fn):
d = {}
with open(fn) as fin:
for line in fin:
if not line.strip():
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#class Cesar(object):
import copy
class Cesar(object):
def __init__(self):
'''
Se definen los alfabetos que se deben utilizar para el cifrado y descifrado
dependiendo si se utiliza un texto o un archivo con su respectivo idima
para los textos
'''
self.ca... |
from pymclevel.materials import Block
from pymclevel.entity import TileEntity
from editortools.brush import createBrushMask
import numpy
from editortools.operation import mkundotemp
from albow import showProgress
import pymclevel
import datetime
import collections
from pymclevel import BoundingBox
import logging
log = ... |
#!/usr/bin/env python
from __future__ import division
import unittest
import numpy as np
import warnings
from pymatgen.core.lattice import Lattice
from pymatgen.core.operations import SymmOp
from pymatgen.symmetry.groups import PointGroup, SpaceGroup
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The ... |
import re
from datetime import datetime
from random import randint
PLUGIN_NAME = "Picobot"
PICO_REGEX = r"^(.*):\s*((\d+)\s*,\s*(\d+)|random)$"
def testFileParser(filename):
with open(filename) as f:
contents = f.read()
testRegex = re.compile(PICO_REGEX, re.M)
testNames = []
for testMatch in testRegex.fi... |
import numpy
from numpy.testing import assert_raises
from fuel import config
from fuel.datasets import CIFAR100
from fuel.streams import DataStream
from fuel.schemes import SequentialScheme
def test_cifar100():
train = CIFAR100('train', load_in_memory=False)
assert train.num_examples == 50000
handle = tr... |
'''
Copyright (C) 2017-2019 Vanessa Sochat.
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
This program is distribute... |
"""distutils.command.config
Implements the Distutils 'config' command, a (mostly) empty command class
that exists mainly to be sub-classed by specific module distributions and
applications. The idea is that while every "config" command is different,
at least they're all named the same, and users always see "conf... |
"""VAT (Maltese VAT number).
The Maltese VAT registration number contains 8 digits and uses a simple
weigted checksum.
>>> validate('MT 1167-9112')
'11679112'
>>> validate('1167-9113') # invalid check digits
Traceback (most recent call last):
...
InvalidChecksum: ...
"""
from stdnum.exceptions import *
from std... |
import datetime
import os
import shutil
import sys
import tempfile
# The rules for recognizing the headers look like this:
# - A header is contained between two horizontal rules,
# that is lines that consist of a sequence of at least
# 10 #'s surrounded by whitespace.
# - All lines inside the header must be em... |
import itertools
from .code_generator_info import CodeGeneratorInfo
from .composition_parts import WithCodeGeneratorInfo
from .composition_parts import WithComponent
from .composition_parts import WithDebugInfo
from .composition_parts import WithExposure
from .composition_parts import WithExtendedAttributes
from .cons... |
from . import schema
from .utils import get_properties
from Products.ZenModel.OSProcess import OSProcess as BaseOSProcess
class OSProcess(schema.OSProcess):
'''
Model class for OSProcess.
Extended here to support alternate monitoring template binding.
Depending on the version of Windows there are di... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: aci_access_port_to_interface_policy_leaf_profile
short_descr... |
# -*- coding: utf-8 -*-
from autoslug import AutoSlugField
# from util import *
from django.db import models
import util
from genericm2m.models import BaseGFKRelatedObject, RelatedObjectsDescriptor
DocumentTypes = (
('lyr', u'Текст на песен'),
('crd', u'Текст и акорди на песен'),
('dsc', u'Информация за песента'),... |
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.creden... |
from rekall.plugins.overlays.windows import tcpip_vtypes
from rekall.plugins.windows import common
# pylint: disable=protected-access
class Connections(tcpip_vtypes.TcpipPluginMixin,
common.WindowsCommandPlugin):
"""
Print list of open connections [Windows XP Only]
----------------------... |
__author__ = """T. Kim Nguyen <<EMAIL>> <unknown>"""
__docformat__ = 'plaintext'
import logging
logger = logging.getLogger('uwosh_grants: setuphandlers')
from Products.uwosh_grants.config import PROJECTNAME
from Products.uwosh_grants.config import DEPENDENCIES
import os
from config import product_globals
from Globals... |
#!/usr/bin/env python
# local imports
from . import utils
import json
import socket
def send_message(conf, cache, paste, paste_id):
'''
Send notification to channels
'''
host = conf.get('bottle', 'relay_host')
port = int(conf.get('bottle', 'relay_port'))
pw = conf.get('bottle', 'relay_pass')... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 27 00:00:00 2017
@author: JOJO
"""
#%% import modules
from __future__ import print_function
import numpy as np
import os
from models import alexnet
from constants import data_matrix_w as n_cols
from constants import data_matrix_h as n_rows
from constants import MODEL, ... |
from __future__ import print_function
import sys
from pyspark import SparkContext
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: sort <file>", file=sys.stderr)
exit(-1)
sc = SparkContext(appName="PythonSort")
lines = sc.textFile(sys.argv[1], 1)
sortedCount = lines.fl... |
"""
@dump_event
def invalidate_will_draw(self):
pass
@dump_return
def invalidate(self, context):
'''
Invalidate means queue a region to redraw at expose event.
GUI specific, not applicable to all surfaces.
'''
user_bounds = self.get_inked_bounds()
##device_coords = self.viewport... |
import codecs
from transaction import Transaction
import csv
import os
from decimal import Decimal
import util
def import_qt_tradehistory(csvfile):
"""Imports Questrade Trade History CSV fles. Files should be in utf-8
format. Will eventually type check this.
"""
with codecs.open(csvfile, 'rb', 'utf-8-sig') a... |
"""TensorFlow Eager execution prototype.
EXPERIMENTAL: APIs here are unstable and likely to change without notice.
To use, at program startup, call `tf.enable_eager_execution()`.
@@metrics
@@list_devices
@@num_gpus
@@py_func
@@defun
@@function
@@make_template
@@implicit_gradients
@@implicit_value_and_gradients
@@g... |
from itertools import groupby
import numpy as np
from operator import itemgetter
from os.path import exists, isdir, join
from os import makedirs
from splipy import SplineModel
class OpenFOAM(object):
def __init__(self, target):
self.target = target
def __enter__(self):
# Create the target d... |
import unittest
from copy import deepcopy
import mock
from google.cloud.bigquery_datatransfer_v1 import DataTransferServiceClient
from google.cloud.bigquery_datatransfer_v1.types import TransferConfig
from google.protobuf.json_format import ParseDict
from airflow.providers.google.cloud.hooks.bigquery_dts import BiqQu... |
import os.path as op
import pandas as pd
import numpy as np
import cooler
import bioframe
import click
from . import cli
from ..lib.common import assign_regions
from .. import dotfinder
from . import util
@cli.command()
@click.argument(
"cool_path",
metavar="COOL_PATH",
type=str,
nargs=1,
)
@click.ar... |
from bet_sizing import BetTiers
import handscore
import constants as C
class Fear(object):
"""Mix-in object for managing fear in the Brain"""
def update_fear(self, bet):
if not self.data.table_cards:
# TODO: should include re-raises eventually
preflop_fear = OpponentPreflopFear... |
"""
Show how to override basic methods so an artist can contain another
artist. In this case, the line contains a Text instance to label it.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import matplotlib.transforms as mtransforms
import matplotlib.text as mtext
class MyLine... |
""" Miscellaneous ressources. """
__all__ = ['testValidProgram', 'copyfile', 'Changedir',
'read_input', 'exec_input', 'load',
'RelativePath', 'LockFile', 'open_exclusive', 'translate_to_regex',
'mkdtemp', 'Redirect', 'local_path']
from types import ModuleType
from sys import version_in... |
__author__ = 'cjm'
import logging
import requests
# TODO: consider an external model
class BBOPGraph:
"""
foo
"""
nodemap = {}
def __init__(self, obj={}):
self.nodes = []
self.edges = []
self.add_json_graph(obj)
return
def add_json_graph(self, obj={}):
... |
import os
import sys
class Arguments:
dict = {}
error = ""
def parse(self) -> None:
if len(sys.argv) == 1:
self.error = self.usage()
return
if not os.path.exists(sys.argv[1]):
self.error = "Source directory doesn't exist."
return
dict = {}
dict['source'] = sys.argv[1]
... |
import nose.tools as ntools
import numpy
import requests
import unittest
from smqtk.representation.descriptor_element.solr_element import SolrDescriptorElement
__author__ = "<EMAIL>"
SOLR_URL = 'http://localhost:8983/solr' # is also a web-page
# Conduct test only if we have the solr module and if there is a de... |
from __future__ import unicode_literals
import hashlib
import logging
import os
try:
import cPickle as pickle
except:
import pickle
from pelican.utils import mkdir_p
logger = logging.getLogger(__name__)
class FileDataCacher(object):
"""Class that can cache data contained in files"""
def __init__(... |
from settings import LDAP_SERVER
from test_factory import SuperdeskTestCase
from superdesk import get_resource_service
from .commands import ImportUserProfileFromADCommand
class ImportUsersTestCase(SuperdeskTestCase):
def test_create_user_command(self):
if LDAP_SERVER:
user = {'username': 'sd... |
import argparse
import requests
APP_NAME = 'ddg-instant-py'
SEARCH_URL = 'https://api.duckduckgo.com/'
# Set up the argument parser
parser = argparse.ArgumentParser(description='Get an Instant Answer from the DuckDuckGo API.')
parser.add_argument('query', help='the query string')
args = parser.parse_args()
# Query t... |
#!/usr/bin/python
"""Commands and control for the Onkyo TX-NR708 eISCP interface.
Model website:
http://www.us.onkyo.com/model.cfm?m=TX-NR708&class=Receiver&p=i
Manual for the reciever:
http://63.148.251.135/redirect_service.cfm?type=own_manuals
&file=SN29400317_TX-NR708_En_web.pdf
"""
__author__ = 'Will Nowak... |
from monary import Monary
import numpy
from profile import profile
def do_monary_block_query():
count = 0
sums = numpy.zeros((5,))
with Monary("127.0.0.1") as m:
with profile("monary block query"):
for arrays in m.block_query(
"monary_test", # database ... |
from firedrake.petsc import PETSc
from argparse import ArgumentParser
from driver import run_profliler
import sys
PETSc.Log.begin()
parser = ArgumentParser(description=("""
Profile of 3D compressible solver for the Euler equations (dry atmosphere).
"""), add_help=False)
parser.add_argument("--hybridization",
... |
"""
Run Regression Test Suite
This module calls down into individual test cases via subprocess. It will
forward all unrecognized arguments onto the individual test scripts, other
than:
- `-extended`: run the "extended" test suite in addition to the basic one.
- `-win`: signal that this is running in a Windows... |
from sqlalchemy import Column
from sqlalchemy import exc
from sqlalchemy import Float
from sqlalchemy import func
from sqlalchemy import insert
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import schema
from sqlalchemy import select
from sqlalchemy import Sequence
from sqlalchemy impor... |
from wsgitest import expect
from wsgitest.config import SERVER_HOST, SERVER_PORT_RANGE
from wsgitest.testutils import *
def test_GET(env, start_response):
assert_equal(env['REQUEST_METHOD'], 'GET')
start_response('200 ok', [])
return ()
def test_POST(env, start_response):
'''
POST / HTTP/1.0
C... |
#!/usr/bin/env python
# encoding: utf-8
import os
import shutil
from tests.utils import TestUtils
from unittest import TestCase
from moodlefuse import MoodleFuse
from tests.data import settings
from moodlefuse.filesystem.file_operations import FileOperationOverrider
class MoodleFuseTestCase(TestCase):
pass
cla... |
"""DHCPv6 Prefix Delegation"""
# pylint: disable=invalid-name,line-too-long
import pytest
import references
import misc
import srv_control
import srv_msg
@pytest.mark.v6
@pytest.mark.PD
@pytest.mark.rfc3633
def test_prefix_delegation_IA_and_PD_confirm():
misc.test_setup()
srv_control.config_srv_subnet('30... |
from braces.views import JSONResponseMixin, AjaxResponseMixin
class HighChartsBasicView(JSONResponseMixin, AjaxResponseMixin):
title = None
subtitle = None
chart_type = None
tooltip = None
tooltip_point_format = None
plot_options = {}
def get_data(self):
data = {}
# Title ... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 24 22:14:48 2017
@author: Richard
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 18:16:55 2017
@author: Richard
Read pickle files with the equity price data and save them in a xlsx file
"""
from Tkinter import *
import ttk
import matplotlib
from matplotlib.figure... |
from shinken_test import *
class TestConfig(ShinkenTest):
#setUp is in shinken_test
def setUp(self):
self.setup_with_file('etc/nagios_bad_timeperiods.cfg')
#Change ME :)
def test_dummy(self):
#
# Config is not correct because of a wrong relative path
# in the main con... |
# -*- coding: utf-8 -*-
import elasticsearch
import sys
import os
import json
import pytest
import mock
from pytest_flask.plugin import client, config
import mongomock
from mocks import PLACE_BIELSK_NOT_FOR_VIEWING
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
... |
import unittest
class TestImportCmdset(unittest.TestCase):
def test_import_cmdset(self):
# self.assertEqual(expected, import_cmdset(python_path, cmdsetobj, emit_to_obj, no_logging))
assert True # TODO: implement your test here
class TestCmdSetHandler(unittest.TestCase):
def test___init__(self)... |
import re
import sys
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
text = text.replace('\n', '')
text = text.replace('<p', '\n <p')
scripts = re.compile(r'<script.*?/script>')
css = re.compile(r'<style.*?/style>')
text = text[text.find('<table '):]
text = scripts.sub('', text)
text =... |
# -*- coding: utf-8 -*-
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor, task
from smpp.pdu import operations
from pdu_bin import PDUBin
from client_settings import HOST, PORT, LOGIN, PASSWORD, SMSCOUNT
CONNECTED = 'connected'
DISCONNECTED = 'disconnected'
BINDED = '... |
from __future__ import unicode_literals
import json
# Django
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db import models, transaction
from django.utils import timezone
try:
from termcolor import cprint as _c... |
from __future__ import print_function
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors.execute import CellExecutionError
import glob
import traceback
import sys
import time
import os
import pytest
this_dir = os.path.dirname(__file__)
nbpath = os.path.join(this_dir, '... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
import xml.etree.ElementTree as ET
import requests
from flexget import plugin
from flexget.config_schema import one_or_more
from flexget.event import event
... |
#!/usr/bin/env python
import os
import glob
import subprocess
import argparse
import shutil
parser = argparse.ArgumentParser()
parser.add_argument("dir", help = "Input directory")
args = parser.parse_args()
def convert2wav(inputfile,logdir='log'):
if not os.path.exists(logdir):
os.mkdir(logdir)
extension = os... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import atexit
import logging
import os
import pendulum
import socket
from sqlalchemy import create_engine, exc
from sqlalchemy.orm import scoped_session, sessionmaker
fr... |
from __future__ import absolute_import
from PySide import QtGui, QtCore
from .worker import Worker
import os
import sys
import importlib
from .. import compat
__all__ = ['Application', 'Dialog', 'MutexLocker']
TOP_SECTION = '<b>%s</b>'
SECTION = '<br><b>%s</b>'
class Dialog(QtGui.QDialog):
def __init__(self, ... |
import logging
import os
import shutil
import threading
import pytest
from paramiko import RSAKey, SFTPServer, SFTP, Transport
from .loop import LoopSocket
from .stub_sftp import StubServer, StubSFTPServer
from .util import _support
# TODO: not a huge fan of conftest.py files, see if we can move these somewhere
# '... |
from .. import config
import logging
logger=logging.getLogger(__name__)
from smb.base import *
from smb.smb_structs import *
from nmb.NetBIOS import NetBIOS
from smb.SMBConnection import SMBConnection
import smb, random, hashlib, tempfile
import socket
ERROR_STRINGS = {
'NotReadyError': 'Authentication failed: %... |
#!/usr/bin/python
import os
import sys
import traceback
import hooking
'''
hugepages vdsm hook
===================
hook is getting hugepages=512 and will preserve 512
huge pages
hook is doing the following:
add pages: sysctl vm.nr_hugepages=516
add the following xml in domain\devices:
<memoryBacking>
<h... |
import inspect
import sys
import sqlalchemy.exc as exceptions
from sqlalchemy.sql import (
alias,
and_,
asc,
between,
bindparam,
case,
cast,
collate,
delete,
desc,
distinct,
except_,
except_all,
exists,
extract,
func,
insert,
intersect,
inter... |
import cgi
from webob import Request, Response
from webob.exc import HTTPNotFound
import json
import functools
import logging
from .validator import validate_args, ValidationError
from .utils import json_encode, is_file, FileIter
from .version import __version__
import threading
from wsgiref.simple_server import make_s... |
import abc
import base64
import datetime
import hashlib
import hmac
import os
import uuid
import struct
from lxml import etree
import dateutil.parser
import dateutil.tz
import nss.nss as nss
import gssapi
import six
from six.moves import xrange
from ipapython import admintool
from ipalib import api, errors
from ipase... |
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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.... |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'cleany.views.home', name='home'),
# url(r'^cleany/', include('cleany.foo.urls')),
# Uncomm... |
import requests
from requests.auth import HTTPDigestAuth, HTTPBasicAuth
import tempfile
from email.utils import formatdate
from artemis.Task import Task, AuthNature, TaskNature
import logging
import pycurl #until requests support sock5, no accreditation handling, http://tech.michaelaltfield.net/2015/02/22/pycurl-throu... |
"""Admin extensions for django-reversion."""
from __future__ import unicode_literals
from contextlib import contextmanager
from django.db import models, transaction, connection
from django.conf.urls import url
from django.contrib import admin
from django.contrib.admin import options
from django.contrib.admin.utils i... |
import logging
import time
import zmq
from pyre import Pyre
from pyre import zhelper
def chat_task(ctx, pipe, ncmds):
n = Pyre(ctx=ctx)
n.join("CHAT")
n.start()
# wait for someone else to join the chat
while not n.get_peer_groups():
pass
pipe.send('ready'.encode('utf-8'))
cmds ... |
import argparse
import json
import os
import sys
from jupyter_client.kernelspec import KernelSpecManager
from IPython.utils.tempdir import TemporaryDirectory
from ..kernelspec import LCWrapperKernelSpecManager
wrapper_kernel_json = {
"argv": [sys.executable, "-m", "lc_wrapper.bash", "-f", "{connection_file}"],
... |
import os
import sys
import logging
import openerp
import openerp.netsvc as netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID, api
from opene... |
"""Tools for dealing with preprocessing operations in the upload process
These functions are executed before the data is sent to geoserver. They're
main purpose is to prepare the data so that it can be ingested.
"""
from collections import namedtuple
import logging
import os.path
import subprocess
from .files impor... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# Create your models here.
# class SocialNetworkLink(models.Model):
# profile = models.ForeignK... |
"""Tests for the testing base code."""
from nova.openstack.common import rpc
from nova import test
class IsolationTestCase(test.TestCase):
"""Ensure that things are cleaned up after failed tests.
These tests don't really do much here, but if isolation fails a bunch
of other tests should fail.
"""
... |
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class MisagoBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USE... |
from . import interaction
from .interaction import Interaction
from .mouse_button import MouseButton
from .pointer_input import PointerInput
from selenium.webdriver.remote.webelement import WebElement
class PointerActions(Interaction):
def __init__(self, source=None):
if source is None:
sou... |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: python 2.7
@author: Sober.JChen
@license: Apache Licence
@contact: <EMAIL>
@software: PyCharm
@file: crop_save_and_view_nodules_in_3d.py
@time: 2017/3/14 13:15
"""
# ToDo ---这个脚本运行时请先根据预定义建好文件夹,并将candidates.csv文件的class头改成nodule_class并存为candidates_class.csv,否则会报错。... |
# Multi-cpu and Windows version: Greg Hazel
import os
if os.name == "nt":
import win32pdh
import win32api
class CPUMeterBase(object):
def __init__(self, update_interval = 2):
from twisted.internet import reactor
self.reactor = reactor
self._util = 0.0
self._util_each = []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.