content
stringlengths
4
20k
#!/usr/bin/env python # -*- coding: utf-8 -*- # Convert times in a large swath of text to a different timezone # See https://github.com/denverpost/wordpress-helpers/issues/1 import sys import argparse import re import string import doctest from datetime import datetime, time, timedelta class Timezoner: """ Convert...
from __future__ import print_function # for Python 3 import sys from numpy import linspace, zeros, sin, pi from pylab import axis, show from tlfem.genmesh import Gen2Dregion, JoinAlongEdge from tlfem.solver import Solver from tlfem.mesh import Mesh def runtest(prob): if prob==1: ...
import json from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.functional import Promise from django.utils.importlib import import_module try: from django.utils.encoding import force_unicode as force_text except ImportError: from django.utils.encoding im...
from twisted.web2.test.test_server import BaseCase, BaseTestResource from twisted.web2 import resource from twisted.web2 import vhost from twisted.web2 import http, responsecode from twisted.web2 import iweb from twisted.web2 import stream from twisted.web2 import http_headers class HostResource(BaseTestResource): ...
"""@file equal_error_rate_from_vecs.py contains the EERFromIvecs class""" import os import numpy as np import scorer import copy import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import random import json class EERFromIvecs(scorer.Scorer): """""" def __init__(self, conf, evalconf, dataconf, s...
import os import re import shutil import pytest from template.test import TestCase, main class CompileTest(TestCase): @pytest.mark.xfail def testCompile(self): dir = os.path.abspath("test") cdir = os.path.join(dir, "tmp", "cache") ttcfg = { "POST_CHOMP": 1, "INCLUDE_PATH": os.path.join...
from MaKaC.plugins.Collaboration.base import WCSPageTemplateBase, WJSBase, WCSCSSBase,\ CollaborationTools from MaKaC.plugins.Collaboration.RecordingRequest.common import \ postingUrgency from MaKaC.conference import Contribution from MaKaC.common.timezoneUtils import isSameDay from MaKaC.common.fossilize impor...
import base64 import os from datetime import datetime, timedelta from ipalib import api, errors from sqlalchemy import Column, DateTime, String, Table from sqlalchemy.sql import delete, select from . import api_connect from ..config import config _password_reset = Table('password_reset', config.metadata, ...
import sys, imp, time, copy import Log, Config def timeDiff(time1, time2): """Returns the difference between the two given datetime or float instances as float with seconds before the comma. """ if time1 > time2: tdelta = time1 - time2 else: tdelta = time2 - time1 if isinstance(tdelta, float): return tdelt...
from django.forms import ValidationError from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from openstack_dashboard.api import cinder from openstack_dashboard.api import keystone class CreateV...
__author__ = 'ggdhines' from penguin import Penguins import numpy import math import scipy project = Penguins() subjects = project.__get_retired_subjects__(1,False) jj = 0 for zooniverse_id in subjects: subject = project.subject_collection.find_one({"zooniverse_id":zooniverse_id}) count = subject["classifica...
#! /usr/bin/env python3 import re from NLP21 import * def read_and_write_section_structure(): lines = read_gz(filename) dictionaries = make_json_dictionaries(lines) structures = get_section_structures(dictionaries) write_section_structures(structures) def get_section_structures(dictionaries): str...
import logging from nose.tools import * # noqa from tests.base import OsfTestCase from website.models import PreprintProvider from website.project.licenses import ensure_licenses from scripts.update_taxonomies import main as taxonomy_main from scripts.populate_preprint_providers import main as populate_main from scr...
#!/usr/bin/env python # Rafael S. Guimaraes # # <EMAIL> # host, port = "localhost", 9999 import os import sys import signal import socket import time import select from SocketServer import TCPServer from SocketServer import StreamRequestHandler class TimeoutException(Exception): pass def read_command(rfile,wfile,p...
from __future__ import print_function, unicode_literals import time import subprocess import traceback _PROCESSES = [] def start_process(popen_args = None, popen_kargs = None): if popen_args is None: popen_args = () if popen_kargs is None: popen_kargs = {} process = subprocess.Popen(*pope...
#! /usr/bin/env python #------------------------------------------------------------# # UDP example to forward data from a local IPv6 DODAG # Antonio Lignan <<EMAIL>> #------------------------------------------------------------# import sys import json import datetime from socket import* from socket import error from ...
import IECore import Gaffer class op( Gaffer.Application ) : def __init__( self ) : Gaffer.Application.__init__( self ) self.parameters().addParameters( [ IECore.StringParameter( name = "op", description = "The name of the op to run.", defaultValue = "" ), IECore.In...
""" This module holds simple classes to convert geospatial values from the database. """ from __future__ import unicode_literals from django.contrib.gis.db.models.fields import GeoSelectFormatMixin from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Area, Distance class Ba...
import argparse, hashlib, os, random, time from subprocess import Popen, PIPE def cmd(s): print s out = Popen(s, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=not isinstance(s, list)) x = out.stdout.read() + out.stderr.read() e = out.wait() return x def all_projects(filename='projects'): return ...
from __future__ import absolute_import import logging import st2common.config as config from st2common.transport.bootstrap_utils import register_exchanges_with_retry def _setup(): config.parse_args() # 2. setup logging. logging.basicConfig( format="%(asctime)s %(levelname)s [-] %(message)s", lev...
import os from collections import OrderedDict from nmt import train from char_biscale import * layers = {'ff': ('param_init_fflayer', 'fflayer'), 'fff': ('param_init_ffflayer', 'ffflayer'), 'gru': ('param_init_gru', 'gru_layer'), 'biscale_decoder': ('param_init_biscale_decoder', ...
import os import sys import base64 import time import requests import ConfigParser APP_DIR = os.path.abspath(os.path.dirname(__file__)) CONFIGFILE = os.path.join(APP_DIR, 'warranty.cfg') CC = ConfigParser.RawConfigParser() # check file if os.path.isfile(CONFIGFILE): CC.readfp(open(CONFIGFILE, "r")) DEBUG = C...
from __future__ import absolute_import from testutil.dott import feature, sh, testtmp # noqa: F401 feature.require(["py2"]) sh % ". '$TESTDIR/hgsql/library.sh'" sh % "initdb" sh % "setconfig 'extensions.treemanifest=!'" # Populate the db with an initial commit sh % "initclient client" sh % "cd client" sh % "ech...
import numpy as np class HilbertCurves(object): def __init__(self, xi, yj, level=10): self.xi = xi self.yj = yj self.data = np.zeros((xi, yj)) self.edges = [] self.level = level def make_line(self, X, Y): if self.edges: i, j = self.edges[-1] xstart = int(min(i, X)) xend = int(max(i, X)) yst...
import copy import logging import os.path import yaml import gen import ssh.validate from gen.build_deploy.bash import onprem_source from gen.exceptions import ValidationError from pkgpanda.util import load_yaml, write_string, YamlParseError log = logging.getLogger(__name__) config_sample = """ --- # The name of yo...
""" This is the default settings files for all production servers. Before importing this settings file the following MUST be defined in the environment: * SERVICE_VARIANT - can be either "lms" or "cms" * CONFIG_ROOT - the directory where the application yaml config files are located """ # ...
# -*- coding: utf-8 -*- from ast import literal_eval from Plugins.Extensions.MediaPortal.plugin import _ from Plugins.Extensions.MediaPortal.resources.imports import * from Plugins.Extensions.MediaPortal.resources.twagenthelper import twAgentGetPage HTV_Version = "heiseVIDEO" HTV_siteEncoding = 'utf-8' class HeiseT...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from os.path import abspath, relpath import sphinx.environment def _warn_node(func): def wrapper(self, msg, node): if not msg.startswith('nonlocal image URI found:'): return func(self, msg, node) return wrapper sphinx.environmen...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import pyhipku try: import pypandoc long_description = pypandoc.convert('README.md','rst') except (IOError, ImportError): with open('README.md') as f: long_description = f.read() setup( name='pyhipku', version=p...
from terralib.pixelgrid import * import math import copy import queue pixelgrid = None quickdraw = None redraw = None undostack = [] def initialize(grid, quick, re): global pixelgrid pixelgrid = grid global quickdraw quickdraw = quick global redraw redraw = re global undostack undo...
from __future__ import (absolute_import, division, print_function) import numpy as np from numpy.testing import assert_almost_equal, assert_array_almost_equal import cartopy.crs as ccrs from .helpers import check_proj_params class TestAzimuthalEquidistant(object): def test_default(self): aeqd = ccrs.Azi...
#!/usr/bin/python3 import requests import argparse import sys def err(msg, *args): print('error:', msg % args, file = sys.stderr) token = open('token').read().strip() URL = 'https://api.github.com/repos/{owner}/{repo}/hooks?access_token=' + token events = [ '*', 'commit_comment', 'create', 'delete', 'deplo...
# -*- coding: utf-8 -*- from __future__ import absolute_import import sys import logging import inspect import pkgutil logger = logging.getLogger(__name__) class IntrospectionHelper(object): """ This is a helper class for performing introspection. """ # Class Members # Instantiation # Sta...
DEBUG = True SESSION_LIMIT = 5 COOKIE_DURATION = 30 MAIN_URL_ROOT = 'https://saylua.com' IMAGE_BUCKET_ROOT = 'https://storage.googleapis.com/saylua-images' IMAGE_BUCKET_NAME = '/saylua-images' THEME_CLASSES = ['theme-sayleus', 'theme-luaria'] # Form fields MIN_USERNAME_LENGTH = 3 MAX_USERNAME_LENGTH = 15 MIN_PASSWOR...
from collections import deque import logging from operator import itemgetter from twisted.internet import protocol from twisted.python import failure from twimp import vecbuf LOG_CATEGORY = 'utils' import twimp.log log = twimp.log.get_logger(LOG_CATEGORY) def ms_time(t): "Convert time t from (real) seconds to ...
"""Perform streaming post-alignment preparation -- de-duplication and sorting. Centralizes a pipelined approach to generating sorted, de-duplicated BAM output from sequencer results. samblaster: http://arxiv.org/pdf/1403.7486v1.pdf biobambam bammarkduplicates: http://arxiv.org/abs/1306.0836 """ import contextlib impo...
"""General settings container. The behaviour of the XMPP implementation may be controlled by many, many parameters, like addresses, authetication methods, TLS settings, keep alive, etc. Those need to be passed from one component to other and passing it directly via function parameters would only mess up the API. Inst...
import bpy from math import sqrt, cos, sin from fashion_project.modules.draw.counter import Counter from fashion_project.modules.draw.base import Base from fashion_project.modules.draw.points.point import Point from fashion_project.modules.draw.lines.line import Line from fashion_project.modules.draw.points import is...
"""Command for adding project-wide metadata.""" from googlecloudsdk.api_lib.compute import base_classes class AddMetadata(base_classes.ProjectMetadataMutatorMixin, base_classes.BaseMetadataAdder): """Add or update project-wide metadata.""" @staticmethod def Args(parser): base_classes.Bas...
import re import CTK import Wizard from util import * from configured import * NOTE_WELCOME_H1 = N_("Welcome to the Icons Wizard") NOTE_WELCOME_P1 = N_("This wizard adds the /icons and /cherokee_themes directories so Cherokee can use icons when listing directories.") NOTE_WELCOME_ERR= N_("The /icons and /cherokee_them...
from yowsup.layers import YowParallelLayer import asyncore, time, logging from yowsup.layers import YowLayer from yowsup.layers.auth import YowCryptLayer, YowAuthenticationProtocolLayer from yowsup.layers.coder import YowCoderLayer from yowsup.layers.logger ...
''' COPYRIGHT 2010 RPS ASA This file is part of SCI-WMS. SCI-WMS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SCI-W...
"""Sensor platform for the PoolSense sensor.""" import logging from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_EMAIL, DEVICE_CLASS_BATTERY, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TIMESTAMP, STATE_OK, STATE_PROBLEM, TEMP_CELSIUS, UNIT_PERCENTAGE, ) from homeassistant.helpers...
"""Measurements for OpenHTF. Measurements in OpenHTF are used to represent values collected during a Test. They can be numeric or string values, and can be configured such that the OpenHTF framework will automatically check them against Pass/Fail criteria. Measurements should not be used for large binary blobs, which ...
''' Created on May 21, 2015 @author: mucx ''' from __future__ import division from abc import ABCMeta, abstractmethod from renderer import Renderer class MapRenderer(Renderer): ''' An abstract metaclass that handles the map rendering ''' __metaclass__ = ABCMeta @abstractmethod def __init__(...
# coding: utf-8 import ConfigParser, sys def config_section_map(section, config): dict1 = {} options = config.options(section) for option in options: try: dict1[option] = config.get(section, option) except: dict1[option] = None return dict1 def variable_definiti...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import sys from datetime import datetime from os import path import constant import func from lang import LANG from models import AFAddressBook, AFUserAccount, ArchiveOut argc = len(sys.argv) if argc < 3: sys.exit("Usage: {0} qfile why jobtime [...
from typing import cast, List, Union from graphql.error import GraphQLError, print_error from graphql.language import ( parse, OperationDefinitionNode, ObjectTypeDefinitionNode, Source, ) from ..utils import dedent source = Source( dedent( """ { field } """ ) ) ast...
""" This module provides BulkRouter that extends the registered ViewSets with bulk operations if they are not provided yet. To display documentation in the browsable API, it is necessary to provide a method `bulk_op` (where `op` is any of `update`, `partial_update`, `destroy`) on the viewset which calls `pdc.apps.comm...
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'Vasiliy Ermilov, e-mail: <EMAIL>, telegram: inkz1' import re, hashlib, logging, logging.handlers, logging.config, os.path from tqdm import * from Database import SqlDataBase from Filereader import File from sys import argv, exit, stdout from RegExpressionsLib im...
"""RunAbove flavor service library.""" from base import Resource, BaseManagerWithList from .exception import ResourceNotFoundError class FlavorManager(BaseManagerWithList): """Manage flavors available in RunAbove.""" basepath = '/flavor' def _dict_to_obj(self, flavor): """Converts a dict to a F...
from typing import Any, Dict, Union from packed import packable from ...requests import Request from ...resolvers import Resolver from ..attribute_matchers import AttributeMatcher, DictOrTupleList, MultiDictMatcher from ._request_matcher import RequestMatcher __all__ = ("ParamMatcher", "DictOrTupleListOrAttrMatcher"...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as stream: long_desc = stream.read() requires = ['Sphinx>=0.6', 'pyparsing'] setup( name='sphinxcontrib-doxylink', version='1.3', url='http://packages.python.org/sphinxcontrib-doxylink', download_url='http:/...
import facebook from . import FacebookTestCase class FacebookAPIVersionTestCase(FacebookTestCase): """Test if using the correct version of Graph API.""" def test_no_version(self): graph = facebook.GraphAPI() self.assertNotEqual(graph.version, None, "Version should not be None.") self....
'''Arakoon administrative call implementations''' import operator from pyrakoon import errors, protocol, utils class OptimizeDB(protocol.Message): '''"optimize_db" message''' __slots__ = () TAG = 0x0025 | protocol.Message.MASK ARGS = () RETURN_TYPE = protocol.UNIT DOC = utils.format_doc(''...
import simplejson, sys, shutil, os, ast , re from mpipe import OrderedStage , Pipeline import glob, json, uuid, logging , time ,datetime import subprocess, threading,traceback from collections import OrderedDict from pprint import pprint , pformat import parallel_tools as parallel from mpipe import OrderedStage , Pip...
import unittest from datetime import datetime from tests.models_t.attachment_base.util import GenericAttachment class AttachmentToDictTest(unittest.TestCase): def test_fields_none_exports_all(self): # given task = object() att = GenericAttachment('/path/to/file', 'desc', datetime(2018, 1...
#!/usr/bin/env python # # WS-I interoperability test http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools # latest download: http://www.ws-i.org/Testing/Tools/2005/06/WSI_Test_Java_Final_1.1.zip # # Before launching this test, you should download the zip file and unpack it in this # directory this should ...
""" Netperf is a benchmark that can be used to measure the performance of many different types of networking. It provides tests for both unidirectional throughput, and end-to-end latency. """ import os import netifaces from avocado import Test from avocado.utils.software_manager import SoftwareManager from avocado.ut...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Evaluation.activity' db.delete_column(u'activities_eval...
import re import string def punctuation_rm(string_value): tmp_value = ( re.sub('[%s]' % re.escape(string.punctuation), '', string_value or '')) return tmp_value
""" Plugin loading system for having custom behaviour of custom hardware for printers Author: Mathieu Monney email: zittix(at)xwaves(dot)net License: GNU GPL v3: http://www.gnu.org/copyleft/gpl.html Redeem is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ...
# coding: utf-8 import unittest from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.util.testing import PymatgenTest from pymatgen.util.coord import in_coord_list from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.analysis.wulff import WulffShape ...
import superdesk from superdesk import get_backend, get_resource_service from superdesk.resource import Resource from superdesk.services import BaseService _preferences_key = 'global_preferences' def init_app(app): endpoint_name = _preferences_key service = GlobalPreferencesService(endpoint_name, backend=get...
import time from amqpstorm.exception import AMQPConnectionError from amqpstorm.heartbeat import Heartbeat from amqpstorm.tests.utility import TestFramework from amqpstorm.tests.utility import fake_function class HeartbeatTests(TestFramework): def test_heartbeat_start(self): heartbeat = Heartbeat(60, fake...
from pixelated.adapter.soledad.soledad_facade_mixin import SoledadDbFacadeMixin from twisted.internet import defer class SoledadWriterMixin(SoledadDbFacadeMixin, object): @defer.inlineCallbacks def mark_all_as_not_recent(self): for mailbox in ['INBOX', 'DRAFTS', 'SENT', 'TRASH']: rct = y...
import functools import pipes import sys; sys.path += ['/var/canvas/common', '../../common'] import time from datetime import datetime from fabric.api import * import ec2 from configuration import Config conn = ec2.connection() running = {'instance-state-name': 'running', 'tag:CanvasStatus': 'bootstrapped'} def ...
import sys import mosek # If numpy is installed, use that, otherwise use the # Mosek's array module. try: from numpy import array,zeros,ones except ImportError: from mosek.array import array, zeros, ones # Since the actual value of Infinity is ignores, we define it solely # for symbolic purposes: inf = 0.0 ...
from strato.racktest.infra.seed import memorycache from strato.racktest.infra.seed import filecache from strato.racktest.infra.seed import cacheregistry class FileBackedByMemory(filecache.FileCache): def __init__(self, cacheDir): filecache.FileCache.__init__(self, cacheDir) self._memoryCache = me...
import os from unittest import TestCase from unittest.mock import patch from RatS.plex.plex_ratings_inserter import PlexRatingsInserter TESTDATA_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'assets')) class PlexRatingsInserterTest(TestCase): def setUp(self): if no...
from __future__ import print_function import time, sys, signal, atexit from upm import pyupm_gas as upmGas def main(): # Attach gas sensor to AIO0 myMQ5 = upmGas.MQ5(0) ## Exit handlers ## # This function stops python from printing a stacktrace when you hit control-C def SIGINTHandler(signum, fram...
"""ICU dependency tester. This probably works only on Linux. The exit code is 0 if everything is fine, 1 for errors, 2 for only warnings. Sample invocation with an in-source build: ~/icu/icu4c/source/test/depstest$ ./depstest.py ../../ Sample invocation with an out-of-source build: ~/icu/icu4c/source/test/depst...
#!/usr/bin/env python # coding=utf-8 """ Copyright 2012 Load Impact Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable la...
# -*- coding:utf-8 -*- """Test views.""" from ..forms import RegisterForm, CreateUserForm from ..views import login_view, register_view, create_user_view, delete_user_view, view_users_view, logout_view, user_detail_view import pytest from webob.multidict import MultiDict from ..models import User # Test login/logout...
from pyrocko import gf from pyrocko import model, util from pyrocko import orthodrome as otd from pyrocko import moment_tensor as mt from pyrocko import trace from beat.sources import RectangularSource from beat import ffi, models import numpy as num from beat import inputf, utility, heart, config import os km = 1000...
import contextlib import logging import teuthology.lock.ops import teuthology.lock.query import teuthology.lock.util from teuthology.job_status import get_status log = logging.getLogger(__name__) @contextlib.contextmanager def lock_machines(ctx, config): """ Lock machines. Called when the teuthology run fi...
# -*- coding: utf-8 -*- """ Several useful template tags! """ import re from django import template from django.template import TemplateSyntaxError, Node, loader, Variable from django.template.defaultfilters import stringfilter from django.utils.html import strip_tags from django.utils.safestring import mark_safe fro...
#!/usr/bin/python3 # Included code from flask import Flask from flask import render_template from flask import request from flask import redirect from flask import url_for from flask import session from flask import flash import bcrypt import sqlite3 # Define the flask application app = Flask(__name__) # The SQL con...
from django.shortcuts import render from django.http import HttpResponse from .models import Aparcamiento, Usuario, Fecha, Comentario from django.views.decorators.csrf import csrf_exempt from django.core.exceptions import ObjectDoesNotExist import datetime from django.shortcuts import redirect from django.template.load...
''' Test the following services - getAccountFunds - transferFunds ''' import sys import bfpy import bfpy.bfclient as bfclient print 'Creating a Betfair Client' bf = bfclient.BfClient() print 'Created a Betfair Client' loginInfo = sys.modules['__main__'].loginInfo response = bf.login(**loginInfo) print response...
import webapp2 import posts import pics from google.appengine.api import search from google.appengine.api import users #Handlers search request for cards #Cards can be of many types #Cards will be returned sperated by commas. <type>:<name> class Search(webapp2.RequestHandler): def post(self): # Get the s...
import unittest import collections from datetime import datetime, timedelta from ..stock import Stock, StockSignal class StockTest(unittest.TestCase): def setUp(self): self.goog = Stock("GOOG") def test_price_of_a_new_stock_class_should_be_None(self): self.assertIsNone(self.goog.price) ...
FT_STYLE_FLAG_ITALIC = (1 << 0) FT_STYLE_FLAG_BOLD = (1 << 1) FT_FACE_FLAG_SFNT = (1 << 3) FT_FACE_FLAG_FIXED_SIZES = (1 << 1) FT_FACE_FLAG_FIXED_WIDTH = (1 << 2) FT_STYLE_ITALIC = 'italic' FT_STYLE_BOLD = 'bold' FT_STYLE_NORMAL = 'normal' NID_COPYRIGHT = 0 NID_FONT_FAMILY = 1 NID_FONT_SUBFAM = 2 NID_UNIQUE_ID = 3 NI...
from django import forms from django.utils.safestring import mark_safe from .models import Senator, ContactList def getContactListChoices(): def c2t(c): return mark_safe( "<strong><a href=\"./?lists=%s\">%s</a></strong><br/>"\ "<em>%s</em><br/>"\ "Senators: %s<br/><br/>"...
#!/usr/bin/env python import logging import struct class TCPFormat(object): logger = logging.getLogger("pipboy.TCPFormat") @staticmethod def __load_bool(stream): (val,) = struct.unpack("<B", stream.read(1)) val = [False, True][val] return val @staticmethod def __load_nat...
from openstack.tests.unit import base from openstack.identity.v3 import region IDENTIFIER = 'RegionOne' EXAMPLE = { 'description': '1', 'id': IDENTIFIER, 'links': {'self': 'http://example.com/region1'}, 'parent_region_id': 'FAKE_PARENT', } class TestRegion(base.TestCase): def test_basic(self): ...
#!/usr/bin/env python # -*- coding: utf-8; mode: python; -*- ################################################################## # Imports from __future__ import absolute_import from dsenser.nnbase import _norm_vec, _norm_word, NNBaseSenser, DFLT_VDIM from dsenser.constants import CONNECTIVE, WORDS, SENTENCES, RAW_TEX...
# coding: utf-8 from __future__ import absolute_import from flask.ext import restful from google.appengine.api import images from google.appengine.ext import blobstore from google.appengine.ext import ndb import flask import werkzeug from api import helpers import auth import config import model import util from ma...
import stix import stix.utils from stix.utils import dates import stix.bindings.ttp as ttp_binding from stix.common import StructuredText, VocabString, InformationSource, Statement from stix.common.vocabs import IntendedEffect from stix.data_marking import Marking from .behavior import Behavior from .resource import Re...
# coding: utf-8 from django.db import models from shortuuid import ShortUUID # should be 22 per shortuuid documentation, but keeping at 21 to avoid having # to migrate dkobo (see SurveyDraft.kpi_asset_uid) UUID_LENGTH = 21 class KpiUidField(models.CharField): """ If empty, automatically populates itself wit...
# -*- coding: utf-8 -*- from datetime import date, datetime, timedelta from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.gis.geos import Point from django.http import HttpResponseForbidden from django.shortcuts import get_...
import traceback import json from ansible.module_utils._text import to_text, to_native from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import env_fallback from ansible.module_utils.connection import Connection, ConnectionError from ansible.module_utils.network.common.netconf import...
# -*- coding: utf-8 -*- # public api to export __all__ = [ 'uuid', 'random_string', 'secure_random_hex', 'roman_range', ] import binascii import os import random import string from typing import Generator from uuid import uuid4 from .manipulation import roman_encode def uuid(as_hex: bool = False) -...
''' This module contains tools for representing "LG + D" (linear Gaussian and discrete) nodes -- those with a Gaussian distribution, zero or more Gaussian parents, and one or more discrete parents -- as class instances with their own *choose* method to choose an outcome for themselves based on parent outcomes. ''' imp...
""" STABLE. """ import logging from gi.repository import GObject from gi.repository import Gtk from sugar3.graphics.icon import Icon from sugar3.graphics.palette import Palette, ToolInvoker def _add_accelerator(tool_button): if not tool_button.props.accelerator or not tool_button.get_toplevel() or \ ...
POKEMON = ( 'Egg', 'Bulbasaur', 'Ivysaur', 'Venusaur', 'Charmander', 'Charmeleon', 'Charizard', 'Squirtle', 'Wartortle', 'Blastoise', 'Caterpie', 'Metapod', 'Butterfree', 'Weedle', 'Kakuna', 'Beedrill', 'Pidgey', 'Pidgeotto', 'Pidgeot', 'Ra...
from functools import reduce # declaración de funciones def contar ( l ) : p = { } for x in l : p.setdefault ( x , 0 ) p[ x ] += 1 return p def contar2 ( l , k ) : p = { } for i in range ( len ( l ) ) : p.setdefault ( k [ i ] , { } ) p [k[i]] . setdefault (l[i] , 0 ) p [k[i]] [l[i]] += 1 r...
import os import time from datetime import datetime, date, timedelta import math import mock from hiro import Timeline from hiro.utils import timedelta_to_seconds from tests.emulated_modules import sample_1, sample_2, sample_3 import pytest def test_accelerate(): s = time.time() with Timeline(100): t...
""" Copyright 2016 Brocade Communications Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
'''@file lstm_reconstructor.py contains the LstmReconstructor class''' import tensorflow as tf from nabu.neuralnetworks.classifiers.asr.reconstructors import reconstructor class LstmFeatureReconstructor(reconstructor.Reconstructor): ''' A reconstructor that reconstructs the input features with an lstm chain.'...