content
string
import datetime from nose.plugins.attrib import attr from nose.tools import eq_, assert_raises from socorro.external import MissingArgumentError, BadArgumentError from socorro.external.postgresql.signature_urls import SignatureURLs from socorro.lib import datetimeutil from .unittestbase import PostgreSQLTestCase #=...
#!/usr/bin/env python import sys,os filesvg=sys.argv[1] filehtml='temp.html' filepng=filesvg[:-4]+'.png' F=open(filesvg,'r') FF=F.readlines() F.close() New=FF[0][:FF[0].find('><')]+' style=\"background: #333\">\n' ww=('').join(New.split()); ww=ww.split('width=\"')[1] ww=ww[:ww.find('\"')] print ww hh=('').join(Ne...
from base64 import standard_b64encode import httplib import xmlrpclib import headphones from headphones import logger def sendNZB(nzb): addToTop = False nzbgetXMLrpc = "%(protocol)s://%(username)s:%(password)s@%(host)s/xmlrpc" if not headphones.CONFIG.NZBGET_HOST: logger.error(u"No NZBget host f...
XXXXXXXXX XXXXX XXXX XXXXXXXXX XXX XXXXXXXXXX XXXXXXXX X XXXXXXXXX XXXXXXXX XXX XXXXXX XXXXXXXXX XXX XXXXXXXXXX XXX XXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXX XXXXXXXXXXXXX XXXXXXX XXXXXXXX XXXXXXXXXXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX...
from ..frame import H2OFrame import urllib class TransformAttributeError(AttributeError): def __init__(self,obj,method): super(AttributeError, self).__init__("No {} method for {}".format(method,obj.__class__.__name__)) class H2OTransformer(object): """H2O Transforms H2O Transforms implement the following ...
from xml.dom import minidom import pywikibot from api.decorator import time_this SiteMock = pywikibot.Site class PageMock(pywikibot.Page): def __init__(self, *args, **kwargs): super(PageMock, self).__init__(*args, **kwargs) self.filename = "test_data/test_pages_%s.xml" % self.site.lang ...
#!/usr/bin/python # -*- coding: utf-8 -*- import os from PyQt5.QtCore import ( Qt, QRect, QUrl, pyqtProperty, QObject, pyqtSlot, pyqtSignal, QThread, QPointF) from PyQt5.QtGui import QKeySequence from PyQt5.QtWidgets import QSystemTrayIcon from PyQt5.QtQuick import QQuickView from .basewindow import B...
import fauxfactory import pytest from Crypto.PublicKey import RSA from cfme.cloud.keypairs import KeyPair from cfme.cloud.provider.openstack import OpenStackProvider from cfme.exceptions import KeyPairNotFound from cfme.web_ui import mixins from utils import testgen from utils.blockers import BZ from utils.appliance.i...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './Plugins/VcsPlugins/vcsMercurial/ShelveExtension/HgShelveBrowserDialog.ui' # # by: PyQt5 UI code generator 5.3.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_HgShelveBro...
'''Test cases for QLineF''' import unittest import datetime from PySide2.QtCore import QTime, QDateTime, QDate class TestDateTimeConversions (unittest.TestCase): def testQDate(self): date = datetime.date(2010, 4, 23) other = QDate(date) self.assertEqual(date.year, other.year()) se...
from ufo2ft.filters.decomposeTransformedComponents import ( DecomposeTransformedComponentsFilter, ) class DecomposeTransformedComponentsFilterTest: def test_transformed_components(self, FontClass): ufo = FontClass() a = ufo.newGlyph("six.lf") a.width = 300 pen = a.getPen() ...
from .. import axis import numpy as np from nose.tools import assert_raises from .test_io import check_rewrite rand_affine = np.random.randn(4, 4) vol_shape = (5, 10, 3) def brain_models(): mask = np.zeros(vol_shape) mask[0, 1, 2] = 1 mask[0, 4, 2] = True mask[0, 4, 0] = True yield axis.BrainMod...
#!/usr/bin/env python import argparse import data_handling.midi as midi def main(): """ Illustrate some functionality of the midi module """ parser = argparse.ArgumentParser("Get information from a MIDI file") parser.add_argument("infile", help="Midi file to read") parser.add_argument("--out...
# -*- coding: utf-8 -*- import os import shutil basepath = "/home/andrew/VOC2012/" respath = "/home/andrew/VOC-CLS/" directory = basepath + "ImageSets/Main/" imagedir = basepath + "JPEGImages/" files = os.listdir(directory) def parseLine(file): outimg = respath + "/" + file.replace("_trainval.txt",""+"/") t...
""" Copyright (C) 2015 @author: Cedrick FAURY """ from bs4 import BeautifulSoup import urllib2 import webbrowser import wx __appname__= "pyXorga" __author__ = u"Cédrick FAURY" __version__ = "2.2" print __version__ ############################################################################################### def ...
class BaseSpatialOperations: """ This module holds the base `BaseSpatialBackend` object, which is instantiated by each spatial database backend with the features it has. """ truncate_params = {} # Quick booleans for the type of this spatial backend, and # an attribute for the spatial da...
import IMP import os import IMP.test import IMP.pmi.restraints.stereochemistry import IMP.pmi.representation import IMP.pmi.tools import IMP.pmi.output class Tests(IMP.test.TestCase): def test_hierarchy_construction(self): """Test construction of a hierarchy""" # input parameter pdbfile =...
""" Proposal Target Operator selects foreground and background roi and assigns label, bbox_transform to them. """ from __future__ import print_function import mxnet as mx import numpy as np from distutils.util import strtobool from rcnn.io.rcnn import sample_rois DEBUG = False class ProposalTargetOperator(mx.opera...
import json from django.contrib.auth.decorators import permission_required from django.core.paginator import EmptyPage from django.core.paginator import Paginator from django.db.models import Q from django.http import HttpResponse from django.template.loader import render_to_string from django.utils.translation import...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Location.respondant' db.add_column(u'survey_location', 'respondant', s...
import json from django.core.paginator import Paginator from django.core.urlresolvers import reverse from django.http import HttpResponse from django.views.generic import View from .models import Data class FormApi(View): def post(self, request, **kwargs): request_data = json.loads(request.body.decode()) ...
import pytest try: from http.server import SimpleHTTPRequestHandler, HTTPServer except ImportError: # Python 2 from SimpleHTTPServer import SimpleHTTPRequestHandler from BaseHTTPServer import HTTPServer import os import ssl from multiprocessing import Process import urllib3 from requests.exceptions impo...
#!/usr/bin/env python #$Id: main.py 4 2009-09-06 17:57:10Z lkalif $ import service import webapp2 from google.appengine.ext import db from google.appengine.ext.webapp import template from uuid import uuid4 class UrlHandler(webapp2.RequestHandler): def get(self): self.response.out.write( ...
"""Declarations of all important constants related to physical IOTile devices.""" from inspect import getmembers from iotile.sg import DataStream from .errors import Error, ConfigDatabaseError, SensorLogError, SensorGraphError from . import rpcs from . import streams from .const_tilemanager import RunLevel, TileState ...
# encoding: UTF-8 # 重载sys模块,设置默认字符串编码方式为utf8 import sys reload(sys) sys.setdefaultencoding('utf8') # vn.trader模块 from vnpy.event import EventEngine from vnpy.trader.vtEngine import MainEngine from vnpy.trader.uiQt import qApp from vnpy.trader.uiMainWindow import MainWindow # 加载底层接口 from vnpy.trader.gateway import (c...
""" Create a FAISS Index with a series of dense embeddings. """ import os import random import torch from typing import List from parlai.core.params import ParlaiParser from parlai.core.script import ParlaiScript import parlai.utils.logging as logging from parlai.agents.rag.rag import RagAgent from parlai.agents.rag....
from django.contrib import admin from eventkit_cloud.user_requests.models import ( DataProviderRequest, SizeIncreaseRequest, UserSizeRule, ) class DataProviderRequestAdmin(admin.ModelAdmin): list_display = [ "uid", "status", "user", "name", "url", "serv...
#!/usr/bin/python # -*- coding: utf-8 -*- def forObj(obj): return DictConfigParser(obj) class DictConfigParser: def __init__( self, obj, isCaseSensitive=True, removeChars=None, isLongestTokenMatch=False, ): self.obj = obj self.options = [] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ make_presentations_table.py Makes the presentation entries for the MoEDAL section. See the README.md file for more information. http://researchinschools.org """ #...for the Operating System stuff. import os #...for parsing the arguments. import argparse #.....
""" Django settings for APyCON project. <<<<<<< HEAD Generated by 'django-admin startproject' using Django 1.11.4. ======= Generated by 'django-admin startproject' using Django 1.11.5. >>>>>>> 83254272d633b05cc9d36b197eba4b0a21beebaa For more information on this file, see https://docs.djangoproject.com/en/1.11/topics...
"""MAAS OAuth API connection library.""" __all__ = ["MAASClient", "MAASDispatcher", "MAASOAuth"] from collections.abc import Sequence import gzip from io import BytesIO import random import time import urllib.error import urllib.parse import urllib.request from oauthlib import oauth1 from apiclient.encode_json impo...
import signal import sys import traceback try: import PyQt5 except Exception: sys.exit("Error: Could not import PyQt5 on Linux systems, you may try 'sudo apt-get install python3-pyqt5'") from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import PyQt5.QtCore as QtCore from ele...
import os # Several module level utility functions def get_segment_signature(vid, fstart, fend): """ Generating video clip signature string """ return '{}-{:04d}-{:04d}'.format(vid, fstart, fend) def get_feature_path(name, vid): """ Path to save intermediate object trajectory proposals and f...
import socket,time from config import conf from data import * class _SuperSocket_metaclass(type): def __repr__(self): if self.desc is not None: return "<%s: %s>" % (self.__name__,self.desc) else: return "<%s>" % self.__name__ class SuperSocket: __metaclass__ = _SuperSo...
__all__ = ( "CSVConverter", ) import csv import sys from os.path import expanduser from .zanatalib.logger import Logger try: import json except ImportError: import simplejson as json class CSVConverter: def __init__(self): self.log = Logger() def read_data(self, csv_file): data...
import collections import json as jsonlib import random import re from operator import attrgetter from urlparse import urljoin from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.forms import CheckboxInput from django.utils import translation from django.utils.encoding im...
#! /usr/bin/env python3 import uuid import os import argparse import boto3 import botocore boto3_session = boto3.Session(profile_name='serverless-meow') client = boto3_session.client('s3') BUCKET = os.getenv('BUCKET_NAME') REGION = 'us-east-2' def upload_photo(photo_path): try: client.head_object(Bucke...
from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils import importlib from django.utils.translation import get_language_info import pytz from appconf import AppConf def load_path_attr(path): i = path.rfind(".") mo...
#!/usr/bin/env python """TODO: place all consensus methods here load_consensus_map make_consensus_tree etc... """ from t2t.nlevel import RANK_ORDER from numpy import zeros, where, logical_or, long def taxa_score(master, reps): """Score taxa strings by contradictions observed in reps""" n_ranks = len(RANK_OR...
#import asyncio import re import operator from collections import defaultdict from cloudbot import hook #from cloudbot.util import timesince from cloudbot.event import EventType karmaplus_re = re.compile('^.*\+\+$') karmaminus_re = re.compile('^.*\-\-$') db_ready = [] def db_init(db, conn_name): """Check to see ...
#!/usr/bin/env python """VectorAddition example data_out[i] = in_a[i] + in_b[i] + scalar""" import sys import time import random sys.path.append('../gen-py') from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from com.max...
#!/usr/bin/python # -*- coding: utf-8 -*- from cow.server import Server from cow.plugins.sqlalchemy_plugin import SQLAlchemyPlugin from cow.plugins.redis_plugin import RedisPlugin from tornado.httpclient import AsyncHTTPClient import tornado.locale import redis from materialgirl import Materializer from materialgirl.s...
"""Parametric distributions over action spaces.""" import abc from typing import Callable import dataclasses import gym import tensorflow as tf import tensorflow_probability as tfp from tensorflow_probability.python.distributions import kullback_leibler tfb = tfp.bijectors tfd = tfp.distributions class ParametricD...
"""Defines reference model patch to save given power after IAP. Usage: Simply import that module. """ # TODO: integrate these changes officially in the reference model, as they # are useful in general for a bunch of studies. # A few reference model data/routines are changed in common/data.py and # iap/iap.py ...
import os import xml.etree.ElementTree as ET class RenderProcessFileWriter: def __init__(self,pipelineSpecs, jobGenModules): self.cF = jobGenModules["commonFunctions"] self.iH = jobGenModules["importHelpers"] self.pipelineSpecs = pipelineSpecs def write(self,p...
from __future__ import division import sys import argparse import textwrap import micca.api def main(argv): prog = "micca classify" description = textwrap.dedent('''\ micca classify assigns taxonomy for each sequence in the input file and provides three methods for classification: ...
""" LICENCE ------- Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. See the associated README.rst file in this directory for background. """ from .VCDStoreElemen...
# Standard library import unittest from collections import Counter, defaultdict from multiprocessing import Pool # External libraries import numpy as np import matplotlib.pyplot as plt class Record: 'The aim of this class is to hide the representation of labels and' 'records from the random forest building a...
#!/usr/bin/python # -*- coding: utf-8 -*- """ flight_warning.py version 1.07 This program will send a Google mail message when an ADS-B data feed from a dump1090 stream detects an aircraft within a set distance of a geographic point. It will also send an email when the aircraft leaves that detection area. As well, it...
#!/usr/bin/env python3 import sys import argparse from syntcomp.syntcomp_constants import UNKNOWN_RC, UNREALIZABLE_RC, \ REALIZABLE_RC from tests.common import run_benchmark realizable = [ ("others/count1.ltl --moore", 2), ("others/count2.ltl --moore", 3), ("others/full_arbiter2.ltl --moore", 4), ...
import threading from direccion import Directions import pygame import itertools class Car(threading.Thread, pygame.sprite.Sprite): """docstring for Vehiculo""" def __init__(self,posicionX,posicionY,direction): super(Car, self).__init__() self.direction = direction self.car_path = "Images/car-" s...
""" Copyright (c) 2017, Battelle Memorial Institute 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 copyright notice, this list of conditions a...
''' Copyright (c) 2020 Yogesh Khatri This file is part of mac_apt (macOS Artifact Parsing Tool). Usage or distribution of this software/code is subject to the terms of the MIT License. documentrevisions.py --------------- Reads the DocumentRevisions database. The database contains information ...
"""This script is used to synthesize generated parts of this library.""" import synthtool as s import synthtool.gcp as gcp import synthtool.languages.ruby as ruby import logging import re logging.basicConfig(level=logging.DEBUG) gapic = gcp.GAPICGenerator() v1_library = gapic.ruby_library( 'dataproc', 'v1', con...
#!/usr/bin/python # Mirrors hudson build results (but not build details) from one hudson # instance to another. Similar to http://wiki.hudson-ci.org/display/HUDSON/Build+Publisher+Plugin , # except that it doesn't require that the publishing hudson be able to talk # directly to the subscribing one. # # Specifically, ...
"""WebSearch Flask Blueprint.""" from __future__ import unicode_literals import cStringIO from functools import wraps from flask import Blueprint, abort, current_app, flash, g, redirect, \ render_template, request, send_file, url_for from flask_breadcrumbs import default_breadcrumb_root from flask_login import...
 from System import Array, Byte from System.Net import HttpListener from System.IO import Path, FileStream, FileMode, File root = "c:/apache-tomcat-6.0.18/webapps/docs" bytes = Array.CreateInstance(Byte,1024) listener = HttpListener() listener.Prefixes.Add("http://*:8000/") def process(context): f...
""" Current report API endpoints """ # pylint: disable=missing-class-docstring,too-many-ancestors import avwx_api.handle.current as handle from avwx_api import app, structs, validate from avwx_api.api.base import Report, Parse, MultiReport ## METAR @app.route("/api/metar/<station>") class MetarFetch(Report): ...
# coding: utf-8 from datetime import datetime from fabric.api import settings, require from fabric.tasks import Task from cuisine import MODE_SUDO class Project(dict): """ Describes the remote directory structure for a project. """ def __init__(self, project, instance, user=None, basedir=None, package...
from unnaturalcode.ucUtil import * from unnaturalcode.unnaturalCode import * from logging import debug, info, warning, error import urllib import re allWhitespace = re.compile('^\s+$') whitespace = re.compile('\s') class genericLexeme(ucLexeme): @classmethod def stringify_build(cls, t, v): """ ...
""" The MIT License (MIT) Copyright (c) 2016 Stratos Goudelis 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 rights to use, copy, modify, me...
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QFileDialog, QToolBar, QToolButton, QMenu, QAction, QLabel, QApplication from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QStandardPaths, QTimer import os class QtCommons: def nestWidget(parent, child): l = QVBoxLayout() l.setContentsMargi...
import re import string install_error_pattern = re.compile("Error: (.*)$", re.MULTILINE) def log_install_errors(ctx, output): """ Print warning for Error: :param ctx: :param output: :return: nothing """ errors = re.findall(install_error_pattern, output) for line in errors: ...
""" ArcREST Setup Code """ from distutils.core import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) packages = ['arcresthelper','arcresthelper/packages', 'arcrest','arcrest/agol','arcrest/agol/helperservices', 'arcrest/ags', 'arcrest/common', '...
from threading import Condition condition = Condition() class ProducerThread(Thread): def run(self): nums = range(5) global queue while True: condition.acquire() num = random.choice(nums) queue.append(num) print "Produced", num ...
# -*- coding: utf-8 -*- """Functions for computing treewidth decomposition. Treewidth of an undirected graph is a number associated with the graph. It can be defined as the size of the largest vertex set (bag) in a tree decomposition of the graph minus one. `Wikipedia: Treewidth <https://en.wikipedia.org/wiki/Treewid...
#!/usr/bin/env python #JSON {"lot": "RKS/6-31G*", #JSON "scf": "ODASCFSolver", #JSON "linalg": "CholeskyLinalgFactory", #JSON "difficulty": 3, #JSON "description": "Basic RKS DFT example with LDA exhange-correlation functional (Dirac+VWN)"} from horton import * # Load the coordinates from file. # Use the XYZ file...
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import requests import yajl as json import progressbar as pb dir = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] sys.path.append(dir) from termcolor import colored as color from utilities.prompt_format import item as I def DeleteAllDat...
from __future__ import unicode_literals import os def get_env_list(name, default=None): """Helper to get list from environment.""" if name not in os.environ: return default or [] return os.environ[name].split(',') def get_env_map(name, default=None): """ Helper to get mapping from envir...
r""" Calculates the scattering for a generalized Guinier/power law object. This is an empirical model that can be used to determine the size and dimensionality of scattering objects, including asymmetric objects such as rods or platelets, and shapes intermediate between spheres and rods or between rods and platelets, a...
import os import sys from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand tests_require = [ 'check-manifest>=0.25', 'coverage>=4.0', 'isort>=4.2.2', 'pep257>=0.7.0', 'pytest-cache>=1.0', 'pytest-cov>=1.8.0', 'pytest-pep8>=1.0.6', 'pytest>...
from StringIO import StringIO from datetime import datetime, timedelta from mock import MagicMock from casexml.apps.case.models import CommCareCase from casexml.apps.case.tests.util import check_xml_line_by_line from casexml.apps.case.xml import V1 from django.core.urlresolvers import reverse from django.test import ...
# -*- 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): # Adding index on 'TweetChunk', fields ['created_at'] db.create_index(u'm...
# -*- coding: utf-8 -*- """ Copyright (C) 2011 Wagner Sartori Junior <<EMAIL>> http://www.wsartori.com This file is part of James. James program 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 ...
import subprocess exe_path = '/Users/chanita/projects/pronto/ban2stats/client/webservice_client.py' from django.core.management import call_command from django.core.management.base import BaseCommand def attack(ip, service_name): command_arguments = [exe_path, service_name, "https", "81", ip] process = subpro...
import hashlib import os.path import re from libs import constants from libs.getpass import getpass from libs.cryptolib import encrypt_file from libs.cryptolib import decrypt_file askedaction = raw_input('What do you wanna do ? decrypt/encrypt - [D/e]: ') if (re.match('^(?i)d(ecrypt|)$',askedaction) or not askedacti...
import numpy as np import cv2 import sys size=0.9 if sys.argv[1] == 'picam': cap=cv2.VideoCapture(1) cont=0 while(1): ret,frame=cap.read() mensaje='Picamera puerto(1)' cv2.putText(frame, mensaje, (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX,size, (0, 0, 255), 2) cv2.imshow('frame',frame) ...
from . import banking_export_sdd from . import res_company from . import account_banking_mandate
import os import subprocess import sys import time import unittest import zipfile from subpar.compiler import error from subpar.compiler import python_archive from subpar.compiler import stored_resource from subpar.compiler import test_utils # pylint: disable=too-many-instance-attributes class PythonArchiveTest(unit...
import os import shutil import json from avocado import Test from avocado import main from avocado.utils import process from avocado.utils.software_manager import SoftwareManager class Hackbench(Test): """ This module will run the hackbench benchmark. Hackbench is a benchmark for measuring the performan...
from __future__ import absolute_import from celery.datastructures import LimitedSet from celery.worker import state from celery.tests.utils import Case class StateResetCase(Case): def setUp(self): self.reset_state() self.on_setup() def tearDown(self): self.reset_state() self...
from world import World import time from shapely.geometry import Polygon import pygame class GraphicalWorld(World): def __init__(self, perimeter, window_width, window_height): super(GraphicalWorld, self).__init__(perimeter) self.window_width = window_width self.window_height = window_heig...
#!/usr/bin/env python import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import settings import socket import traceback import signal import logging, logging.config from partition_mess...
#!/usr/bin/python # -*- coding: utf-8 -*- ## # Wrapper around the crawlutils module that provides: # (a) an autonomous push mode via command-line invocation, and # (b) a network pull mode via an HTTP REST interface (xxx CURRENTLY DISABLED) ## import os import sys import logging import logging.handlers import time imp...
import nltk import re _stemmer = None _lemmatizer = None def nltk_major_version(): return int(nltk.__version__.split('.')[0]) NLTK_VERSION = nltk_major_version() ALNUM_PAT = re.compile(r'[A-Za-z0-9]+') MULTIWORD_PAT = re.compile(r'(.*) +(.*)') def get_sentences(text): """Return sentence list""" ...
#!/usr/bin/env python2.3 # use FFTPACK as a baseline import FFT from Numeric import * import math import random import sys import struct import fft pi=math.pi e=math.e j=complex(0,1) lims=(-32768,32767) def randbuf(n,cpx=1): res = array( [ random.uniform( lims[0],lims[1] ) for i in range(n) ] ) if cpx: ...
from django.forms import widgets, CharField, ChoiceField from django.utils.html import format_html from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from cms.plugin_pool import plugin_pool from entangled.forms import EntangledModelFormMixin from cmsplugin_cascade.plug...
#!/usr/bin/env python3 '''Test for changeset application after restart. ''' from dnstest.test import Test import dnstest.utils def check_axfr(server, zone): # Get AXFR axfr_pre = server.dig(zone[0].name, "AXFR", log_no_sep=True) # Restart server.stop() t.sleep(1) server.start() server.zo...
"""Invenio module to integrate beard.""" import os import sys from setuptools import setup from setuptools.command.test import test as TestCommand readme = open('README.rst').read() history = open('CHANGES.rst').read() requirements = [ ] test_requirements = [ 'unittest2>=1.1.0', 'pytest>=2.8.0', 'pytes...
from functools import wraps from django.core.exceptions import PermissionDenied from django.http import HttpResponseNotAllowed, HttpResponseRedirect from canvas.api_decorators import is_api from django.conf import settings def view_guard(guard): """ It will check if the view has already been decorated with `...
from sqla_wrapper import SQLAlchemy, Paginator def create_test_model(): db = SQLAlchemy('sqlite://') class Item(db.Model): id = db.Column(db.Integer, primary_key=True) class Part(db.Model): id = db.Column(db.Integer, primary_key=True) item_id = db.Column(db.Integer, db.ForeignKey...
""" utilities.py """ import os import tarfile from scipy.spatial import cKDTree import numpy as np from shutil import rmtree, copyfile from ConfigParser import SafeConfigParser from netCDF4 import Dataset from logging import getLogger from log import LOG_NAME from share import TIMESTAMPFORM, RPOINTER, EARTHRADIUS, METE...
from django import forms from django.db.models import F from django.test import TestCase from agir.lib.form_fields import IBANField from agir.lib.iban import IBAN from agir.lib.tests.models import IBANTestModel # generated on http://randomiban.com/ GOOD_IBANS = [ "NL28ABNA4217631642", "MZ656811669129982389359...
import collections import collections.abc import threading class LRUCache(collections.abc.MutableMapping): """Thread-safe LRUCache based on an OrderedDict. All dict operations (__getitem__, __setitem__, __contains__) update the priority of the relevant key and take O(1) time. The dict is iterated over ...
"""Implements the OSEO GetOptions operation""" import logging import pyxb import pyxb.bundles.opengis.oseo_1_0 as oseo import pyxb.bundles.opengis.swe_2_0 as swe from ..models import Order from .. import settings from .. import utilities logger = logging.getLogger(__name__) def create_oseo_order_options(collectio...
#!/usr/bin/env python3 from argparse import ArgumentParser, RawTextHelpFormatter from itertools import islice import getpass import logging import os from pygerrit2 import GerritRestAPI, HTTPBasicAuth, HTTPBasicAuthFromNetrc from tqdm import tqdm EPILOG = """\ To query the list of changes which have been created or m...
from __future__ import absolute_import from flask.ext.wtf import Form import os from wtforms import validators from digits import utils from digits.utils import subclass from digits.utils.forms import validate_required_if_set @subclass class DatasetForm(Form): """ A form used to create an image processing da...
#verarching Script import numpy import tables import scipy import matplotlib import matplotlib.pyplot as plt import collections import scipy.signal import csv import egan_vorpalUtil as egan import os #import plotPlasmoids as pplas import pplot DEBUG=False RunOne=False #if I just want to run one dump RunNone=0 DistPlot...
from ironic.db import api as db_api from ironic.db.sqlalchemy import models from ironic import objects from ironic.tests.db import base from ironic.tests.db import utils class TestPortObject(base.DbTestCase): def setUp(self): super(TestPortObject, self).setUp() self.fake_port = utils.get_test_por...
"""Fichier contenant le type bracelet.""" from .bijou import Bijou class Bracelet(Bijou): """Type d'objet: bracelet. """ nom_type = "bracelet" protection_froid = 1 def __init__(self, cle=""): Bijou.__init__(self, cle) self.emplacement = "poignets" self.positions = (1, )