content
stringlengths
4
20k
import logging from ..primitive.manager import PrimitiveManager logger = logging.getLogger(__name__) class Robot(object): """ This class is used to regroup all motors and sensors of your robots. Most of the time, you do not want to directly instantiate this class, but you rather want to use a factory whic...
from __future__ import print_function, division import espressomd from espressomd import thermostat from espressomd import visualization import numpy as np import matplotlib matplotlib.use('WXAgg') from matplotlib import pyplot from threading import Thread from traits.api import HasTraits, Button, Any, Range, List, Enu...
# -*- coding: utf-8 -*- """unittest-xml-reporting is a PyUnit-based TestRunner that can export test results to XML files that can be consumed by a wide range of tools, such as build systems, IDEs and Continuous Integration servers. This module provides the XMLTestRunner class, which is heavily based on the default Te...
import logging import re from django.contrib.staticfiles.storage import staticfiles_storage from django.contrib.staticfiles import finders from django.conf import settings from xmodule.contentstore.content import StaticContent from opaque_keys.edx.locator import AssetLocator from six import text_type log = logging....
def main(request, response): import simplejson as json f = file('config.json') source = f.read() s = json.JSONDecoder().decode(source) url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1]) url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0]) response.headers.set("Content...
from django.conf.urls.defaults import patterns, url urlpatterns = patterns("symposion.reviews.views", url(r"^section/(?P<section_slug>[\w\-]+)/all/$", "review_section", {"reviewed": "all"}, name="review_section"), url(r"^section/(?P<section_slug>[\w\-]+)/reviewed/$", "review_section", {"reviewed": "reviewed"}...
from la.piecewise import * ''' The convolute_onepiece function is from http://www.mare.ee/indrek/misc/convolution.pdf slightly changed for our use ''' # Convolute two "one-piece" functions. Arguments F and G # are tuples in form (h(x), a_h, b_h), where h(x) is # the function and [a_h, b_h) is the range where the func...
def get_files_from_bibdoc(recid): """ Retrieves using BibDoc all the files related with a given record @param recid @return List of dictionaries containing all the information stored inside BibDoc if the current record has files attached, the empty list otherwise """ if...
# Working with TF commit 24466c2e6d32621cd85f0a78d47df6eed2c5c5a6 import math import numpy as np import tensorflow as tf import tensorflow.contrib.seq2seq as seq2seq from tensorflow.contrib.layers import safe_embedding_lookup_sparse as embedding_lookup_unique from tensorflow.contrib.rnn import LSTMCell, LSTMStateTupl...
import json class FailureDatabase(object): """Logs the failures happening in the Clovis backend.""" DIRTY_STATE_ERROR = 'startup_with_dirty_state' CRITICAL_ERROR = 'critical_error' def __init__(self, json_string=None): """Loads a FailureDatabase from a string returned by ToJsonString().""" self.is_dir...
import sys import random import traceback import telepot from telepot.delegate import per_chat_id, create_open, pave_event_space """ $ python3.5 guess.py <token> Guess a number: 1. Send the bot anything to start a game. 2. The bot randomly picks an integer between 0-99. 3. You make a guess. 4. The bot tells you to g...
# -*- coding: utf-8 -*- """ netvisor.schemas.products.get ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013-2016 by Fast Monkeys Oy. :license: MIT, see LICENSE for more details. """ from marshmallow import Schema, fields from ..fields import Decimal class UnitPriceSchema(Schema): amount = Decim...
import numpy as np import theano import theano.tensor as T from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from deap import base from deap import tools rng = np.random # 0 | 1 | 2 # ---+---+--- # 3 | 4 | 5 # ---+---...
"""Wraps the upstream safebrowsing_test_server.py to run in Chrome tests.""" import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(BASE_DIR, '..', '..', '..', '..', 'net', 'tools', 'testserver')) import testserver_base class ServerRunne...
""" Copyright 2016, 2017 UFPE - Universidade Federal de Pernambuco Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela ...
import xml.etree.ElementTree as ET from util_functions import is_number, xml_indent try: import lxml.etree LXML_IMPORTED = True except ImportError: LXML_IMPORTED = False class GRCXMLGenerator(object): """ Create and write the XML bindings for a GRC block. """ def __init__(self, modname=None, block...
# Python 2/3 compatibility from __future__ import absolute_import, division, print_function import xarray as xr import numpy as np import pandas as pd import xscale.signal.fitting as xfit def test_polyfit(): Nt, Nx, Ny = 100, 128, 128 rand = xr.DataArray(np.random.rand(Nt, Nx, Ny), dims=['time', 'x', 'y']) slopes =...
""" Context managers, i.e. things you can use with the 'with' statement. """ from __future__ import absolute_import import fcntl import os from contextlib import contextmanager @contextmanager def flock(lockfile, shared=False): """Lock a file object using flock(2) for the duration of a 'with' statement. ...
"""Encoding and decoding audio using FFmpeg.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.contrib.ffmpeg.ops import gen_decode_audio_op_py from tensorflow.contrib.ffmpeg.ops import gen_encode_audio_op_py from tensorflow.pyth...
import simplejson import urllib import openerp import openerp.addons.web.http as http from openerp.addons.web.http import request import openerp.addons.web.controllers.main as webmain from openerp.addons.web.http import SessionExpiredException from werkzeug.exceptions import BadRequest import werkzeug.utils class goog...
import re from keystonemiddleware import auth_token from oslo_log import log from magnum.common import exception from magnum.common import utils from magnum.i18n import _ LOG = log.getLogger(__name__) class AuthTokenMiddleware(auth_token.AuthProtocol): """A wrapper on Keystone auth_token middleware. Does ...
#!/usr/bin/env python """ @package mi.core.instrument.chunker Chunking buffer for MI work @file mi/core/instrument/chunker.py @author Steve Foley @brief A buffer structure that allows for combining fragments and breaking apart multiple instances of the same data from an instrument's data stream. """ __author__ = ...
"""Illustrates use of the :meth:`.AttributeEvents.init_scalar` event, in conjunction with Core column defaults to provide ORM objects that automatically produce the default value when an un-set attribute is accessed. """ from sqlalchemy import event def configure_listener(mapper, class_): """Establish attribute...
# -*- coding: utf-8 -*- """ FileSystem 文件系统路径安全类 用于删除类似 ../../ 这类非法的遍历到外部路径的string 作者 双羽 Python 3.2+ """ import os def toURLpath(oldpath): return oldpath.replace("\\","/").replace("//","/") class PathFilter(object): """ 路径过滤类 """ def __init__(self,root_path=None,allow_back_dir=True): """ ...
""" Simple datasets to be used for unit tests. """ __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" import numpy as np from theano.compat.six.move...
# $Id: cdp.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Cisco Discovery Protocol.""" import struct import dpkt CDP_DEVID = 1 # string CDP_ADDRESS = 2 CDP_PORTID = 3 # string CDP_CAPABILITIES = 4 # 32-bit bitmask CDP_VERSION = 5 # string CDP_PLATFORM = 6 # string CDP_IPPREFIX = 7 CDP_VTP_MGMT_...
from flask import Flask from passlib.hash import bcrypt from sixquiprend.config import * from sixquiprend.models.card import Card from sixquiprend.models.six_qui_prend_exception import SixQuiPrendException from sixquiprend.sixquiprend import app, db from sixquiprend.utils import * import random import unittest class C...
#!/usr/bin/env python """tilestache-server.py will serve your cache. This script is intended to be run directly from the command line. It is intended for direct use only during development or for debugging TileStache. For the proper way to configure TileStach for serving tiles see the docs at: http://tilestache.org...
import unittest import starsky_ingest import json import boto3 import settings import iris_settings import boto from moto import mock_sqs, mock_s3, mock_sns @mock_sqs @mock_s3 @mock_sns class TestIngest(unittest.TestCase): def test_process_message(self): # creating some mock sqs resources. We won't use ...
from optparse import make_option import sys from django.conf import settings from django.core.management.base import NoArgsCommand from django.core.management.color import no_style from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal from django.db import connections, router, transaction,...
"""SCons.Tool.linkloc Tool specification for the LinkLoc linker for the Phar Lap ETS embedded operating system. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005,...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import json import os import pipes import tempfile from ansible import constants as C from ansible.plugins.action import ActionBase from ansible.utils.boolean import boolean from ansible.utils.hashing import checksum from ansible....
""" Images Pipeline See documentation in topics/media-pipeline.rst """ import hashlib import six try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO from PIL import Image from scrapy.utils.misc import md5sum from scrapy.utils.python import to_bytes from scrapy.http imp...
import os import codecs from ansible import utils from ansible import constants as C from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase # ansible 2.4 try: from ansible.parsing.plugin_docs import read_docstring # load the definitions dstring = read_docstring(__file__.rep...
import skimage import skimage.io import skimage.transform import numpy as np # synset = [l.strip() for l in open('synset.txt').readlines()] # returns image of shape [224, 224, 3] # [height, width, depth] def load_image(path): # load image img = skimage.io.imread(path, mode='constant') img = img / 255.0 ...
"""Tests for segmentation_losses.py.""" from absl.testing import parameterized import tensorflow as tf from official.vision.beta.projects.volumetric_models.evaluation import segmentation_metrics class SegmentationMetricsTest(parameterized.TestCase, tf.test.TestCase): @parameterized.parameters((1, 'generalized', ...
from __future__ import division import numpy as np infiles = [] xyzfiles = [] outfiles = [] scales = [] xyzfiles.append('dcv5t.xyz') infiles.append('dcv5t_n.esp') outfiles.append('dcv5t_n.mps') scales.append(2) xyzfiles.append('dcv5t.xyz') infiles.append('dcv5t_h.esp') outfiles.append('dcv5t_h.mps') scales.append(2....
"""Horizontal bar graph""" from pygal.graph.bar import Bar from pygal.graph.horizontal import HorizontalGraph class HorizontalBar(HorizontalGraph, Bar): """Horizontal Bar graph""" def _plot(self): """Draw the bars in reverse order""" for serie in self.series[::-1]: self.bar(seri...
"""Tests for options manager for :class:`Poly` and public API functions. """ from sympy.polys.polyoptions import ( Options, Expand, Gens, Wrt, Sort, Order, Field, Greedy, Domain, Split, Gaussian, Extension, Modulus, Symmetric, Strict, Auto, Frac, Formal, Polys, Include, All, Gen, Symbols, Method) from sym...
# -*- coding: utf-8 -*- """ pygments.formatters.latex ~~~~~~~~~~~~~~~~~~~~~~~~~ Formatter for LaTeX fancyvrb output. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.formatter import Formatter from pygments.token import T...
# -*- coding: cp1252 -*- """ Portions copyright © 2005-2009, Stephen John Machin, Lingfo Pty Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above ...
"""Based on code from timeout_socket.py, with some tweaks for compatibility. These tweaks should really be rolled back into timeout_socket, but it's not totally clear who is maintaining it at this point. In the meantime, we'll use a different module name for our tweaked version to avoid any confusion. T...
# -*- coding: utf-8 -*- """ DataFrame client for InfluxDB """ import math import warnings from .client import InfluxDBClient class DataFrameClient(InfluxDBClient): """ The ``DataFrameClient`` object holds information necessary to connect to InfluxDB. Requests can be made to InfluxDB directly through the ...
import json from django.core.urlresolvers import reverse from rest_framework import serializers from olympia import amo from olympia.amo.helpers import absolutify from olympia.files.models import FileUpload class FileUploadSerializer(serializers.ModelSerializer): active = serializers.SerializerMethodField('get...
from asdf import tagged, yamlutil from astropy.modeling import mappings from astropy.utils import minversion from astropy.modeling import functional_models from astropy.io.misc.asdf.types import AstropyAsdfType __all__ = ['TransformType', 'IdentityType', 'ConstantType'] class TransformType(AstropyAsdfType): ve...
import airflow from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator from airflow.operators.hive_operator import HiveOperator from datetime import date, timedelta # ------------------------------------------------------------------...
import logging import os import sys ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) sys.path.append(ROOT_PATH) DEBUG = False TEMPLATE_DEBUG = DEBUG SITE_ID = 1 SITE_BRANDING = 'OpenStack' SITE_NAME = 'openstack' ENABLE_VNC = True LOGIN_URL = '/auth/login' LOGIN_REDIRECT_URL = '/' MEDIA_ROOT = os.path.join(...
from __future__ import division, print_function, absolute_import # Scipy imports. import numpy as np from numpy import pi from numpy.testing import (assert_array_almost_equal, TestCase, run_module_suite, assert_equal, assert_warns) from scipy.odr import Data, Model, ODR, RealData, OdrStop, O...
import datetime from random import randint from django.template.defaultfilters import slugify from django.db import models from django.utils import timezone class Language(models.Model): name = models.CharField(max_length=50) description = models.TextField() documentation_url = models.URLField(max_length=...
# -*- coding: utf-8 -*- def to_text(path, language="fra"): """Wraps Tesseract 4 OCR with custom language model. Parameters ---------- path : str path of electronic invoice in JPG or PNG format Returns ------- extracted_str : str returns extracted text from image in JPG or P...
#!/usr/bin/env python __author__ = 'Adam Smith, Tom Lennan' import inspect from copy import deepcopy from mi.core.exceptions import NotFound enum_classes = {} model_classes = {} message_classes = {} def getextends(type): """ Returns a list of classes that the object with the given type extends. @para...
import commands from lettuce.fs import FileSystem from nose.tools import assert_equals from tests.util import run_scenario current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'kale') def test_harvest_uses_test_runner(): 'harvest uses LETTUCE_TEST_SERVER specifie...
''' demandimport - automatic demandloading of modules To enable this module, do: import demandimport; demandimport.enable() Imports of the following forms will be demand-loaded: import a, b.c import a.b as c from a import b,c # a will be loaded immediately These imports will not be delayed: from a impor...
import etcd import hvbenchapi.conf as conf import hvbenchapi.tenant import logging log = logging.getLogger(__name__) class NoSuchInstance(Exception): pass class WrongAPIVersion(Exception): pass class HVBench: def __init__(self, host="127.0.0.1", port=2379): self._host = host self._e...
"""Tests for Compute Driver CPU resource monitor.""" import fixtures from nova.compute import manager from nova.compute.monitors import virt from nova import test class FakeLibvirt(object): def getCPUStats(self, cpuNum, flag): if cpuNum < 2: return {'kernel': 5664160000000L, ...
"""Acceptance tests for LMS-hosted Programs pages""" from nose.plugins.attrib import attr from ...fixtures.programs import ProgramsFixture, ProgramsConfigMixin from ...fixtures.course import CourseFixture from ..helpers import UniqueCourseTest from ...pages.lms.auto_auth import AutoAuthPage from ...pages.lms.programs ...
""" Reduce the halo catalog. """ import os, sys import numpy as np #Pull out the indices indices = {} with open("rockstar_config") as myfile: for line in myfile: name, var = line.partition("=")[::2] indices[name.strip()] = int(var) x_index = indices['x'] y_index = indices['y'] z_index = indices['z'...
import zipfile, os, codecs, datetime class ZipUtil(object): def zip_dir(cls, dir, zip_path=None, ignore_dirs=[], include_dirs=[]): if not zip_path: zip_path = "./%s.zip" % os.path.basename(dir) print "zip_path: ", zip_path if os.path.exists(zip_path): os.unlink(zi...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: replace author: Evan Kaufman (@EvanK) extends_docum...
from __future__ import print_function, division from sympy.core import S, sympify, diff from sympy.core.function import Function, ArgumentIndexError from sympy.core.relational import Eq from sympy.polys.polyerrors import PolynomialError from sympy.functions.elementary.complexes import im, sign from sympy.functions.ele...
"""Tests for tensorflow.python.client.session.Session's list_devices API.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.protobuf import cluster_pb2 from tensorflow.core.protobuf import config_pb2 from tensorflow.python import pywra...
from __future__ import (absolute_import, division, print_function) import numpy as np from .harmonics import ut_E from .utilities import Bunch from ._time_conversion import _normalize_time def reconstruct(t, coef, epoch='python', verbose=True, **opts): """ Reconstruct a tidal signal. Parameters ----...
""" sentry.tasks.fetch_source ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import itertools import logging import hashlib import re import urllib2 import zlib import base64 from os.path import splitext from colle...
import time import unittest import node CHANNEL_INIT = 19 PANID_INIT = 0xface NETWORK_NAME_FINAL = 'threadCert' PANID_FINAL = 0xabcd COMMISSIONER = 1 LEADER = 2 ROUTER1 = 3 ROUTER2 = 4 class Cert_9_2_16_ActivePendingPartition(unittest.TestCase): def setUp(self): self.nodes = {} for i in range(1...
from six.moves import queue import logging import os import threading from thrift.protocol import TBinaryProtocol from thrift.transport import TTransport logger = logging.getLogger(__name__) class TServer(object): """Base interface for a server, which must have a serve() method. Three constructors for all ...
"Memcached cache backend" import pickle import re import time import warnings from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.utils.deprecation import RemovedInDjango21Warning from django.utils.functional import cached_property class BaseMemcachedCache(BaseCache): def __init__...
from astroid.bases import BoundMethod from astroid.brain.helpers import register_module_extender from astroid.builder import parse from astroid.exceptions import InferenceError from astroid.manager import AstroidManager from astroid.scoped_nodes import FunctionDef def _multiprocessing_transform(): module = parse(...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} RETURNS = ''' name: description: Name of the External Router returned: always type: str sample: Server-IpAddrs id: description: AOS unique ID assigned to the External Router re...
"""Support for particulate matter sensors connected to a serial port.""" import logging from pmsensor import serial_pm as pm import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONF_NAME import homeassistant.hel...
from sympy.utilities.pytest import raises from sympy import symbols, Function, Integer, Matrix, Abs, \ Rational, Float, S, WildFunction, ImmutableMatrix, sin from sympy.core.compatibility import exec_ from sympy.geometry import Point, Ellipse from sympy.printing import srepr from sympy.polys import ring, field, ZZ,...
from __future__ import with_statement import os, re, string from time import time, sleep import aniDBfileInfo as fileInfo from aniDBmaper import AniDBMaper from aniDBtvDBmaper import TvDBMap from aniDBerrors import * from aniDBfileInfo import read_anidb_xml, read_tvdb_map_xml try: import xml.etree.cElementTree a...
""" This module houses the ctypes initialization procedures, as well as the notice and error handler function callbacks (get called when an error occurs in GEOS). This module also houses GEOS Pointer utilities, including get_pointer_arr(), and GEOM_PTR. """ import logging import os import re from ctypes import CD...
"""Implements the Embedded Atom Method""" from __future__ import absolute_import from .calculator import EAM from .io import mix_eam, read_eam, write_eam from .average_atom import average_potential
# -*- coding: utf-8 -*- """ Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Range Sum Query 2D The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which co...
# -*- coding: iso-8859-1 -*- """ MoinMoin - Create a list of currentpage?action=edit&template=X links for all available templates X. Used by MissingPage. @copyright: 2004 Johannes Berg <<EMAIL>> @license: GNU GPL, see COPYING for details. """ Dependencies = ["language"] def macro_EditTemplates(macro)...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from jinja2.exceptions import UndefinedError from ansible.errors import AnsibleError, AnsibleUndefinedVariable from ansible.plugins.lookup import LookupBase from ansible.utils.listify import listify_lookup_plugin_terms class Look...
"""Utility functions """ import numpy as np; import theano; def init_weights(name, out_dim, in_dim=None, weight_type="none"): """Create shared weights or bias Parameters ---------- out_dim : int output dimension in_dim : int ...
import unittest from bottle import static_file, request, response, parse_date, parse_range_header, Bottle, tob import wsgiref.util import os import tempfile import time class TestDateParser(unittest.TestCase): def test_rfc1123(self): """DateParser: RFC 1123 format""" ts = time.time() rs = t...
"""Sun OS Solaris platform implementation.""" import errno import os import socket import subprocess import sys from psutil import _common from psutil import _psposix from psutil._common import usage_percent, isfile_strict from psutil._compat import namedtuple, PY3 import _psutil_posix import _psutil_sunos as cext ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import six from tensorflow.contrib.eager.python import checkpointable from tensorflow.contrib.eager.python import network as network_lib from tensorflow.python.eager import context from tensor...
import sys sys.path.insert(1, "../../../") import h2o import pandas as pd import zipfile import statsmodels.api as sm def link_functions_gamma(ip,port): # Connect to h2o h2o.init(ip,port) print("Read in prostate data.") h2o_data = h2o.import_frame(path=h2o.locate("smalldata/prostate/prostate_complete.csv.zip")) ...
"""Plugin for swedish news paper Aftonbladet's streaming service.""" import re from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate from streamlink.stream import HDSStream, HLSStream PLAYLIST_URL_FORMAT = "http://{address}/{path}/{filename}" STREAM_TYPES = { "hds": HDSStream.pars...
"""Delegate test execution to another environment.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import re import sys import tempfile from .executor import ( SUPPORTED_PYTHON_VERSIONS, HTTPTESTER_HOSTS, create_shell_command, run_httptester, st...
import sys import string import os import re import time import math import vclib import sapi # If kconv module exists, character code conversion is enabled. try: import kconv except ImportError: multibyte = 0 else: multibyte = 1 re_includes = re.compile('\\#(\\s*)include(\\s*)"(.*?)"') def link_includes(text,...
import zookeeper, zktestbase, unittest, threading, sys if sys.version_info < (3,): range = xrange ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"} class GetSetTest(zktestbase.TestBase): def setUp( self ): zktestbase.TestBase.setUp(self) try: zookeeper.create(self...
import re import cherrypy import wikimarkup from openobject import rpc from openobject.widgets import CSSLink from openerp.widgets import register_widget from openerp.widgets.form import Text _image = re.compile(r'img:(.*)\.(.*)', re.UNICODE) _rss = re.compile(r'rss:(.*)\.(.*)', re.UNICODE) _attach = re.compile(r...
# -*- coding: utf-8 -*- from django.conf import settings from django.db.models import Q import re APPEND_TO_SLUG = "-copy" COPY_SLUG_REGEX = re.compile(r'^.*-copy(?:-(\d)*)?$') def is_valid_page_slug(page, parent, lang, slug, site, path=None): """Validates given slug depending on settings. """ from cms.mo...
import mock import os import shutil from oslo.config import cfg import six.moves.builtins as __builtin__ from ironic.common import exception from ironic.common import image_service from ironic.common import images from ironic.common import utils from ironic.openstack.common import imageutils from ironic.openstack.com...
from plugin.utils.klasses import Singleton from plugin.api.client_facade_api import ARCADIAClientFacade from proxy_tools import proxy class ARCADIAContext(object): __metaclass = Singleton def __init__(self): self._components = dict() self._relationships = dict() self._service_graph_instance = None self._c...
''' Tesselate Demonstration ======================= This demonstrates the experimental library for tesselating polygons. You should see a hollow square with some buttons below it. You can click and drag to create additional shapes, watching the number of vertexes and elements at the top of the screen. The 'debug' butt...
''' Some tests for filters ''' import numpy as np from numpy.testing import assert_equal, assert_raises import scipy.ndimage as sndi def test_ticket_701(): # Test generic filter sizes arr = np.arange(4).reshape((2,2)) func = lambda x: np.min(x) res = sndi.generic_filter(arr, func, size=(1,1)) #...
from __future__ import unicode_literals import frappe def execute(): frappe.db.sql("update tabItem set has_batch_no = 'No' where ifnull(has_batch_no, '') = ''") frappe.db.sql("update tabItem set has_serial_no = 'No' where ifnull(has_serial_no, '') = ''") item_list = frappe.db.sql("""select name, has_batch_no, has...
import sys sys.path.insert(1, "../../../") import h2o import random import string def nb_baddata(ip, port): h2o.init(ip, port) rawdata = [[random.gauss(0,1) for c in range(10)] for r in range(100)] print "Training data with all NA's" train = [["NA" for c in range(10)] for r in range(100)] train_h...
# ----------------------------------------------------------------------------- # yacc_misplaced.py # # A misplaced | in grammar rules # ----------------------------------------------------------------------------- import sys if ".." not in sys.path: sys.path.insert(0,"..") import ply.yacc as yacc from calclex import...
# -*- coding: utf-8 -*- """ wakatime.dependencies.php ~~~~~~~~~~~~~~~~~~~~~~~~~ Parse dependencies from PHP code. :copyright: (c) 2014 Alan Hamlett. :license: BSD, see LICENSE for more details. """ from . import TokenParser from ..compat import u class PhpParser(TokenParser): state = None ...
#!/usr/bin/env python import sys import csv import argparse from ddb import configuration if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-s', '--samples_file', help="Input configuration file for samples") parser.add_argument('-c', '--configuration', help="Configuratio...
"""Test for async task service status""" from django.utils import unittest from django.test.client import Client from django.core.urlresolvers import reverse import json class CeleryConfigTest(unittest.TestCase): """ Test that we can get a response from Celery """ def setUp(self): """ ...
[comment # this is a comment] [keyword import] [variable foo].[property bar] [keyword as] [def foobar] [keyword from] [variable foo] [keyword import] * [keyword from] [variable foo] [keyword import] bar [keyword from] [variable foo] [keyword import] bar [keyword as] [def foobar] [keyword from] [variable foo] [keyword ...
import logging import sys if (sys.version_info > (3,)): from urllib.parse import quote else: from urllib import quote import jsonpickle from cairis.core.MisuseCase import MisuseCase from cairis.test.CairisDaemonTestCase import CairisDaemonTestCase import os from cairis.mio.ModelImport import importModelFile __auth...
# Shows the tempos for all of the songs in a directory # requires eyeD3, available from http://eyed3.nicfit.net/ import sys import os from pyechonest import track AUDIO_EXTENSIONS = set(['mp3', 'm4a', 'wav', 'ogg', 'au', 'mp4']) def _bar(val, ref=100, char='='): if val: num_chars = int(val * float(ref))...