content
stringlengths
4
20k
"""Tests for Momentum.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf class MomentumOptimizerTest(tf.test.TestCase): def testBasic(self): ...
# Display a list of *.dat files in a bar chart. # Based on an example from https://chrisalbon.com/python/matplotlib_grouped_bar_plot.html import sys import os import matplotlib.pyplot as plt import numpy as np if len(sys.argv) > 3 and (len(sys.argv)-3) % 2 : print("usage: python3 {0} <benchmark> <image path> (<da...
from beritest_tools import BaseBERITestCase from nose.plugins.attrib import attr # # Test that cgetperm raises a C2E exception if the capability register is one # of the reserved registers, and the corresponding bit in PCC is not set. # class test_cp2_x_cgetperm_reg(BaseBERITestCase): @attr('capabilities') de...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib import linalg as linalg_lib from tensorflow.contrib.linalg.python.ops import linear_operator_test_util from tensorflow.python.framework import dtypes from tensorflow....
import utils as ut import pdb from sklearn.ensemble import ExtraTreesRegressor from sklearn.pipeline import Pipeline from sklearn.preprocessing import Imputer from sklearn.cross_validation import cross_val_score from sklearn.metrics import mean_squared_error import numpy as np import matplotlib.pyplot as plt import mat...
from openerp.osv import fields, osv class sale_order_line(osv.osv): _inherit = "sale.order.line" def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=Fal...
#!/usr/bin/env python import json import netaddr import os import random import re import requests import sys from azure.storage.blob import AppendBlobService from azure.storage.table import TableService import azure.mgmt.network from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.network ...
import sqlite3 import logging import os logging.basicConfig(level=logging.ERROR) # 数据库操作,负责连接、提交事务、断开数据库,返回操作的行数与结果列表 def operate(db_name, execute_str, execute_args=None): conn = sqlite3.connect(db_name + ".db") try: cursor = conn.cursor() if execute_args: cursor.execute(execute_s...
# Django settings for happybears project. import os PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) SITE_ROOT = os.path.dirname(PROJECT_ROOT) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '<EMAIL>'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.bac...
from dasbus.client.proxy import get_object_path from pyanaconda.anaconda_loggers import get_module_logger from pyanaconda.core.constants import PAYLOAD_TYPE_DNF from pyanaconda.modules.common.constants.services import PAYLOADS from pyanaconda.modules.common.task import sync_run_task log = get_module_logger(__name__) ...
""" This is a testing module, which exports some functions for the YAML tests. Instead of repeating the same FTP code all over, we prefer to have it in this file """ from ftplib import FTP from openerp.tools import config def get_plain_ftp(timeout=10.0): ftp = FTP() host = config.get('ftp_server_host'...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['stableinterface'], 'supported_by': 'curated'} try: import boto.ec2 from boto.s3.connection import OrdinaryCallingFormat, Location from boto.exception import BotoServerError, S3CreateError, S3ResponseError ...
""" Common utility functions useful throughout the contentstore """ import logging from opaque_keys import InvalidKeyError import re from datetime import datetime from pytz import UTC from django.conf import settings from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from ...
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): # metadata info about the module, not modified during runtime self.info = { # name for the module that will appear in module menus 'Name': 'Etcd Crawler', # list of one or mo...
import json import yaml from nose_parameterized import parameterized from unittest import skip from tests.st.test_base import TestBase from tests.st.utils.docker_host import DockerHost from tests.st.utils.utils import ETCD_CA, ETCD_CERT, \ ETCD_KEY, ETCD_HOSTNAME_SSL, ETCD_SCHEME, get_ip, \ retry_until_success...
import json import math import os from telemetry import benchmark from telemetry.core import util from telemetry.page import page_set from telemetry.page import page_test from telemetry.value import merge_values from telemetry.value import scalar def _GeometricMean(values): """Compute a rounded geometric mean from...
import mraa u = mraa.Uart(0) print u.getDevicePath()
""" Demo of the new boxplot drawer function """ import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook # fake data np.random.seed(937) data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75) labels = list('ABCD') # compute the boxplot stats stats = cbook.boxplot_stats(data, labels...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import unittest from pants.help.help_info_extracter import HelpInfoExtracter from pants.option.config import Config from pants.option.global_options import GlobalOpti...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Licens...
"""Spectral biclustering algorithms. Authors : Kemal Eren License: BSD 3 clause """ from abc import ABCMeta, abstractmethod import numpy as np from scipy.sparse import dia_matrix from scipy.sparse import issparse from . import KMeans, MiniBatchKMeans from ..base import BaseEstimator, BiclusterMixin from ..external...
"""Module progress tests""" import unittest from mock import Mock from xblock.field_data import DictFieldData from xmodule.progress import Progress from xmodule import x_module from . import get_test_system class ProgressTest(unittest.TestCase): ''' Test that basic Progress objects work. A Progress represent...
import time from cookielib import CookieJar as _CookieJar, DefaultCookiePolicy, IPV4_RE from scrapy.utils.httpobj import urlparse_cached class CookieJar(object): def __init__(self, policy=None, check_expired_frequency=10000): self.policy = policy or DefaultCookiePolicy() self.jar = _CookieJar(self...
from flask import (Blueprint, request, render_template, flash, send_from_directory, current_app as app) from werkzeug import secure_filename from flask.views import MethodView from users.models import User from models import Item, Meta from flask.ext.login import login_required, current_user from for...
import optparse import os import sys from util import build_utils from util import proguard_util _DANGEROUS_OPTIMIZATIONS = [ # See crbug.com/625992 "code/allocation/variable", # See crbug.com/625994 "field/propagation/value", "method/propagation/parameter", "method/propagation/returnvalue", ...
# Early, and incomplete implementation of -04. # import re import urllib RESERVED = ":/?#[]@!$&'()*+,;=" OPERATOR = "+./;?|!@" EXPLODE = "*+" MODIFIER = ":^" TEMPLATE = re.compile("{([^\}]+)}") def _tostring(varname, value, explode, operator, safe=""): if type(value) == type([]): if explode == "+": return...
import collections import os from typing import List, Tuple from ..utils.download import download_and_decompress from ..utils.env import DATA_HOME from .dataset import AudioClassificationDataset __all__ = ['ESC50'] class ESC50(AudioClassificationDataset): """ The ESC-50 dataset is a labeled collection of 20...
""" safe_eval module - methods intended to provide more restricted alternatives to evaluate simple and/or untrusted code. Methods in this module are typically used as alternatives to eval() to parse OpenERP domain strings, conditions and expressions, mostly based on locals condition/math builtins. "...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.network.fortios.fortios import fortios_argument_spec, fortios_requ...
#!/usr/bin/env python """ cdecl.py - parse c declarations (c) 2002, 2003, 2004, 2005 Simon Burton <<EMAIL>> Released under GNU LGPL license. version 0.xx """ import sys class Symbols(object): def __init__(self,parent=None,verbose=False): self.verbose = verbose self.parent=parent # are we a nested namesp...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} import json from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_ex...
# We're still on Django 1.4 and use django-setuptest. Use this as a starting # point for your test settings. Typically copy this file as test_settings.py # and replace myapp with your app name. from os.path import expanduser DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql...
# -*- coding: utf-8 -*- import fauxfactory import pytest import yaml from cfme import test_requirements from cfme.intelligence.reports.dashboards import Dashboard from cfme.intelligence.reports.reports import CustomReport from cfme.intelligence.reports.schedules import ScheduleCollection from cfme.intelligence.reports...
"""A `QueueRunner` that takes a feed function as an argument.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import from tensorflow.python.estimator.inputs.queues.feeding_queue_runner import _FeedingQueueRunner as FeedingQueueRu...
import matplotlib.pyplot as plt import numpy as np from scipy.special import erf, erfinv plt.close('all') z0 = 10**(-4) zhub = 0.1 D = 0.1 H = 1 Hh = 1 Nz = 144 # Generate the base profile uhub = 8.5 kappa = 0.4 utau = uhub*kappa/(np.log(10**3)) z = np.linspace(0, 1, num=Nz*2+1) zcc = z[1::2] ubase = utau/kappa*np.l...
from pybtex.style.formatting.unsrt import Style as UnsrtStyle class Style(UnsrtStyle): name = 'alpha' default_sorting_style = 'author_year_title' default_label_style = 'alpha'
#!/usr/bin/python # -*- coding: utf-8 -*- import logging import plugins_manager from base_crawler import BaseFrame from utils.crawler_exceptions import EmitterUnsupportedProtocol logger = logging.getLogger('crawlutils') class EmittersManager: """ Class that manages a list of formatter and emitter objects, ...
# Adapted from http://nbviewer.ipython.org/github/JonathanRaiman/theano_lstm/blob/master/Tutorial.ipynb import numpy as np from ..util import file_handling as fh class Vocab: def __init__(self, prefix, read_from_filename=None, tokens_to_add=None, add_oov=True): self.token2index = {} self.index2t...
from __future__ import division, print_function, absolute_import from functools import reduce import numpy as np import numpy.testing as npt from dipy.reconst.multi_voxel import _squash, multi_voxel_fit, CallableArray from dipy.core.sphere import unit_icosahedron def test_squash(): A = np.ones((3, 3), dtype=fl...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.che...
"""Display a subunit stream through a colorized unittest test runner.""" import heapq import subunit import sys import unittest import testtools class _AnsiColorizer(object): """ANSI colorizer that wraps a stream object. colorizer is an object that loosely wraps around a stream, allowing callers to wri...
# -*- coding: utf-8 -*- # ----- for creating dataset ----- from sklearn.datasets import load_digits from sklearn.cross_validation import train_test_split # ----- general import ----- import pandas as pd import numpy as np # ----- stacking library ----- from stacking.base import FOLDER_NAME, PATH, INPUT_PATH, TEMP_PA...
#!/usr/bin/python """distutils script for libwebp python module.""" from distutils.core import setup from distutils.extension import Extension import os import shutil import tempfile tmpdir = tempfile.mkdtemp() package = "com.google.webp" package_path = os.path.join(tmpdir, *package.split(".")) os.makedirs(package_p...
""" A test spanning all the capabilities of all the serializers. This class sets up a model for each model field type (except for image types, because of the PIL dependency). """ from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType fro...
from ctypes import * import unittest import sys class Test(unittest.TestCase): def test_array2pointer(self): array = (c_int * 3)(42, 17, 2) # casting an array to a pointer works. ptr = cast(array, POINTER(c_int)) self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2])...
from __future__ import absolute_import import __builtin__ import os import unittest from solfege import i18n __builtin__.testsuite_is_running = True outdir = 'test-outdir' class I18nSetup(unittest.TestCase): def setUp(self): self.__saved_LANGUAGE = os.environ.get('LANGUAGE', None) os.environ['...
""" Signals relating to comments. """ from django.dispatch import Signal # Sent just before a comment will be posted (after it's been approved and # moderated; this can be used to modify the comment (in place) with posting # details or other such actions. If any receiver returns False the comment will be # discarded a...
"""This code example gets all ad units within a network. To create ad units, run create_ad_units.py The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication informatio...
""" udplite protocl support class(es) http://libvirt.org/formatnwfilter.html#nwfelemsRulesProtoMisc """ from virttest.libvirt_xml import accessors, xcepts from virttest.libvirt_xml.nwfilter_protocols import base class Udplite(base.TypedDeviceBase): """ Create new Udplite xml instances Properties: ...
"""Package contenant le paramètre 'créer' de la commande 'auberge'.""" from primaires.interpreteur.masque.parametre import Parametre class PrmCreer(Parametre): """Commande 'auberge créer'""" def __init__(self): """Constructeur du paramètre.""" Parametre.__init__(self, "creer", "create") ...
import constants, sys from charsetprober import CharSetProber class CharSetGroupProber(CharSetProber): def __init__(self): CharSetProber.__init__(self) self._mActiveNum = 0 self._mProbers = [] self._mBestGuessProber = None def reset(self): CharSetProber.reset(se...
__author__ = '<EMAIL> (Jeff Scudder)' import atom.client # Old imports import urllib import urlparse import gdata.auth import gdata.service import atom.service class GDClient(atom.client.AtomPubClient): pass SCOPE_URL_PARAM_NAME = gdata.service.SCOPE_URL_PARAM_NAME # Maps the service names used in ClientLogi...
import gdb import re from variable import Variable from type import Type class GdbHelper(object): def parse_var_description(self, data): match = re.search(r"([^=]*)=(.*)", data) return (match.group(1).strip(), match.group(2).strip()) def parse_var_descriptions(self, data): variables ...
import logging import numpy import scipy import matplotlib import platform import wx from pysqlite2 import dbapi2 as sqlite from time import strftime # # A class to collect debug and trace information. # # # Dale Lane (http://dalelane.co.uk/blog) # enableTrace = False # used for indenting trace...
"""Tests for tensorflow.ops.tf.MatrixDeterminant.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import...
# encoding: cinje : from .. import table_args, caption_args : from datetime import timedelta : def songstatistics ctx : total_played_by_me = ctx.queries.get_total_played_by_me() : total_artists = ctx.queries.get_total_artists() : total_albums = ctx.queries.get_total_albums() <div class='table-respons...
""" ZMQ server test application. Use CTRL-C to end the application. NOTE! If connected to a Crazyflie this will power on the motors! """ from threading import Thread import signal import time import sys try: import zmq except ImportError as e: raise Exception("ZMQ library probably not installed ({})".format(...
import os ARCH = 'arm' CPU = 'arm926' # toolchains options CROSS_TOOL = 'gcc' #------- toolchains path ------------------------------------------------------- if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') if CROSS_TOOL == 'gcc': PLATFORM = 'gcc' # EXEC_PATH = 'D:/ArdaArmTools/Sour...
'''Unit test that checks preprocessing of files. Tests preprocessing by adding having the preprocessor provide the actual rctext data. ''' import os import sys if __name__ == '__main__': sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) import unittest import grit.tool.preprocess_interface fr...
from django.shortcuts import render import json from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.http import HttpResponse from rest_framework import status from core.api.custom_exceptions import CustomApiException from core.api.services import Services from rest_fra...
"""Class to hold all cover accessories.""" import logging from pyhap.const import CATEGORY_GARAGE_DOOR_OPENER, CATEGORY_WINDOW_COVERING from homeassistant.components.cover import ( ATTR_CURRENT_POSITION, ATTR_POSITION, DOMAIN, SUPPORT_STOP, ) from homeassistant.const import ( ATTR_ENTITY_ID, A...
from email.utils import formatdate from twisted.internet import defer from twisted.internet.error import TimeoutError, DNSLookupError, \ ConnectionRefusedError, ConnectionDone, ConnectError, \ ConnectionLost, TCPTimedOutError from scrapy import signals from scrapy.exceptions import NotConfigured, Ignore...
#!/usr/bin/env python # Test whether a client produces a correct connect with a username and password. # The client should connect to port 1888 with keepalive=60, clean session set, # client id 01-unpwd-set, username set to uname and password set to ;'[08gn=# import inspect import os import subprocess import socket ...
#!/usr/bin/env python import json import os import signal import subprocess import unittest import sys TEST_ROOT = os.path.abspath(os.path.dirname(__file__)) CASPERJS_ROOT = os.path.abspath(os.path.join(TEST_ROOT, '..', '..')) CASPER_EXEC_FILE = sys.argv[1] if (len(sys.argv) == 2) else 'casperjs' CASPER_EXEC = os.pat...
""" Portfolio views. """ from django.template.loader import render_to_string from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_control from lms.djangoapps.courseware.views.views import CourseTabView from util.views import ensure_valid_course_key from web_fragments....
#!/usr/bin/env python """migrateDb.py: Migrate SQLite databases from older version of iAssist.""" __author__ = "Matthias Keller" __copyright__ = "Copyright 2012, Computer Engineering and Networks Laboratory, ETH Zurich" __license__ = "GPL" import sqlite3 from datetime import datetime, timedelta import arg...
"""Tests for the toolchain sub-system""" import sys import os from string import printable from copy import deepcopy from mock import MagicMock, patch from hypothesis import given, settings from hypothesis.strategies import text, lists, fixed_dictionaries, booleans ROOT = os.path.abspath(os.path.join(os.path.dirname(_...
"""A generic class to build line-oriented command interpreters. Interpreters constructed with this class obey the following conventions: 1. End of file on input is processed as the command 'EOF'. 2. A command is parsed out of each line by collecting the prefix composed of characters in the identchars member. 3. A ...
# coding: utf-8 from ..roles import DEFAULT_ROLE from ..resolutionscope import EMPTY_SCOPE from .._compat import OrderedDict from .base import BaseSchemaField from .util import validate, validate_regex __all__ = [ 'StringField', 'BooleanField', 'EmailField', 'IPv4Field', 'DateTimeField', 'UriField', 'NumberFi...
import payment_order # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} import datetime import time try: from zabbix_api import ZabbixAPI HAS_ZABBIX_API = True except ImportError: HAS_ZABBIX_API = False def create_maintenance(zbx, group_ids, host...
""" Helper methods for testing cohorts. """ import factory from factory import post_generation, Sequence from factory.django import DjangoModelFactory import json from opaque_keys.edx.locations import SlashSeparatedCourseKey from xmodule.modulestore.django import modulestore from xmodule.modulestore import ModuleStore...
# -*- coding: utf-8 -*- from django.db.models import Model from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType class ObjectPermissionBackend(object): def has_perm(self, user_obj, perm, obj=None): if user_obj and user_obj.is_superuser: re...
from __future__ import print_function import json import re import sys # Parse lines like this # #,TEST,SAMPLES,MIN(ms),MAX(ms),MEAN(ms),SD(ms),MEDIAN(ms) SCORERE = re.compile(r"(\d+),[ \t]*(\w+),[ \t]*([\d.]+),[ \t]*([\d.]+)") # The Totals line would be parsed like this. TOTALRE = re.compile(r"()(Totals),[ \t]*([\d...
#!/usr/bin/env python #coding:utf-8 import time import re import Queue import ConfigParser import os MQ = Queue.Queue(4096) ALARM_DICT = { 'cpu':'', 'mem':'', 'disk':'', 'inode':'', 'net':'', 'proc':'', 'sec':['',0], 'mysql':'', 'redis':'', 'nginx':'', 'game':'', 'custom':'', 'log':'' } def TIME(): re...
import bpy, os, sys, logging, pickle, mathutils from pprint import pprint from bpy.props import * AXIS_MODES = [ ('xyz', 'xyz', 'no swapping'), ('xz-y', 'xz-y', 'ogre standard'), ('-xzy', '-xzy', 'non standard'), ] CONFIG_PATH = bpy.utils.user_resource('CONFIG', path='scripts', create=True) CONFIG_FILENA...
import os import unittest from test import support spwd = support.import_module('spwd') @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0, 'root privileges required') class TestSpwdRoot(unittest.TestCase): def test_getspall(self): entries = spwd.getspall() se...
import exceptions def main(): module = AnsibleModule( argument_spec = dict( data=dict(required=False, default=None), ), supports_check_mode = True ) result = dict(ping='pong') if module.params['data']: if module.params['data'] == 'crash': raise ex...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.callback.default import CallbackModule as CallbackModule_default from ansible import constants as C import json import os import time import sqlite3 class CallbackModule(CallbackModule_default): # pylint: dis...
import os import random import stat import shutil import logging import deluge.component as component import deluge.configmanager as configmanager from deluge.common import (AUTH_LEVEL_ADMIN, AUTH_LEVEL_NONE, AUTH_LEVEL_NORMAL, AUTH_LEVEL_READONLY, AUTH_LEVEL_DEFAULT, ...
"""The Extended Server Attributes API extension.""" from nova.api.openstack import extensions from nova.api.openstack import wsgi authorize = extensions.soft_extension_authorizer('compute', 'extended_server_attributes') class ExtendedServerAttributesController(wsgi.C...
import os,re,subprocess,os.path,sys,time class RunTestLib: "base class to run cmdline tests" __shared_state = {} def __init__(self): self.__dict__=self.__shared_state if self.__shared_state=={}: self.firstinit() def firstinit(self): self.verbose=True self....
"""Utilities for extracting common archive formats""" import zipfile import tarfile import os import shutil import posixpath import contextlib from distutils.errors import DistutilsError from pkg_resources import ensure_directory __all__ = [ "unpack_archive", "unpack_zipfile", "unpack_tarfile", "default_filter",...
import numpy as np import cv2 import cPickle as pickle import os.path from dpm_classifier import MultiDPMClassifier from ioutils import load_data from features import Feature print "loading data..." # Loads the training and testdata. testdata = load_data( 'data/images/5-fold/0/positives/', 'data/json/boundin...
from unittest import TestCase from .symmath_check import symmath_check class SymmathCheckTest(TestCase): def test_symmath_check_integers(self): number_list = [i for i in range(-100, 100)] self._symmath_check_numbers(number_list) def test_symmath_check_floats(self): number_list = [i + ...
import os from lib.cuckoo.common.abstracts import Report from lib.cuckoo.common.exceptions import CuckooDependencyError from lib.cuckoo.common.exceptions import CuckooReportError from lib.cuckoo.common.objects import File try: from pymongo import MongoClient from pymongo.errors import ConnectionFailure fr...
from time import time from random import choice import string import logging import re from sqlalchemy import or_ import ibid from ibid.compat import hashlib from ibid.db.models import Credential, Permission def hash(password, salt=None): if salt: salt = salt[:8] else: chars = string.letters ...
#!/usr/bin/python # -*- coding: utf-8 -*- import simplejson as json from quixote.errors import TraversalError, AccessError from libs.template import st, stf from webapp.models.group import Group, Thread from webapp.models.card import Card from webapp.views import check_access _q_exports = [] @check_access def _q_lo...
# -*- coding: utf-8 -*- """ Created on Wed Jan 11 17:27:53 2017 @author: richard """ from werkzeug.contrib.cache import (BaseCache, RedisCache, string_types) def rediscluster(app, config, args, kwargs): kwargs.update(dict( host=confi...
from tests.contrib.utils.logging_command_executor import LoggingCommandExecutor BUCKET = "gs://test-display-video-bucket" class GcpDisplayVideoSystemTestHelper(LoggingCommandExecutor): def create_bucket(self): self.execute_cmd(["gsutil", "mb", "gs://{bucket}".format(bucket=BUCKET)]) def delete_bucke...
import unittest import numpy import math from pyscf import gto from pyscf import scf from pyscf import adc mol = gto.Mole() r = 0.957492 x = r * math.sin(104.468205 * math.pi/(2 * 180.0)) y = r * math.cos(104.468205* math.pi/(2 * 180.0)) mol.atom = [ ['O', ( 0., 0. , 0)], ['H', ( 0., -x, y)], ['H', ( 0....
""" Tests for split's copy_from_template method. Currently it is only used for content libraries. However for these tests, we make sure it also works when copying from course to course. """ import ddt from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.exceptions import ItemNotFoundError from xmodu...
import re from org.o3project.odenos.remoteobject.message.response import Response class RequestParser(object): PATTERN = "pattern" METHOD = "method" FUNC = "func" PARAMS = "params" def __init__(self): self.__rules = [] # rule : [{"pattern": "<regex path>", "method": "<method>", ...
import os import time from datetime import datetime import PIL import requests from PIL import Image from flask import current_app as app from geoip import geolite2 from requests import ConnectionError from app.helpers.flask_helpers import get_real_ip from app.helpers.storage import upload, UploadedFile def get_cur...
DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y' SHORT_DATETIME_FORMAT = 'j.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/da...
import collections from io import BytesIO from ansible.modules.web_infrastructure.jenkins_plugin import JenkinsPlugin def pass_function(*args, **kwargs): pass GITHUB_DATA = {"url": u'https://api.github.com/repos/ansible/ansible', "response": b""" { "id": 3638964, "name": "ansible", "full_n...
import types from feat.common import reflect """TODO: Better function mimicry.""" def simple_class(decorator): '''Decorator used to make simple class decorator without arguments. Doesn't really do anything, just here to have a central implementation of the simple class decorator.''' def meta_decora...
from PyQt4 import QtCore class Simbolos(object): def __init__(self, pilas): self.pilas = pilas self.IZQUIERDA = 1 self.DERECHA = 2 self.ARRIBA = 3 self.ABAJO = 4 self.BOTON = 5 self.SELECCION = 6 self.ESPACIO = 32 self.CTRL=17 self....
""" Defines a KernelClient that provides signals and slots. """ from IPython.external.qt import QtCore # Local imports from IPython.utils.traitlets import Bool, DottedObjectName from IPython.kernel import KernelManager from IPython.kernel.restarter import KernelRestarter from .kernel_mixins import QtKernelManagerMi...
# -*- 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 model 'TopicModels' db.create_table(u'mining_topicmodels', ( (u'id', self.gf('django.db...