code
stringlengths
1
199k
from django.contrib import admin from modeltranslation.admin import TranslationAdmin from .models import Campaign class CampaignAdmin(TranslationAdmin): list_display = ("__str__", "url", "image", "active") admin.site.register(Campaign, CampaignAdmin)
import kivy kivy.require('1.9.1') from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.uix.scatter import Scatter from kivy.app import Builder from kivy.metrics import dp from kivy.graphics import Color, Line from autosportlabs.racecapture.geo.geopoint i...
import json import os, os.path import shutil as sh import sys from fabric.api import abort, local, prompt, warn try: from fabric.api import lcd as cd except ImportError: from fabric.api import cd from ubik import builder, packager defenv = builder.BuildEnv('_root','_root','.') file_map, file_map_table = None, N...
""" Tests the following set of sequences: z-a-b-c: (1X) a-b-c: (6X) a-d-e: (2X) a-f-g-a-h: (1X) We want to insure that when we see 'a', that we predict 'b' with highest confidence, then 'd', then 'f' and 'h' with equally low confidence. We expect the following prediction scores: inputPredScore_at1 ...
import IMP import IMP.algebra import IMP.core import IMP.atom import IMP.test class Tests(IMP.test.TestCase): """Tests for SurfaceMover.""" def test_init(self): """Test creation of surface mover.""" m = IMP.Model() surf = IMP.core.Surface.setup_particle(IMP.Particle(m)) surf.set_...
"""Exception classes for commands modules. Defined here to avoid circular dependency hell. """ class Error(Exception): """Base class for all cmdexc errors.""" class CommandError(Error): """Raised when a command encounters an error while running.""" pass class NoSuchCommandError(Error): """Raised when a ...
import serial import serial.tools.list_ports import copy import numpy as np import math import random class AsciiSerial: def __init__(self): self._graphsChannels = {'graph1': None, 'graph2': None, 'graph3': None, 'graph4': None} self._enChannels = {'graph1': False, 'graph2': False, 'graph3': False, ...
""" 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 distributed in the hope that it will be useful, but W...
from dealer.git import git from django.template import RequestContext requestcontext = None class MakoMiddleware(object): def process_request(self, request): global requestcontext requestcontext = RequestContext(request) requestcontext['is_secure'] = request.is_secure() requestcontex...
from bears.natural_language.AlexBear import AlexBear from tests.LocalBearTestHelper import verify_local_bear good_file = "Their network looks good." bad_file = "His network looks good." AlexBearTest = verify_local_bear(AlexBear, valid_files=(good_file,), ...
from amon.apps.alerts.checkers.system import system_alerts from amon.apps.alerts.checkers.process import process_alerts from amon.apps.alerts.checkers.plugin import plugin_alerts from amon.apps.alerts.checkers.healthcheck import healthcheck_alert_checker from amon.apps.alerts.models import alerts_model from amon.apps.p...
from lims.browser import BrowserView from dependencies.dependency import getToolByName from dependencies.dependency import check as CheckAuthenticator import json class ajaxGetInstruments(BrowserView): """ Returns a json list with the instruments assigned to the method with the following structure: ...
""" End-to-end tests for the Account Settings page. """ from unittest import skip from nose.plugins.attrib import attr from bok_choy.web_app_test import WebAppTest from ...pages.lms.account_settings import AccountSettingsPage from ...pages.lms.auto_auth import AutoAuthPage from ...pages.lms.dashboard import DashboardPa...
import sys from weboob.capabilities.job import ICapJob from weboob.tools.application.repl import ReplApplication, defaultcount from weboob.tools.application.formatters.iformatter import IFormatter, PrettyFormatter __all__ = ['Handjoob'] class JobAdvertFormatter(IFormatter): MANDATORY_FIELDS = ('id', 'url', 'publica...
from openerp.osv import fields from openerp.osv import osv from openerp import netsvc import time from datetime import datetime from openerp.tools.translate import _ class stock_move(osv.osv): _inherit = 'stock.move' _columns = { 'move_dest_id_lines': fields.one2many('stock.move','move_dest_id', 'Childr...
from django import template import re from django.utils.html import escape from urlparse import urlparse import logging register = template.Library() @register.inclusion_tag('profile/contributors.html') def show_other_contributors(project, user, count, **args): return { 'project': project, '...
from openerp.osv import orm from openerp.tools.translate import _ class logistic_requisition_cost_estimate(orm.TransientModel): _inherit = 'logistic.requisition.cost.estimate' def _check_requisition(self, cr, uid, requisition, context=None): """ Check the rules to create a cost estimate from the ...
from osv import fields from osv import osv import netsvc import tools from xml.dom import minidom import os, base64 import urllib2 try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from tools.translate import _ from report_aeroo_ooo.DocumentConverter import DocumentConversion...
from django.apps import AppConfig class CheckoutAppConfig(AppConfig): name = 'ecommerce.extensions.checkout' verbose_name = 'Checkout' def ready(self): super(CheckoutAppConfig, self).ready() # noinspection PyUnresolvedReferences import ecommerce.extensions.checkout.signals # pylint:...
import collections from functools import partial from django.db import models, transaction, connection, IntegrityError import logging from django.db.models import sql import itertools from amcat.models.coding.codingschemafield import CodingSchemaField from amcat.models.coding.coding import CodingValue, Coding from amca...
from pixelated.adapter.mailstore.searchable_mailstore import SearchableMailStore from pixelated.adapter.services.mail_service import MailService from pixelated.adapter.model.mail import InputMail from pixelated.adapter.services.mail_sender import MailSender from pixelated.adapter.search import SearchEngine from pixelat...
"""SCons.Platform.win32 Platform-specific initialization for Win32 systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ __revision__ = "/home/scons/scons/branch.0/baseline/src/engine/SCons/Platform/...
import os import unicodedata from tendrl.commons.event import Event from tendrl.commons.message import ExceptionMessage from tendrl.commons.utils import cmd_utils from tendrl.commons.utils import etcd_utils from tendrl.commons.utils import log_utils as logger def sync(): try: _keep_alive_for = int(NS.config...
import re fireWallState = None def modifyRunSettingsForHookInto(projectName, port): prepareBuildSettings(1, 0) # this uses the defaultQtVersion currently switchViewTo(ViewConstants.PROJECTS) switchToBuildOrRunSettingsFor(1, 0, ProjectSettings.BUILD) qtVersion, mkspec, qtBinPath, qtLibPath = getQtInf...
""" Current driven domain-wall motion with constant current and spin accumulation. """ from magnumfe import * mesh = BoxMesh(-600.0/2, -100.0/2, -10.0/2, 600.0/2, 100.0/2, 10.0/2, 120, 20, 1) state = State(mesh, scale = 1e-9, material = Material( alpha = 0.1, ms = 8e5, Aex = 1....
from django import forms from . import models class GroupForm(forms.ModelForm): class Meta: model = models.Group fields = '__all__'
from __future__ import absolute_import import logging import os import shlex import shutil import sys import traceback from flask import current_app from subprocess import PIPE, Popen, STDOUT from uuid import uuid1 from freight.exceptions import CommandError class Workspace(object): log = logging.getLogger('workspa...
"""The Virtual File System (VFS) extent.""" class Extent(object): """Extent. Attributes: extent_type (str): type of the extent, for example EXTENT_TYPE_SPARSE. offset (int): offset of the extent relative from the start of the file system in bytes. size (int): size of the extent in bytes. """ ...
__author__ = 'greghines' import numpy as np import os import pymongo import sys import cPickle as pickle import bisect import random import csv import matplotlib.pyplot as plt if os.path.exists("/home/ggdhines"): base_directory = "/home/ggdhines" else: base_directory = "/home/greg" def index(a, x): 'Locate ...
"""Simple datastore view and interactive console, for use in dev_appserver.""" import cgi import csv import cStringIO import datetime import logging import math import mimetypes import os import os.path import pickle import pprint import random import sys import time import traceback import types import urllib import u...
def authorized_to_manage_request(_, request, current_user, pushmaster=False): if pushmaster or \ request['user'] == current_user or \ (request['watchers'] and current_user in request['watchers'].split(',')): return True return False def sort_pickmes(_, requests, tags_order): """Sort pi...
import sys, re PATH_INSTALL = "./" sys.path.append(PATH_INSTALL) from androguard.core.androgen import AndroguardS from androguard.core.analysis import analysis TESTS_CASES = [ #'examples/android/TC/bin/classes.dex', 'examples/android/TestsAndroguard/bin/classes.dex', ] VALUES = { ...
from dsl_parser.interfaces import utils INTERFACES = 'interfaces' SOURCE_INTERFACES = 'source_interfaces' TARGET_INTERFACES = 'target_interfaces' NO_OP = utils.no_op()
"""A helper library for the runtime_configs command group."""
import logging import os import sys if (sys.version_info.major < 3) or (sys.version_info.major == 3 and sys.version_info.minor < 6): raise Exception("Must be using Python minimum version 3.6!") sys.path.insert(0, os.path.dirname(__file__)) from tesstrain_utils import ( parse_flags, initialize_fontconfig, ...
import re import os import sys import time import pydas.communicator as apiMidas import pydas.exceptions as pydasException import uuid import json import shutil from zipfile import ZipFile, ZIP_DEFLATED from subprocess import Popen, PIPE, STDOUT from contextlib import closing def loadConfig(filename): try: configfil...
from django.test import TestCase from zerver.decorator import \ REQ, has_request_variables, RequestVariableMissingError, \ RequestVariableConversionError, JsonableError from zerver.lib.validator import ( check_string, check_dict, check_bool, check_int, check_list ) import ujson class DecoratorTestCase(TestC...
from __future__ import absolute_import, division, print_function, with_statement from tornado import netutil from tornado.escape import json_decode, json_encode, utf8, _unicode, recursive_unicode, native_str from tornado import gen from tornado.http1connection import HTTP1Connection from tornado.httpserver import HTTPS...
import sys, os os.environ["ENV_DEPLOYMENT_TYPE"] = "JustRedis" from src.common.inits_for_python import * action = "Extract and Upload IRIS Models to S3" parser = argparse.ArgumentParser(description="Parser for Action: " + str(action)) parser.add_argument('-u', '--url', help='URL to Download', ...
"""Log entries within the Google Stackdriver Logging API.""" import json import re from google.protobuf import any_pb2 from google.protobuf.json_format import Parse from google.cloud.logging.resource import Resource from google.cloud._helpers import _name_from_project_path from google.cloud._helpers import _rfc3339_nan...
import datetime from lxml import etree import webob from nova.api.openstack.compute import consoles from nova.compute import vm_states from nova import console from nova import db from nova import exception from nova import flags from nova import test from nova.tests.api.openstack import fakes from nova import utils FL...
__author__ = "Marelie Davel" __email__ = "mdavel@csir.co.za" """ Display the dictionary pronunciations of the most frequent words occuring in a speech corpus @param in_trans_list: List of transcription filenames @param in_dict: Pronunciation dictionary @param top_n: Number of words to verify @pa...
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
import errno import logging import os import posix from functools import reduce from typing import Optional, Set logger = logging.getLogger(__name__) OS_ALIASES = { "darwin": {"macos", "darwin", "macosx", "mac os x", "mac"}, "linux": {"linux", "linux2"}, } Pid = int def get_os_name(uname_result: Optional[posix....
import mock from oslo_config import cfg from oslo_messaging.rpc import dispatcher import six from heat.common import exception from heat.common import identifier from heat.engine.clients.os import keystone from heat.engine import dependencies from heat.engine import resource as res from heat.engine import service from ...
"""Fail if the C extension module doesn't exist. Only really intended to be used by internal build scripts. """ import sys sys.path[0:0] = [""] import bson import pymongo if not pymongo.has_c() or not bson.has_c(): sys.exit("could not load C extensions")
from share.transform.chain.exceptions import * # noqa from share.transform.chain.links import * # noqa from share.transform.chain.parsers import * # noqa from share.transform.chain.transformer import ChainTransformer # noqa from share.transform.chain.links import Context ctx = Context()
import webob from nova import compute from nova import db from nova import exception from nova import objects from nova.objects import instance as instance_obj from nova.openstack.common import jsonutils from nova import test from nova.tests.api.openstack import fakes from nova.tests import fake_instance UUID1 = '00000...
import logging from ..core import exceptions from ..coresight.cortex_m_core_registers import (CortexMCoreRegisterInfo, index_for_reg) from .metrics import CacheMetrics LOG = logging.getLogger(__name__) class RegisterCache(object): """@brief Cache of a core's register values. The only interesting part of this ca...
from __future__ import print_function import sys, os, logging, functools import multiprocessing as mp import mxnet as mx import numpy as np import random import shutil from mxnet.base import MXNetError curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) sys.path.append(os.path.join(curr_path, '.....
from rdflib import Literal from classes import ldp from namespaces import dcterms, oa, rdf ns = oa class Annotation(ldp.Resource): def __init__(self): super(Annotation, self).__init__() self.motivation = None def add_body(self, body): self.linked_objects.append((oa.hasBody, body)) ...
""" Base types used by other parts of libcloud """ from libcloud.common.types import LibcloudError, MalformedResponseError from libcloud.common.types import InvalidCredsError, InvalidCredsException __all__ = [ "Provider", "NodeState", "DeploymentError", "DeploymentException", # @@TR: should the unus...
""" Unit testing for affine_channel_op """ from __future__ import print_function import unittest import numpy as np from op_test import OpTest import paddle.fluid.core as core import paddle.fluid as fluid def affine_channel(x, scale, bias, layout): C = x.shape[1] if layout == 'NCHW' else x.shape[-1] if len(x.sh...
import libvirt import os import time from tests import data from tests import utils def verify_private_key(stdout): line = [l for l in stdout.split('\n') if l != ''] if ((line[0] == '-----BEGIN PRIVATE KEY-----' and line[-1] == '-----END PRIVATE KEY-----')): return stdout return '' def cwd(...
import mock from oslo_config import cfg from rally import exceptions from rally.plugins.openstack.scenarios.cinder import utils from tests.unit import fakes from tests.unit import test CINDER_UTILS = "rally.plugins.openstack.scenarios.cinder.utils" CONF = cfg.CONF class CinderScenarioTestCase(test.ScenarioTestCase): ...
from __future__ import unicode_literals import django.contrib.postgres.fields.ranges from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('climate_data', '0019_auto_20170613_0241'), ] operations = [ migrations.Crea...
""" This sample shows how to update the large thumbnail of an item Python 2.x ArcREST 3.0.1 """ import arcrest from arcresthelper import securityhandlerhelper from arcresthelper import common def trace(): """ trace finds the line, the filename and error message and returns it to ...
''' :codeauthor: :email:`Mike Place <mp@saltstack.com>` ''' from __future__ import absolute_import import os import logging import tornado.gen import tornado.ioloop import tornado.testing import salt.utils import salt.config import salt.exceptions import salt.transport.ipc import salt.transport.server import salt.t...
"""Arm(R) Ethos(TM)-N integration mean tests""" import numpy as np import tvm from tvm import relay from tvm.testing import requires_ethosn from . import infrastructure as tei def _get_model(shape, axis, keepdims, input_zp, input_sc, output_zp, output_sc, dtype): a = relay.var("a", shape=shape, dtype=dtype) cas...
"""Test configuration for the ZHA component.""" from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch import pytest import zigpy from zigpy.application import ControllerApplication import zigpy.config import zigpy.group import zigpy.types from homeassistant.components.zha import DOMAIN import homeassistan...
import json import pytest from indy import crypto, did, error @pytest.mark.asyncio async def test_auth_crypt_works_for_created_key(wallet_handle, seed_my1, verkey_my2, message): verkey = await did.create_key(wallet_handle, json.dumps({'seed': seed_my1})) await crypto.auth_crypt(wallet_handle, verkey, verkey_my2...
import math import mock import mox from oslo_config import cfg from oslo_serialization import jsonutils from oslo_utils import units from cinder.brick.initiator import connector from cinder import exception from cinder.image import image_utils from cinder.openstack.common import log as logging from cinder import test f...
"""The tests for the Tasmota sensor platform.""" import copy import datetime from datetime import timedelta import json from unittest.mock import Mock, patch import hatasmota from hatasmota.utils import ( get_topic_stat_status, get_topic_tele_sensor, get_topic_tele_will, ) import pytest from homeassistant i...
'''browse the repository in a graphical way The hgk extension allows browsing the history of a repository in a graphical way. It requires Tcl/Tk version 8.4 or later. (Tcl/Tk is not distributed with Mercurial.) hgk consists of two parts: a Tcl script that does the displaying and querying of information, and an extensio...
import numpy as np import os import copy import re """ Created on July 12, 2018 @author: wangc """ def _deweird(s): """ Sometimes numpy loadtxt returns strings like "b'stuff'" This converts them to "stuff" @ In, s, str, possibly weird string @ Out, _deweird, str, possibly less weird string """ if ...
"""Support for BMW car locks with BMW ConnectedDrive.""" import logging from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN from homeassistant.components.lock import LockDevice from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED DEPENDENCIES = ['bmw_connected_drive'] _LOGGER = logging...
"""Common array methods.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import enum import functools import math import numbers import numpy as np import six from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtype...
from SubjectNodes import SubjectNode class MultiClassSubjectNode(SubjectNode): def __init__(self): SubjectNode.__init__(numClasses=1) def __changeClassificationAttributes__(self,attributesList): pass
'''Tests for helpers_views''' from mysite import settings from mysite.helpers.db_access import DBAccess from mysite.helpers import testhelpers as th from heatmap.helpers.table_view import (TableForm, QueryForm) from heatmap.helpers import test_helpers_views as thv from django.test import TestCase # Provides mocks for ...
from __future__ import unicode_literals from .service import Service # noqa:flake8 __version__ = '1.0.1'
import datetime from helpers import unittest from datetime import timedelta import luigi import luigi.date_interval import luigi.interface import luigi.notifications from helpers import with_config from luigi.mock import MockTarget, MockFileSystem from luigi.parameter import ParameterException from worker_test import e...
import copy from threading import Lock from .metrics_core import Metric class CollectorRegistry(object): """Metric collector registry. Collectors must have a no-argument method 'collect' that returns a list of Metric objects. The returned metrics should be consistent with the Prometheus exposition forma...
"""Auto-generated file, do not edit by hand. 882 metadata""" from phonenumbers.phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_882 = PhoneMetadata(id='001', country_code=882, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='\\d{9}', possible_length=(9...
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "my-django-skeleton", version = "0.1", url = 'http://github.com/lemonad/my-django-skeleton', license = 'BSD', description = "A skeleton setup fo...
from __future__ import unicode_literals import datetime from django.utils import timezone from django.test import TestCase from django.contrib.auth.models import User from django.test.utils import override_settings import six from happenings.models import Event @override_settings(CALENDAR_SHOW_LIST=True) class SetMeUp(...
import sys import unittest from pyasn1.codec.der.decoder import decode as der_decoder from pyasn1.codec.der.encoder import encode as der_encoder from pyasn1.type import char from pyasn1.type import namedtype from pyasn1.type import univ from pyasn1_modules import pem from pyasn1_modules import rfc5652 from pyasn1_modul...
from __future__ import print_function from builtins import input import sys import scipy import numpy import pmagpy.pmagplotlib as pmagplotlib def main(): """ NAME plot_2cdfs.py DESCRIPTION makes plots of cdfs of data in input file SYNTAX plot_2cdfs.py [-h][command line options] ...
import unittest from distutils.errors import CompileError from pythran.tests import TestFromDir import os import pythran from pythran.syntax import PythranSyntaxError from pythran.spec import Spec class TestOpenMP(TestFromDir): path = os.path.join(os.path.dirname(__file__), "openmp") class TestOpenMP4(TestFromDir):...
import csv import os from datetime import datetime import logging import re from dipper.sources.PostgreSQLSource import PostgreSQLSource from dipper.models.assoc.Association import Assoc from dipper.models.assoc.G2PAssoc import G2PAssoc from dipper.models.Genotype import Genotype from dipper.models.Reference import Ref...
from pygraz_website import filters class TestFilters(object): def test_url_detection(self): """ Test that urls are found correctly. """ no_urls_string = '''This is a test without any urls in it.''' urls_string = '''This string has one link in it: http://pygraz.org . But it al...
""" Script example of tissue classification """ from __future__ import print_function # Python 2/3 compatibility import numpy as np from nipy import load_image, save_image from nipy.core.image.image_spaces import (make_xyz_image, xyz_affine) from nipy.externals.argparse import ...
>>> import random >>> random.sample(range(10), 5) [7, 6, 3, 5, 1] >>> all(a < b for a, b in zip(_,_[1:])) False >>>
import logging import sys import traceback from collections import namedtuple import numpy as np import pandas as pd from scipy.stats import chisquare from . import categorizer as cat from . import draw from .ipf.ipf import calculate_constraints from .ipu.ipu import household_weights logger = logging.getLogger("synthpo...
from __future__ import absolute_import, unicode_literals from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from rest_framework.urlpatterns import format_suffix_patterns from . import views router = DefaultRouter() router.register(r'minion', views.MinionViewSet, 'minion') router....
import httplib import pprint import json import sys import logging import datetime import os import os.path import codecs class cmdb( object ): def __init__( self, args , info=None ): self.res = {} self.result = {} self.info = info self.args = args self.device_type = '机架服务器'...
from django.core.files.storage import FileSystemStorage import os from datetime import datetime from django.db import models from django.contrib.contenttypes.models import ContentType from django.utils.timezone import utc from autofixture.compat import get_GenericForeignKey from autofixture.compat import get_GenericRel...
from __future__ import absolute_import, print_function __all__ = ['DummyProvider'] from django.http import HttpResponse from sentry.identity.base import Provider from sentry.pipeline import PipelineView class AskEmail(PipelineView): def dispatch(self, request, pipeline): if 'email' in request.POST: ...
from eventkit_cloud.settings.prod import * # NOQA TESTING = True CELERY_ALWAYS_EAGER = True BROKER_BACKEND = "memory" PASSWORD_HASHERS = ("django.contrib.auth.hashers.MD5PasswordHasher",)
""" Let's say we play a game where I keep flipping a coin until I get heads. If the first time I get heads is on the nth coin, then I pay you 2n-1 dollars. How much would you pay me to play this game? You should end up with a sequence that you need to find the closed form of. If you don't know how to do this, write som...
try: import json except ImportError: import simplejson as json import calendar import datetime import decimal from functools import partial import locale import math import re import time import dateutil import numpy as np import pytest import pytz import pandas._libs.json as ujson from pandas._libs.tslib impor...
import numpy as np from parakeet import jit, testing_helpers @jit def true_divided(x): return True / x def test_true_divided_bool(): testing_helpers.expect(true_divided, [True], True) def test_true_divided_int(): testing_helpers.expect(true_divided, [1], 1) testing_helpers.expect(true_divided, [2], 0) d...
from __future__ import absolute_import from django.apps import apps from django.conf import settings from sentry.models import Organization, Project, ProjectKey, Team, User from sentry.receivers.core import create_default_projects, DEFAULT_SENTRY_PROJECT_ID from sentry.testutils import TestCase class CreateDefaultProje...
""" Tests for wham_rad. """ import unittest import os from md_utils.md_common import silent_remove, diff_lines from md_utils.press_dups import avg_rows, compress_dups, main __author__ = 'mayes' DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data') DUPS_DIR = os.path.join(DATA_DIR, 'press_dups') HEAD_RAW = os....
from __future__ import unicode_literals from prompt_toolkit import prompt if __name__ == '__main__': print('If you press meta-! or esc-! at the following prompt, you can enter system commands.') answer = prompt('Give me some input: ', enable_system_bindings=True) print('You said: %s' % answer)
""" Bit Writing Request/Response ------------------------------ TODO write mask request/response """ import struct from pymodbus3.constants import ModbusStatus from pymodbus3.pdu import ModbusRequest from pymodbus3.pdu import ModbusResponse from pymodbus3.pdu import ModbusExceptions from pymodbus3.utilities import pack...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) def softmax(): # Model variables x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) W = tf.Variable(tf.zeros(...
import collections from mock import MagicMock from mock import call from mock import patch from honcho.test.helpers import TestCase from honcho.export.upstart import Export FakeProcess = collections.namedtuple('FakeProcess', 'name') FIX_1PROC = [FakeProcess('web.1')] FIX_NPROC = [FakeProcess('web.1'), Fake...
from __future__ import unicode_literals import os import paramiko from django.utils import six from reviewboard.ssh.client import SSHClient from reviewboard.ssh.errors import (BadHostKeyError, SSHAuthenticationError, SSHError) from reviewboard.ssh.policy import RaiseUnknownHostKeyPol...
import socket try: import requests httplib2 = None except ImportError: requests = None try: import httplib2 except ImportError: raise ImportError('No module named requests or httplib2') ConnectionError = requests.exceptions.ConnectionError if requests else socket.error def wrap_http_...
from collections import defaultdict import os import ansiblelint.utils class AnsibleLintRule(object): def __repr__(self): return self.id + ": " + self.shortdesc def verbose(self): return self.id + ": " + self.shortdesc + "\n " + self.description def match(self, file="", line=""): re...