content string |
|---|
import os
import re
from collections import namedtuple
from textwrap import dedent
# To avoid adding a new direct dependency, we import markdown from within mkdocs.
from mkdocs.structure.pages import markdown
from pyspark.java_gateway import launch_gateway
SQLConfEntry = namedtuple(
"SQLConfEntry", ["name", "d... |
from unittest import TestCase
from lybica.actions.user_script import _UserScriptAction
from lybica.__main__ import Context
import os
import shutil
class TestUserScriptAction(TestCase):
def setUp(self):
super(TestUserScriptAction, self).setUp()
self.context = Context()
os.environ['WORKSPACE... |
import unittest
from mock import MagicMock
from pytactoe.board import Board
from pytactoe.computer import Computer
class ComputerTests(unittest.TestCase):
def setUp(self):
self.computer = Computer("O")
self.board = Board()
def test_computer_initializes_with_a_mark(self):
self.assertEq... |
import numpy as np
import pylab
import os
import cv2
def getGroundTruth(fileNameGT):
'''
Returns the ground truth maps for roadArea and the validArea
:param fileNameGT:
'''
# Read GT
assert os.path.isfile(fileNameGT), 'Cannot find: %s' % fileNameGT
full_gt = cv2.imread(fileNameGT, cv2.CV_L... |
"""A simple invertible tokenizer.
Converts from a unicode string to a list of tokens
(represented as Unicode strings).
This tokenizer has the following desirable properties:
- It is invertible.
- Alphanumeric characters are broken away from non-alphanumeric characters.
- A single space between words does not produ... |
from ..daltools.util.full import init
Z = [8., 1., 1.]
Rc = init([0.00000000, 0.00000000, 0.48860959])
Dtot = [0, 0, -0.76539388]
Daa = init([
[ 0.00000000, 0.00000000, -0.28357300],
[ 0.15342658, 0.00000000, 0.12734703],
[-0.15342658, 0.00000000, 0.12734703],
])
QUc = init([-7.31176220, 0., 0., -5.432... |
import os
test = {
"deployment_code": os.path.join(os.path.dirname(os.path.abspath(__file__)), "deployment.py"),
"test_code": [
os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_suites/zookeeper_basic.py")],
"perf_code": os.path.join(os.path.dirname(os.path.abspath(__file__)), "log_naarad.py")... |
"""Error codes for PostgresSQL
This module contains symbolic names for all PostgreSQL error codes.
"""
# psycopg2/errorcodes.py - PostgreSQL error codes
#
# Copyright (C) 2006-2010 Johan Dahlin <<EMAIL>>
#
# psycopg2 is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser Genera... |
from __future__ import print_function, unicode_literals
import json
import sys
from type_alias import create_type_alias, find_type_aliases, find_union_types
from decoder import create_decoder, create_encoder, create_union_type_decoder, create_union_type_encoder
from helpers import *
def test():
testJson = """... |
from distutils.errors import DistutilsOptionError
from unittest import TestLoader
import unittest
import sys
from pkg_resources import (resource_listdir, resource_exists, normalize_path,
working_set, _namespace_packages,
add_activation_listener, require, EntryPoint... |
from selenium.webdriver.common import service
class Service(service.Service):
"""
Object that manages the starting and stopping of the IEDriver
"""
def __init__(self, executable_path, port=0, host=None, log_level=None, log_file=None):
"""
Creates a new instance of the Service
... |
"""
A python task automator, with a focus on task composition
"""
import ligament
import helpers
import buildtarget
import buildcontext
import buildcontextfseventhandler
import exceptions
import sys
import getopt
from helpers import pout
def print_helptext():
""" print helptext for command-line interface """
... |
import uuid
from locust import TaskSet
from helpers import settings
LMS_HOST = settings.data['LMS_HOST'].rstrip('\/')
class AuthenticationMixin(TaskSet):
"""Mixin that gives tasks different authentication methods."""
def __init__(self, parent):
super().__init__(parent)
self._setup_basic_au... |
# -*- coding: utf-8 -*-
def index():
pagina = request.args(0, cast=int, default=1)
itens_por_pagina = 5
total = db(db.noticias).count()
paginas = total / itens_por_pagina
if total % itens_por_pagina:
paginas += 1
limites = (itens_por_pagina * (pagina - 1), (itens_por_pagina * pagina))
... |
import imp
import importlib
import os
import os.path
import shutil
import sys
from test import support
from test.test_importlib import util
import unittest
import warnings
class LockTests(unittest.TestCase):
"""Very basic test of import lock functions."""
def verify_lock_state(self, expected):
self.a... |
import os
import sys
import tokenize
from optparse import OptionParser
from toolfunctions import checkDirectory
from toolfunctions import getFileContent
objMap = None
lastToken = [None, None]
stopTokens = ('OP', 'NAME', 'NUMBER', 'ENDMARKER')
def parseCommandLine():
global directory, onlyRemovable
parser = Op... |
"""
Declares toolchains.mpi namespace.
:author: Stijn De Weirdt (Ghent University)
:author: Kenneth Hoste (Ghent University)
"""
__path__ = __import__('pkgutil').extend_path(__path__, __name__) |
"""Tests for google.protobuf.text_encoding."""
try:
import unittest2 as unittest #PY26
except ImportError:
import unittest
from google.protobuf import text_encoding
TEST_VALUES = [
("foo\\rbar\\nbaz\\t",
"foo\\rbar\\nbaz\\t",
b"foo\rbar\nbaz\t"),
("\\'full of \\\"sound\\\" and \\\"fury\\\"\\'"... |
from __future__ import absolute_import, division, unicode_literals
from html5lib import constants, parseFragment, serialize
from html5lib.filters import sanitizer
def runSanitizerTest(_, expected, input):
parsed = parseFragment(expected)
expected = serialize(parsed,
omit_optional_tag... |
"""Tests for pprof_profiler."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
from proto import profile_pb2
from tensorflow.core.framework import step_stats_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.framework ... |
import uno
import string
import unohelper
import xmlrpclib
from com.sun.star.task import XJobExecutor
if __name__<>"package":
from lib.gui import *
from lib.functions import *
from lib.error import ErrorDialog
from LoginTest import *
from lib.rpc import *
database="test_001"
uid = 3
class ... |
"""
This file was automatically generated.
"""
class users(object):
def __init__(self, zap):
self.zap = zap
def users_list(self, contextid=''):
return next(self.zap._request(self.zap.base + 'users/view/usersList/', {'contextId' : contextid}).itervalues())
def get_user_by_id(self, context... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by <EMAIL> at 2014-04-18
import os
from .decrypt import decrypt
from .http import download
from mutagen.easyid3 import EasyID3
from mutagen.id3 import ID3, APIC
class Track(object):
''' A song '''
def __init__(self, tag):
''' @tag: a BeautifulSo... |
from unittest import TestCase
from libcloud.compute.types import Provider, NodeState, StorageVolumeState, \
VolumeSnapshotState, Type
class TestType(Type):
INUSE = "inuse"
class TestTestType(TestCase):
model = TestType
attribute = TestType.INUSE
def test_provider_tostring(self):
self.a... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import os
import tempfile
from distutils.version import LooseVersion
from ansible.module_ut... |
from south.db import db
from django.db import models
from cmsplugin_filer_teaser.models import *
from cmsplugin_filer_utils.migration import rename_tables_new_to_old
class Migration:
cms_plugin_table_mapping = (
# (old_name, new_name),
('cmsplugin_filerteaser', 'cmsplugin_filer_teaser_filerteaser... |
from __future__ import absolute_import
import datetime
import json
import logging
import os.path
import sys
from pip._vendor import lockfile
from pip._vendor.packaging import version as packaging_version
from pip.compat import total_seconds, WINDOWS
from pip.models import PyPI
from pip.locations import USER_CACHE_DI... |
from Analyser_Merge import Analyser_Merge, Source, SHP, Load, Mapping, Select, Generate
class Analyser_Merge_Bicycle_Rental_FR_bm(Analyser_Merge):
def __init__(self, config, logger = None):
self.missing_official = {"item":"8160", "class": 1, "level": 3, "tag": ["merge", "public equipment", "cycle"], "desc... |
from object_renderer import ObjectRenderer
from kivy.core.window import Window # noqa
from kivy.lang import Builder
from kivy.properties import NumericProperty, BooleanProperty
from kivy.clock import Clock
from kivy.animation import Animation
from math import cos, sin, pi
def dist(p1, p2):
return ((p1[0] - p2[0... |
from __future__ import unicode_literals
import logging
import time
from pyupdater import settings
log = logging.getLogger(__name__)
class KeyDB(object):
"""Handles finding, sorting, getting meta-data, moving packages.
Kwargs:
data_dir (str): Path to directory containing key.db
load (bool... |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import authenticate
from rest_framework import serializers, exceptions
from rest_framework.authtoken.serializers import AuthTokenSerializer
from activities.mode... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from argparse import ArgumentParser
from miasm2.analysis import debugging, gdbserver
from miasm2.jitter.csts import *
from miasm2.analysis.machine import Machine
from pdb import pm
parser = ArgumentParser(
description="""Sandbox raw binary with mips32 engine
(ex: jit_mi... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
EXAMPLES = r'''
- name: Task to boot a system using an ISO from an HP iLO interface only if... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chartsheet09.xlsx'
... |
from ._compat import PY2, text_type, long_type, JYTHON, IRONPYTHON, unichr
import datetime
from decimal import Decimal
import re
import time
from .constants import FIELD_TYPE, FLAG
from .charset import charset_by_id, charset_to_encoding
def escape_item(val, charset, mapping=None):
if mapping is None:
ma... |
from nupic.regions.ImageSensorExplorers.SpiralSweep import SpiralSweep
DEBUG = 0
class Jiggle(SpiralSweep):
"""
This explorer jiggles the image around each possible location within a specified
radius, being careful not to repeat movements already performed between any
two locations for maximum efficiency.
... |
#!/usr/bin/env python
# freely inspired by http://www.ros.org/wiki/arbotix_python/follow_controller
import roslib
import rospy, actionlib
from control_msgs.msg import FollowJointTrajectoryAction
from dynamixel_msgs.msg import JointState as JointStateDynamixel
from std_msgs.msg import Float64
... |
#!/usr/bin/env python
#coding=utf-8
from twisted.python import log
from toughradius.radiusd.settings import *
import datetime
def std_rate(resp,_in,_out):
input_limit = str(_in)
output_limit = str(_out)
_class = input_limit.zfill(8) + input_limit.zfill(8) + output_limit.zfill(8) + output_limit.zfill(8)
... |
"""This module classifies NativeHeap objects filtering their allocations.
The only filter currently available is 'stacktrace', which works as follows:
{'name': 'rule-1', 'stacktrace': 'foo' }
{'name': 'rule-2', 'stacktrace': ['foo', r'bar\s+baz']}
{'name': 'rule-3', 'source_path': 'sk.*allocator'}
{'name': 'rule-3', ... |
import sys
import argparse
import json
import datetime
from opserver_util import OpServerUtils
from sandesh_common.vns.ttypes import Module
from sandesh_common.vns.constants import ModuleNames, NodeTypeNames
import sandesh.viz.constants as VizConstants
from pysandesh.gen_py.sandesh.ttypes import SandeshType, SandeshLev... |
#!/usr/bin/env python
import sys
import pysam
def main():
if len(sys.argv) != 5:
print('extract_anchor.py sam fa i length')
sys.exit(0)
i = sys.argv[3]
length = int(sys.argv[4]) + 10
flag = ''
fa = pysam.Fastafile(sys.argv[2])
with open(sys.argv[1], 'r') as sam:
for lin... |
from slicc.symbols.Symbol import Symbol
class Event(Symbol):
def __repr__(self):
return "[Event: %s]" % self.ident
__all__ = [ "Event" ] |
from lib.alerttask import AlertTask
from mozdef_util.query_models import SearchQuery, TermMatch, PhraseMatch
class AlertSFTPEvent(AlertTask):
def main(self):
search_query = SearchQuery(minutes=5)
search_query.add_must([
TermMatch('category', 'execve'),
TermMatch('processna... |
""" Tests for editing descriptors"""
import unittest
import os
import logging
from mock import Mock
from pkg_resources import resource_string
from opaque_keys.edx.locations import Location
from xmodule.editing_module import TabsEditingDescriptor
from xblock.field_data import DictFieldData
from xblock.fields import Sco... |
# -*- coding: utf-8 -*-
"""
flask.sessions
~~~~~~~~~~~~~~
Implements cookie based sessions based on itsdangerous.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import uuid
import hashlib
from base64 import b64encode, b64decode
from datetime import dateti... |
import os, logging
import toml, json
import urllib.error
import base64
from tabulate import tabulate
# Local modules
import quince, nrtdb, nrtftp
import RetrieverFactory, PreprocessorFactory
# Extract the list of IDs from a set of instruments
def get_ids(instruments):
result = []
for instrument in instruments:
... |
from osv import fields, osv
class account_invoice(osv.osv):
_inherit = "account.invoice"
_columns = {
'internal_number': fields.char('Invoice Number', size=32, readonly=True, states={'draft':[('readonly',False)]}),
}
account_invoice() |
from django.core.management import call_command
from django.core.management.commands.syncdb import Command as SyncDBCommand
from optparse import make_option
class Command(SyncDBCommand):
option_list = SyncDBCommand.option_list + (
make_option('--skip-migrations',
action='store_false',
... |
"""
NonPhysicsWalker.py is for avatars.
A walker control such as this one provides:
- creation of the collision nodes
- handling the keyboard and mouse input for avatar movement
- moving the avatar
it does not:
- play sounds
- play animations
although it does send messeges that allow a listener t... |
from locale import gettext as _
from gi.repository import Gtk
from typecatcher_lib.helpers import get_media_file
from random import choice
def html_font_view(font=None, text=None):
start_page_icon = get_media_file("typecatcher.svg")
try:
con_icon_name = "nm-no-connection"
con_theme = Gtk.Ico... |
from pyttsx.drivers import _espeak
import ctypes
import wave
import time
import threading
import StringIO
class Synth(object):
_done = False
def __init__(self):
self.rate = _espeak.Initialize(_espeak.AUDIO_OUTPUT_RETRIEVAL, 1000)
assert self.rate != -1, 'could not initialize espeak'
_esp... |
#!/usr/bin/env python
"""
Extraction parsers for structured data embedded into HTML or XML files.
The former may include RDFa or microdata. The syntax and the extraction
procedures are based on:
* The RDFa specifications: http://www.w3.org/TR/#tr_RDFa
* The microdata specification: http://www.w3.org/TR/microdata/
* Th... |
"""WebMessage module web tests."""
from invenio.config import CFG_SITE_SECURE_URL
from invenio.testutils import make_test_suite, \
run_test_suite, \
InvenioWebTestCase
class InvenioWebSessionWebTest(InvenioWebTestCase):
"""WebSession web tests."""
... |
from optparse import OptionParser
import psycopg2
import os, sys
import csv
import re
from collections import namedtuple
p = OptionParser(usage='usage: %prog [options] outfile')
p.add_option('-V', '--product-version', dest='productversion',
help='Firefox version', default=None)
p.add_option('-s', '--start... |
"""The mdtraj package contains tools for loading and saving molecular dynamics
trajectories in a variety of formats, including Gromacs XTC & TRR, CHARMM/NAMD
DCD, AMBER BINPOS, PDB, and HDF5.
"""
import numpy as _ # silence cython related numpy warnings, see github.com/numpy/numpy/pull/432
from .formats.registry impo... |
from __future__ import absolute_import, division, print_function, \
with_statement
import hashlib
from shadowsocks.crypto import openssl
__all__ = ['ciphers']
def create_cipher(alg, key, iv, op, key_as_bytes=0, d=None, salt=None,
i=1, padding=1):
md5 = hashlib.md5()
md5.update(key)
... |
"""Classes for reading/writing binary data (such as TLS records)."""
from .compat import *
class Writer(object):
def __init__(self):
self.bytes = bytearray(0)
def add(self, x, length):
self.bytes += bytearray(length)
newIndex = len(self.bytes) - 1
for count in range(length):
... |
from django.db import connection
from django.contrib.auth.models import User, Permission
class ModelBackend(object):
"""
Authenticates against django.contrib.auth.models.User.
"""
supports_object_permissions = False
supports_anonymous_user = True
supports_inactive_user = True
# TODO: Mode... |
"""An XML Reader is the SAX 2 name for an XML parser. XML Parsers
should be based on this code. """
import handler
from _exceptions import SAXNotSupportedException, SAXNotRecognizedException
# ===== XMLREADER =====
class XMLReader:
"""Interface for reading an XML document using callbacks.
XMLReader is the... |
# encoding: 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 'Sell.cancel'
db.add_column('sell_sell', 'cancel', self.gf('django.db.models.fields.Boolean... |
#!"C:\Users\hog\Documents\Visual Studio 2010\Projects\ArdupilotMega\ArdupilotMega\bin\Debug\ipy.exe"
"""
process_file(filename)
takes templated file .xxx.src and produces .xxx file where .xxx
is .pyf .f90 or .f using the following template rules:
'<..>' denotes a template.
All function and subroutine blocks... |
"""Softplus bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
fr... |
"""MD4 cryptographic hash algorithm.
MD4 is specified in RFC1320_ and produces the 128 bit digest of a message.
>>> from Crypto.Hash import MD4
>>>
>>> h = MD4.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
MD4 stand for Message Digest version 4, and it was invented by Rivest in 1990.
This... |
#!/usr/bin/env python
'''Pygame module for interacting with events and queues.
Pygame handles all it's event messaging through an event queue. The routines
in this module help you manage that event queue. The input queue is heavily
dependent on the pygame display module. If the display has not been
initialized and a ... |
from django.db import models
from simple_history.models import HistoricalRecords
from .crf_model_mixin import CrfModelMixin, CrfInlineModelMixin
class PregnancyHistory(CrfModelMixin):
history = HistoricalRecords()
class Meta(CrfModelMixin.Meta):
app_label = 'ba_namotswe'
verbose_name = 'Pr... |
from twisted.internet import task, defer
from twisted.names import dns
from twisted.names import common
from twisted.names import client
from twisted.names import resolve
from twisted.python import log, failure
from twisted.application import service
class SecondaryAuthorityService(service.Service):
calls = None
... |
#!/usr/bin/env python
# coding=utf-8
import re
import json
import sys
fmt = '\033[0;3{}m{}\033[0m'.format
def cls():
print chr(27) + "[2J"
def fmtAnswer(s,sp=None):
r=re.sub("Answer:| |\r|\n","",s)
if sp is None:
a=[]
for i in r.upper():
a+=[i]
return a
return r.upper().split(sp)
def fmtI... |
#!/usr/bin/env python
"""
Applying perturbation theory to calculate the ground state energy
of the infinite 1D box of width ``a`` with a perturbation
which is linear in ``x``, up to second order in perturbation
"""
from sympy.core import pi
from sympy import Integral, var, S
from sympy.functions import sin, sqrt
de... |
""" (deprecated) generate a single-file self-contained version of pytest """
import os
import sys
import pkgutil
import py
import _pytest
def find_toplevel(name):
for syspath in sys.path:
base = py.path.local(syspath)
lib = base/name
if lib.check(dir=1):
return lib
mo... |
from datetime import datetime
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
# M2M described on one of the models
@python_2_unicode_compatible
class Person(models.Model):
name = models.CharField(max_length=128)
class Meta:
ordering = ('name',)
def __s... |
"""
Unit tests for Ecommerce feature flag in new instructor dashboard.
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from courseware.tests.tests import TEST_DATA_MONGO_MODULESTORE
from student.tests.factories import AdminFactory
from xmodule.modulestore.tests.django_... |
""" The core's core. """
from __future__ import print_function, division
# used for canonical ordering of symbolic sequences
# via __cmp__ method:
# FIXME this is *so* irrelevant and outdated!
ordering_of_classes = [
# singleton numbers
'Zero', 'One', 'Half', 'Infinity', 'NaN', 'NegativeOne', 'NegativeInfinity... |
import uuid
import hashlib
from .. import constants
ROUND = constants.DEFAULT_PRECISION
def bit_mask(flags):
"""Generate a bit mask.
:type flags: dict
:return: int
"""
bit = 0
true = lambda x, y: (x | (1 << y))
false = lambda x, y: (x & (~(1 << y)))
for mask, position in constant... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import MagicMock
from units.mock.loader import DictDataLoader
from ansible import errors
from ansible.playbook.block import Block
from ansible.pla... |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.security
~~~~~~~~~~~~~~~~~~~~~~~~~
Checks the sandbox and other security features.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import E... |
#!/usr/bin/env python
"""
Hacky helper application to collect form data.
"""
from werkzeug.serving import run_simple
from werkzeug.wrappers import Request, Response
def copy_stream(request):
from os import mkdir
from time import time
folder = 'request-%d' % time()
mkdir(folder)
environ = request.e... |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
from bokeh.util.api import INTERNAL, PUBLIC ; INTERNAL, PUBLIC
from bokeh.util.testing import verify_api ; verify_api
#-----------------------------------------------------------------------------
# Imports
#---... |
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
import numpy as np
import numpy.random as rnd
import copy
from mxnet.test_utils import assert_almost_equal
def check_diff_to_scalar(A, x, rank=None):
""" assert A == x"""
assert(np.sum(np.abs((A - x).asnumpy())) == 0), (rank, A.asnumpy(), x)
d... |
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the directory that is passed as an
argument:
nodes_main.txt
nodes_test.txt
These files must consist of lines in the format
<ip>
<ip>:<port>
[<ipv6>]
[<ipv6>]:<port>
<onion>.onion
0xD... |
"""INSPIRE authors."""
from __future__ import absolute_import, print_function
from .ext import INSPIREAuthors
from .receivers import *
__all__ = ('INSPIREAuthors', ) |
"""Extracts bounding boxes from a list of images, saving them to files.
The images must be in JPG format. The program checks if boxes already
exist, and skips computation for those.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import... |
# pylint: skip-file
# flake8: noqa
def main():
'''
ansible oc module for editing objects
'''
module = AnsibleModule(
argument_spec=dict(
kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
state=dict(default='present', type='str',
... |
# -*- coding: utf-8 -*-
import logging
import os
import time
import openerp
import openerp.addons.hw_proxy.controllers.main as hw_proxy
import threading
from openerp import http
from openerp.http import request
from openerp.tools.translate import _
_logger = logging.getLogger(__name__)
upgrade_template = """
<!DOCTY... |
#!/usr/bin/env python3
# @author Slandau3
def ranges(input: list) -> list:
# The patterns_found list keeps track of the definite ranges we have completed
patterns_found = []
# pattern_in_progress keeps track of a pattern we are tracing
pattern_in_progress = []
for i in input:
if len(patter... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.limiter
~~~~~~~~~~~~~~~~~~~~~~~~
A middleware that limits incoming data. This works around problems with
Trac_ or Django_ because those directly stream into the memory.
.. _Trac: http://trac.edgewall.org/
.. _Django: http://www.djangoproject.com/
... |
'''@file layer.py
Neural network layers '''
import tensorflow as tf
from tensorflow.python.ops.rnn import bidirectional_dynamic_rnn
from nabu.neuralnetworks.components import ops
def blstm(
inputs,
sequence_length,
num_units,
layer_norm=False,
scope=None):
'''
a BLSTM l... |
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def cloud_monitoring(module, state, label, agent_id, named_ip_addresses,
metadata):
if len(label) < 1 or len(label) > 255:
module.fail_json(msg='label must be between 1 and 255 characters long')
... |
import os
from helpers import run_cmd
from colorama import Fore
defaultTestDir = 'test-files'
defaultOutDir = 'test-outs'
"""
Run a single test
@param tFile- required; the full path to the file to run
@param level- optional (default: all); the compression level [1-9]
@return True if all tests passed; False if at lea... |
"""Helper class for instrumenation test jar."""
# pylint: disable=W0702
import collections
import logging
import os
import pickle
import re
import sys
from pylib import cmd_helper
from pylib import constants
sys.path.insert(0,
os.path.join(constants.DIR_SOURCE_ROOT,
'buil... |
#!/usr/bin/env python2
# coding=utf-8
import copy
import os
import json
import unicodecsv as csv
import codecs
from urllib2 import urlopen
from jinja2 import Environment, FileSystemLoader
CHINESE_WIKI_LANG = "zh"
SIMPLIFIED_CHINESE_LANG = "zh-hans"
TRADITIONAL_CHINESE_LANG = "zh-hant"
# Wikis that cause problems an... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_log_syslogd_override_filter
except Impor... |
from __future__ import absolute_import
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from hq.authentication import get_username_password
from hq.utils import get_dates
try:
from threading import local
except ImportError:
from django.utils._threading_local import loca... |
import math
def _float_check_precision(precision_digits=None, precision_rounding=None):
assert (precision_digits is not None or precision_rounding is not None) and \
not (precision_digits and precision_rounding),\
"exactly one of precision_digits and precision_rounding must be specified"
if pr... |
import sys
import argparse
import gzip
import math
def parseArgument():
# Parse the input
parser =\
argparse.ArgumentParser(description = "Get domain boundaries that are present in the 1st cell type but not in the 2nd")
parser.add_argument("--cellTypeOneDomainsFileName", required=True,
help='Domain boundaries ... |
from driver_log import Log
import types
######################################################################
#
# Shell Utilities
#
######################################################################
class shell(object):
@staticmethod
def unescape(s):
w = shell.split(s)
if len(w) == 0:
return ... |
import time
from lxml import etree
from openerp.osv import fields, osv
class asset_modify(osv.osv_memory):
_name = 'asset.modify'
_description = 'Modify Asset'
def _get_asset_method_time(self, cr, uid, ids, field_name, arg, context=None):
if ids and len(ids) == 1 and context.get('active_id'):
... |
# -*- coding: utf-8 -*-
"""
Extract Table of Content
========================
A Pelican plugin to extract table of contents (ToC) from `article.content` and
place it in its own `article.toc` variable for use in templates.
"""
from os import path
from bs4 import BeautifulSoup
from pelican import signals, readers, cont... |
import glob
import os
import re
import shutil
import tempfile
import urlparse
import pyauto_functional # Must be imported before pyauto
import pyauto
import test_utils
class OmniboxTest(pyauto.PyUITest):
"""Test cases for the omnibox."""
def Debug(self):
"""Test method for experimentation.
This method... |
import itertools
import os
import re
import libbe
import libbe.bug
import libbe.command
import libbe.command.depend
from libbe.command.depend import Filter, parse_status, parse_severity
import libbe.command.tag
import libbe.command.target
import libbe.command.util
# get a list of * for cmp_*() comparing two bugs.
AVA... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2017 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the righ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.