content stringlengths 4 20k |
|---|
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
class SessionManager(models.Manager):
use_in_migrations = True
def encode(self, session_dict):
"""
Return... |
"""Command line tool to start token master and workflow workers."""
import argparse
import gc
import guppy
import signal
import socket
import sys
import time
import threading
from django.core import management
from pinball.config.pinball_config import PinballConfig
from pinball.config.utils import get_log
from pinball... |
""" Test refcounting and behavior of SCXX.
"""
import sys
from numpy.testing import TestCase, dec, assert_, assert_raises
from scipy.weave import inline_tools
class TestDictConstruct(TestCase):
#------------------------------------------------------------------------
# Check that construction from basic ty... |
""" This module implements the DecompressionMiddleware which tries to recognise
and extract the potentially compressed responses that may arrive.
"""
import bz2
import gzip
import zipfile
import tarfile
from tempfile import mktemp
import six
try:
from cStringIO import StringIO as BytesIO
except ImportError:
... |
import subprocess
import datetime
import os
VERSION = __version__ = (0, 2, 0, 'final', 0)
NAME='django-uuid-pk'
__author__ = 'sax'
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert... |
import openerp.modules
import logging
_logger = logging.getLogger(__name__)
def is_initialized(cr):
""" Check if a database has been initialized for the ORM.
The database can be initialized with the 'initialize' function below.
"""
cr.execute("SELECT relname FROM pg_class WHERE relkind='r' AND relna... |
"""
A benchmark script to profile changes to typecheck's deep internals
"""
import time
### Bookkeeping ###
import support
if __name__ == '__main__':
support.adjust_path()
### /Bookkeeping ###
import typecheck
from typecheck import accepts
print "Using typecheck from", typecheck.__file__
def test_add_accepts_t... |
"""
Regression tests for proper working of ForeignKey(null=True). Tests these bugs:
* #7512: including a nullable foreign key reference in Meta ordering has un
xpected results
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
... |
import logging
from pylib import android_commands
from pylib.device import device_utils
class OmapThrottlingDetector(object):
"""Class to detect and track thermal throttling on an OMAP 4."""
OMAP_TEMP_FILE = ('/sys/devices/platform/omap/omap_temp_sensor.0/'
'temperature')
@staticmethod
de... |
from extensions.rich_text_components import base
TAB_CONTENT_SCHEMA = {
'type': 'dict',
'properties': [{
'name': 'title',
'description': 'Tab title',
'schema': {
'type': 'unicode',
'validators': [{
'id': 'is_nonempty'
}]
}
... |
import os
import gtk
from parameters import Parameters
class Column:
NAME = 0
PATH = 1
TIMESTAMP = 2
class HistoryList(gtk.Window):
"""History list is used to display complete browsing history."""
def __init__(self, parent, application):
# create main window
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)... |
def keyword(name=None, tags=()):
"""Decorator to set custom keyword names and tags to functions and methods.
This decorator creates the ``robot_name`` and ``robot_tags`` attributes on
the decorated keyword method or function. Robot Framework checks them to
determine the keyword's name and tags, respec... |
"""
Functional tests for the Cinder store interface
"""
import os
import oslo.config.cfg
import testtools
import glance.store.cinder as cinder
import glance.tests.functional.store as store_tests
import glance.tests.functional.store.test_swift as store_tests_swift
import glance.tests.utils
def parse_config(config):... |
import sys
import os
import datetime
import settings
_LEVEL_MAP = {
'debug': 4,
'info': 3,
'warning': 2,
'error': 1
}
def _header(level):
return settings.SERVICE_NAME+":"+level+' '+datetime.datetime.now().isoformat()+" |"
def _handler_stats(handler):
stats = handler.request.method+" "+\
... |
"""
Traditional Chinese language mappings for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
labels = {
# fixed: language-dependent
'author': u'\u4f5c\u8005', # '作者' <-- Chinese word
'authors': u'\u4f5c\u8005\u7fa4', # '作者群',
'organization': u'\u7d44\u7e54', # ... |
"""Model training for Iris data set using Validation Monitor."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
# Data sets
IRIS_TRAINING = os.path.join(os.pa... |
#!/usr/bin/env python
# texi-langutils.py
# WARNING: this script can't find files included in a different directory
import sys
import re
import getopt
import os
import langdefs
def read_pipe (command):
print command
pipe = os.popen (command)
output = pipe.read ()
if pipe.close ():
print "pip... |
from pycrc.main import main
import sys
if __name__ == "__main__":
sys.exit(main()) |
"""Test for end-to-end."""
import logging
import os
import signal
import socket
import subprocess
import sys
import time
import unittest
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from test import client_for_testing
from test import mux_client_for_testing
# Special message that tells... |
from django.http.request import HttpRequest
from django.test import TestCase, tag
from django.views.generic.base import ContextMixin
from edc_appointment.constants import INCOMPLETE_APPT
from edc_appointment.creators import UnscheduledAppointmentCreator
from edc_appointment.models import Appointment
from edc_base impor... |
from thespian.actors import *
from datetime import timedelta
from encoder import EncodeThis, Encoded, Encoder, Base64Encoder, Rot13Encoder
from morse import MorseEncoder
class Acceptor(ActorTypeDispatcher):
def __init__(self, *args, **kw):
super(Acceptor, self).__init__(*args, **kw)
# The analyze... |
# coding=utf-8
# --------------------------------------------------------------------------
# --------------------------------------------------------------------------
from msrest.serialization import Model
class StorageAccountProperties(Model):
"""StorageAccountProperties
:param provisioning_state: Gets t... |
"""Delegating optimizer to clip norm for specified variables."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import cli... |
import optparse
import os
import sys
from util import build_utils
from util import proguard_util
_DANGEROUS_OPTIMIZATIONS = [
"class/unboxing/enum",
# See crbug.com/625992
"code/allocation/variable",
# See crbug.com/625994
"field/propagation/value",
"method/propagation/parameter",
"method... |
from __future__ import unicode_literals
from django.db import migrations, models
from swh.web.config import scheduler
def _remove_archived_tasks_with_no_saved_status(apps, schema_editor):
"""
Scheduler tasks are archived on a regular basis so their completion
state could not be known anymore as previous ... |
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.functional.api import client
class TestServerGet(test.TestCase):
REQUIRES_LOCKING = True
def setUp(self):
super(TestServerGet, self).setUp()
self.useFixture(nova_fixtures.RealPolicyFixture())
self.u... |
"""
builder class for the tinderbox target
"""
from generic_stage import *
import catalyst.util
from catalyst.error import *
from catalyst.spawn import cmd
class tinderbox_target(generic_stage_target):
depends = ('system', 'stage3')
def __init__(self):
generic_stage_target.__init__(self)
self.required_values... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import serial
import struct
from time import sleep
from sys import argv
font = []
font += [ 0x00, 0x38, 0x44, 0x44, 0x44, 0x44, 0x38, 0x00] # /* 0 */
font += [ 0x00, 0x08, 0x38, 0x08, 0x08, 0x08, 0x08, 0x00] # /* 1 */
font += [ 0x00, 0x38, 0x44, 0x08, 0x10, 0x20, 0x7C, ... |
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = """
options:
host:
description:
- Specifies the DNS host name or address for connecting to the remote
device over the specified transport. The value of host is used as
the destination address f... |
from sympy import ratsimpmodprime, ratsimp, Rational, sqrt, pi, log, erf
from sympy.abc import x, y, z, t, a, b, c, d, e, f, g, h, i, k
def test_ratsimp():
f, g = 1/x + 1/y, (x + y)/(x*y)
assert f != g and ratsimp(f) == g
f, g = 1/(1 + 1/x), 1 - 1/(x + 1)
assert f != g and ratsimp(f) == g
f, ... |
"""
Given two strings s and t, t is a substring of s if t is contained as a
contiguous collection of symbols in s (as a result, t must be no longer
than s).
The position of a symbol in a string is the total number of symbols
found to its left, including itself (e.g., the positions of all
occurrences of 'U' in "AUGCUUC... |
# encoding: UTF-8
__author__ = 'CHENXY'
from string import join
from ksotp_struct import structDict
def processCallBack(line):
orignalLine = line
line = line.replace('\tvirtual void ', '') # 删除行首的无效内容
line = line.replace('{};\n', '') # 删除行尾的无效内容
content = line.split('(')
cb... |
"""
This module contains "matcher" classes. Matchers deal with posting lists. The
most basic matcher, which reads the list of postings for a term, will be
provided by the backend implementation (for example,
:class:`whoosh.filedb.filepostings.FilePostingReader`). The classes in this
module provide additional functional... |
"""
This module provides views that proxy to the staff grading backend service.
"""
import json
import logging
from django.conf import settings
from django.http import HttpResponse, Http404
from django.utils.translation import ugettext as _
from xmodule.course_module import CourseDescriptor
from xmodule.open_ended_g... |
""" Luks settings dialog (advanced mode) """
import os
import show_message as show
import misc.validation as validation
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
# When testing, no _() is available
try:
_("")
except NameError as err:
def _(message):
return message
cl... |
from __future__ import absolute_import
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from ..utils import (import_attribute,
email_address_exists,
valid_email_or_none)
fro... |
{
'name': 'Timesheets',
'version': '1.0',
'category': 'Human Resources',
'sequence': 24,
'summary': 'Timesheets, Attendances, Activities',
'description': """
Record and validate timesheets and attendances easily
=====================================================
This application supplies a n... |
import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('Misc')
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 15:12:13 2015
@author: meow
"""
from ortools.constraint_solver import pywrapcp
from networkx import nx
def graph_coloring_problem_or(G,limit,fixed):
n = G.number_of_nodes()
solver = pywrapcp.Solver("Graph coloring")
xs = [solver.IntVar(0,limit-1) for... |
import json
import logging
import zmq
from peerz import engine, utils
LOG = logging.Logger(__name__)
class Network(object):
"""
Client API for creating an interacting with
a nodes connection into the p2p network.
"""
def __init__(self, seeds, storage):
"""
Creates a new (not yet... |
"""Hierarchical Token Bucket traffic shaping.
Patterned after U{Martin Devera's Hierarchical Token Bucket traffic
shaper for the Linux kernel<http://luxik.cdi.cz/~devik/qos/htb/>}.
@seealso: U{HTB Linux queuing discipline manual - user guide
<http://luxik.cdi.cz/~devik/qos/htb/manual/userg.htm>}
@seealso: U{Token B... |
import sys
import types
import cStringIO
class MiniIndentPrinter:
def __init__(self,output):
self.out = output
self.col = 0
self.indent_step = 4
def writeln(self,text):
self.out.write(' '*self.col)
self.out.write(text)
self.out.write("\n")
def inde... |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import os
import numpy
import attrconf_old as attrconf
import bodyconf
from reid.utils.cache_manager import CacheManager
cachem = CacheManager(os.path.join('..', 'cache'), 'attr')
@cachem.save('raw')
def load_data(datasets):
"""Load images, corresponding body parts ma... |
import unittest
from telemetry.internal.platform import gpu_device
from telemetry.internal.platform import gpu_info
from telemetry.internal.platform import system_info
class TestSystemInfo(unittest.TestCase):
def testConstruction(self):
data = {
'model_name': 'MacBookPro 10.1',
'gpu': {
... |
# Testing rgbimg module
import rgbimg, os, uu
from test.test_support import verbose, unlink, findfile
class error(Exception):
pass
print 'RGBimg test suite:'
def testimg(rgb_file, raw_file):
rgb_file = findfile(rgb_file)
raw_file = findfile(raw_file)
width, height = rgbimg.sizeofimage(rgb_file)
... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
ASKBOT_AUTH_USER_COLUMNS = (
'website',
'about',
'gold',
'email_isvalid',
'real_name',
'location',
'reputation',
'gravatar',
'bronze',
'last_seen',
... |
import os
import sys
from setuptools import setup
from distutils.core import Command
from os.path import join as pjoin
try:
import epydoc # NOQA
has_epydoc = True
except ImportError:
has_epydoc = False
import libcloud.utils # NOQA
from libcloud.utils.dist import get_packages, get_data_files # NOQA
l... |
try:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.common.google import GoogleBaseError, QuotaExceededError, \
ResourceExistsError, ResourceInUseError, ResourceNotFoundError
_ = Provider.GCE
HAS_LIBCLOUD = True
except ImportEr... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
import hashlib, random, sys, os, time
__all__ = ['Nonce', 'Association', 'UserAssociation',
'UserPasswordQueueManager', 'UserPasswordQueue']
class Nonce(models.Model):
""" op... |
import optparse
import sys
import subprocess
import time
import os
import signal
import datetime
import commands
if len(sys.argv) < 2 or sys.argv[1].startswith('-'):
print 'Usage: %s <planfile>\nThis will cleanup the planfile and the logs from all participating hosts.' % sys.argv[0]
sys.exit(0)
if not sys.argv[1]... |
from setuptools import setup
from codecs import open
from os import path
import sys
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'pyked', '_version.py')) as version_file:
exec(version_file.read())
with open(path.join(here, 'README.md')) as readme_file:
readme = readme_file.read()
wi... |
"""Tests for launchers
Doesn't actually start any subprocesses, but goes through the motions of constructing
objects, which should test basic config.
Authors:
* Min RK
"""
#-------------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distrib... |
import qrcode
import qrcode.image.svg
import xml.etree.ElementTree as ET
import io
MAX_QR_CACHE_ENTRIES = 256
class QRImage(qrcode.image.svg.SvgPathFillImage):
YUU_CACHE = {}
QR_PATH_STYLE = "fill:#000;fill-opacity:1;fill-rule:nonzero;stroke:none"
BACKGROUND_COLOUR = "rgba(255,255,255,0.9)"
def _svg(... |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import NotFound
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin
from djangobmf.core.pagina... |
import os
import urlparse
from fnmatch import fnmatch
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
from xml.etree import ElementTree
import html5lib
import vcs
from item import Stub, ManualTest, WebdriverSpecTest, RefTest, TestharnessTest
from utils import rel_path_to_url, is_bla... |
"""
Test lldb-vscode setBreakpoints request
"""
import unittest2
import vscode
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
import lldbvscode_testcase
import os
class TestVSCode_breakpointEvents(lldbvscode_testcase.VSCodeTestCaseBase):
mydir ... |
__problem_title__ = "Reciprocal cycles II"
__problem_url___ = "https://projecteuler.net/problem=417"
__problem_description__ = "A unit fraction contains 1 in the numerator. The decimal " \
"representation of the unit fractions with denominators 2 to 10 are " \
"given:... |
from ducktape.services.service import Service
from ducktape.utils.util import wait_until
import os
import subprocess
"""
0.8.2.1 MirrorMaker options
Option Description
------ -----------
--abort.on.send.failure <Stop the Configure the mirror mak... |
from nose.tools import eq_ as eq
import errno
import os
import shutil
import stat
import sys
def mkdir(*a, **kw):
try:
os.mkdir(*a, **kw)
except OSError, e:
if e.errno == errno.EEXIST:
pass
else:
raise
def maketemp():
tmp = os.path.join(os.path.dirname(__fi... |
from . import Infinite
from .helpers import WriteMixin
class Spinner(WriteMixin, Infinite):
message = ''
phases = ('-', '\\', '|', '/')
hide_cursor = True
def update(self):
i = self.index % len(self.phases)
self.write(self.phases[i])
class PieSpinner(Spinner):
phases = [u'◷', u'... |
#
# These tests require gmpy and test the limits of the 32-bit build. The
# limits of the 64-bit build are so large that they cannot be tested
# on accessible hardware.
#
import sys
from decimal import *
from gmpy import mpz
_PyHASH_MODULUS = sys.hash_info.modulus
# hash values to use for positive and negative infin... |
from __future__ import absolute_import
from django.views.debug import SafeExceptionReporterFilter
from django.http import build_request_repr
class ZulipExceptionReporterFilter(SafeExceptionReporterFilter):
def get_post_parameters(self, request):
filtered_post = SafeExceptionReporterFilter.get_post_paramet... |
from __future__ import unicode_literals
from .common import InfoExtractor
class ESPNIE(InfoExtractor):
_VALID_URL = r'https?://espn\.go\.com/(?:[^/]+/)*(?P<id>[^/]+)'
_WORKING = False
_TESTS = [{
'url': 'http://espn.go.com/video/clip?id=10365079',
'info_dict': {
'id': 'FkYWtma... |
from tests.markup._util import alternate_expectation, desired_output
def simple_schema():
from flatland import Form, String
class SmallForm(Form):
name = "test"
valued = String
empty = String
return SmallForm({u'valued': u'val'})
### value
@desired_output('xhtml', simple_sche... |
"""
Utility functions for Image transfer.
"""
import StringIO
from nova import exception
from nova.image import glance
from nova.openstack.common import log as logging
from nova.virt.vmwareapi import io_util
from nova.virt.vmwareapi import read_write_util
LOG = logging.getLogger(__name__)
QUEUE_BUFFER_SIZE = 10
de... |
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QTableView
from PyQt5.QtSql import (QSqlQuery, QSqlRelation, QSqlRelationalDelegate,
QSqlRelationalTableModel, QSqlTableModel)
import connection
def initializeModel(model):
model.setTable('employee')
model.setEditStrategy(QSqlTabl... |
#!/bin/env python
""" A simple example for the usage of Person.send()
- random movement
- output to visual player, which is executed as child process
- you may try the other commented monitor examples - you can choose a single or multiple monitors
- print a message send to another person
"""
import sy... |
import test_controllers
checks = [
test_controllers,
]
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" This module contains an implementation of the 'b64' transport. """
from obfsproxy.transports.base import BaseTransport
import base64
import obfsproxy.common.log as logging
log = logging.get_obfslogger()
def _get_b64_chunks_from_str(string):
"""
Given a 'string... |
"""
Shopify OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/shopify.html
"""
import imp
import six
from social.utils import handle_http_errors
from social.backends.oauth import BaseOAuth2
from social.exceptions import AuthFailed, AuthCanceled
class ShopifyOAuth2(BaseOAuth2):
"""Shopify OA... |
"""Some utility functions for commands (e.g. for cmdline handling)
"""
# Authors: Yaroslav Halchenko <<EMAIL>>
#
# License: BSD (3-clause)
import imp
import os
import re
from optparse import OptionParser
import mne
def get_optparser(cmdpath, usage=None):
"""Create OptionParser with cmd source specific settings... |
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
def find_vswitch_by_name(host, vswitch_name):
for vss in host.config.network.vswitch:
if vss.name == vswitch_name:
return vss
return None
# Source from
# https://github.com/rreubenu... |
"""
Forms for the user accounts app.
"""
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.files.images import get_image_dimensions
from .models import UserProfile
from .settings import (AVATAR_HEIGHT_SIZE_PX,
AVATAR_WIDTH_SIZE_PX,
... |
from django.db.models import get_model
Category = get_model('catalogue', 'category')
def create_from_sequence(bits):
"""
Create categories from an iterable
"""
if len(bits) == 1:
# Get or create root node
name = bits[0]
try:
# Category names should be unique at the... |
from homeassistant.helpers.entity import Entity
import voluptuous as vol
import homeassistant.components.remote as remote
import homeassistant.helpers.config_validation as cv
from homeassistant.components.remote import (DOMAIN)
DATA_BROADLINK = 'broadlink'
DEPENDENCIES = ['broadlink']
SERVICE_LEARN = 'broadlink_lear... |
__metaclass__ = type
from zope.schema.vocabulary import SimpleTerm
from lp.services.webapp.vocabulary import ForgivingSimpleVocabulary
from lp.testing import TestCase
class TestForgivingSimpleVocabulary(TestCase):
"""Tests for ForgivingSimpleVocabulary."""
def setUp(self):
super(TestForgivingSimple... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import pytest
# pylint: disable-msg=W0612,E1101
from copy import deepcopy
import sys
from distutils.version import LooseVersion
from pandas.compat import range, lrange, long
from pandas import compat
from numpy.random import randn
import numpy as np
fr... |
# Importing standard libraries
import sys
'''
QuickSelect Function that selects kth position element in sorted array using quickSort
Params : a - array to be sorted
start - start position of to be sorted subset
end - end position of to be sorted subset
pos - the k where w... |
'''
Created on Aug 5, 2011
@author: sean
'''
from __future__ import print_function
import unittest
import ast
from graphlab.meta.asttools.visitors.symbol_visitor import get_symbols
class Test(unittest.TestCase):
def assertHasSymbols(self, codestring, expected_symbols, ctxts=(ast.Load, ast.Store)):
root... |
"""
Simplistic HTTP proxy support.
This comes in two main variants - the Proxy and the ReverseProxy.
When a Proxy is in use, a browser trying to connect to a server (say,
www.yahoo.com) will be intercepted by the Proxy, and the proxy will covertly
connect to the server, and return the result.
When a ReverseProxy is ... |
from .base import Browser, ExecutorBrowser, require_arg
from .webdriver import ChromedriverLocalServer
from ..executors import executor_kwargs as base_executor_kwargs
from ..executors.executorselenium import (SeleniumTestharnessExecutor,
SeleniumRefTestExecutor)
__wptrunner__... |
import re
import logging
import traceback
from google.appengine.api.mail import EmailMessage
from django.conf import settings
class UserMiddleware:
def process_request(self, request):
url = request.get_full_path()
match = re.search(r"/user/(?P<username>[\w\d\_]+)/.*", url)
... |
#!/usr/bin/python
import os;
import sys;
import socket;
if (len(sys.argv) != 3):
print("Usage : "+sys.argv[0] + " <infile> <outfile>");
sys.exit(1);
ifile = file(sys.argv[1],"r");
ofile = file(sys.argv[2],"w");
rawdata = ifile.readlines();
bundles = [];
def parsedataline(line):
toks = line.split(' ');
chr... |
"""
FOR TRAINING PURPOSES ONLY!
"""
from Parse_OMERO_Properties import USERNAME, PASSWORD, HOST, PORT
from omero.gateway import BlitzGateway
if __name__ == '__main__':
"""
NB: This block is only run when calling this file directly
and not when imported.
"""
"""
start-code
"""
# Conne... |
from __future__ import print_function
import numpy as np
try:
try:
# cElementTree on Python 2.5+
import xml.etree.cElementTree as etree
except ImportError:
# ElementTree on Python 2.5+
import xml.etree.ElementTree as etree
except ImportError:
try:
# cElementTree
... |
import re
from SCons.Script import * # the usual scons stuff you get in a SConscript
def generate(env):
"""
Add builders and construction variables for the
SubstInFile tool.
Adds SubstInFile builder, which substitutes the keys->values of SUBST_DICT
from the source to the target.
The values of... |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import selenium.webdriver.chrome.service as service
import tracebac... |
# -*- 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 field 'Option.min'
db.add_column(u'survey_option', 'min',
self.gf('django.db.... |
# -*- coding: utf-8 -*-
import arcpy
import mds
import mds.messages
import numpy
class GetVariableStatistics(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Get Variable Statistics"
self.description = "Calculates statistics for a variab... |
{'name': 'Switzerland - Bank type',
'description': """
Swiss localization Bank type. Add new bank types
================================================
This addons will add different bank type required by
DTA, and ESR system in order to manage duality of Post and bank systems
""",
'version': '1.1',
'author': 'Campt... |
# stdlib
import time
from types import ListType
# 3p
from nose.plugins.attrib import attr
try:
import psycopg2 as pg
except ImportError:
pg = None
# project
from tests.checks.common import AgentCheckTest
@attr(requires='pgbouncer')
class TestPgbouncer(AgentCheckTest):
CHECK_NAME = 'pgbouncer'
def t... |
import datetime
from os import path
import urllib
import numpy as np
import ocw.data_source.local as local
import ocw.dataset_processor as dsp
import ocw.evaluation as evaluation
import ocw.metrics as metrics
import ocw.plotter as plotter
# File URL leader
FILE_LEADER = "http://zipper.jpl.nasa.gov/dist/"
# Two Local... |
from odoo import api, fields, models
class AccountInvoice(models.Model):
_inherit = "account.invoice"
delegated_member_id = fields.Many2one(
comodel_name='res.partner',
string='Delegated Member',
)
def write(self, vals):
"""Change associated membership lines if delegated memb... |
__author__ = 'thauser'
from argh import arg
from six import iteritems
import logging
from pnc_cli import swagger_client
from pnc_cli import utils
import pnc_cli.cli_types as types
from pnc_cli.pnc_api import pnc_api
@arg("-p", "--page-size", help="Limit the amount of builds returned")
@arg("--page-index", help="Sele... |
import _mysql
from dealFile import *
#Get of Domains which has 2 interfaces have more than 15 examples
db=_mysql.connect(host="localhost",user="root",passwd="zxcv4321",db="DDI")
#db.query("""select COUNT(*) from PPI inner join example on (ID = PPI_ID) where domain1="ACT" and domain2="ACT" and topology_1 = 6 and topolog... |
import unittest
import os
import smartcols
class Table(unittest.TestCase):
def test_json(self):
"""Test smartcols.Table.json()"""
table = smartcols.Table()
column_name = table.new_column("NAME", 0.1)
column_age = table.new_column("AGE", 2)
line = table.new_line()
lin... |
#!/usr/bin/env python
import argparse
import collections
import warnings
import chainer
from chainer.training import extensions
import numpy
import babi
import memnn
def train(train_data_path, test_data_path, args):
device = chainer.get_device(args.device)
device.use()
vocab = collections.defaultdict... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import os
import requests
import sys
import tempfile
import zipfile
from . import Command
class Deploy(Command):
"""Deploy a module on an Odoo instance"""
def __init__(self):
super(Deploy, self).__init__()
self.session = requests.se... |
import yaml
import pprint
def test_implicit_resolver(data_filename, detect_filename, verbose=False):
correct_tag = None
node = None
try:
correct_tag = open(detect_filename, 'rb').read().strip()
node = yaml.compose(open(data_filename, 'rb'))
assert isinstance(node, yaml.SequenceNode)... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, varibles=None, **kwargs):
if not isinstance(terms, dict):
raise A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.