content
stringlengths
4
20k
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2006-2010 (ita) # Ralf Habacker, 2006 (rh) import os from waflib import Utils from waflib.Tools import ccroot, ar from waflib.Configure import conf @conf def find_sxx(conf): """ Detect the sun C++ compiler """ v = conf.env cc = None if v['CXX']: cc = v['CXX...
from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render from django.http import HttpResponse, Http404 from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.core import serializers from django.http import JsonResponse ...
import re from openstates.utils import url_xpath, State from .people import UTPersonScraper from .events import UTEventScraper from .bills import UTBillScraper # from .committees import UTCommitteeScraper class Utah(State): scrapers = { "people": UTPersonScraper, "events": UTEventScraper, ...
import logging import posixpath import threading import time import json from django.utils.translation import ugettext as _ from desktop.conf import TIME_ZONE from desktop.lib.rest.http_client import HttpClient from link import Link from job import Job from connector import Connector from driver import Driver from e...
from __future__ import generators import sys import time from celery.tests.utils import unittest from itertools import chain, izip from celery.registry import TaskRegistry from celery.task.base import Task from celery.utils import timeutils from celery.utils import gen_unique_id from celery.utils.functional import p...
# -*- coding: utf-8 -*- from .exceptions import ReadError from .parsers import ebml from .mkv import MKV from .parsers import ebml import logging import codecs import os import io __all__ = ['Subtitle'] logger = logging.getLogger(__name__) class Subtitle(object): """Subtitle extractor for Matroska Video File. ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import image_cropping.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Page', fields=[ ('...
{ 'name': 'La Maison Dub - Custom Module', 'summary': 'Custom Settings for La Maison Dub', 'version': '0.1', 'category': 'Custom', 'license': 'AGPL-3', 'author': 'La Maison Dub', 'website': 'http://lamaisondub.potager.org', 'depends': [ 'base', 'account', 'web_tre...
import account_invoice_special_message # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
#!/usr/bin/env python import time import os import logging import subprocess def resize_image(path, width, save_path): # _resize_tool = 'resize' # cmd = ( # 'convert %s -%s %d %s' % # (path, _resize_tool, width, save_path) # ) # cmd = 'MAGICK_THREAD_LIMIT=1 ' + cmd # see https://gi...
import warnings from collections import OrderedDict from optparse import make_option from django.apps import apps from django.core.management.base import BaseCommand, CommandError from django.core import serializers from django.db import router, DEFAULT_DB_ALIAS from django.utils.deprecation import RemovedInDjango19W...
from marionette_test import MarionetteTestCase class TestPageSource(MarionetteTestCase): def testShouldReturnTheSourceOfAPage(self): test_html = self.marionette.absolute_url("testPageSource.html") self.marionette.navigate(test_html) source = self.marionette.page_source self.assertTr...
def extractNovitranslation(item): """ Novels Translation """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None tagmap = { 'The Evil Prince and his Precious Wife: The Sly Lady' : 'The Evil Prince a...
# -*- coding: cp1252 -*- from __future__ import print_function #compatibilité python 3.0 import xmlreader import libsimpa from libsimpa import vec3 import math ## # @file coreConfig.py # \~english # This file contain the class coreconfig that read the XML file and feed some arrays and dict with data extracted from th...
from . import ArchiveTest, Content from .. import needs_program class TestArc(ArchiveTest): program = 'arc' @needs_program(program) def test_arc(self): self.archive_commands(self.filename + '.arc', check=Content.Multifile) @needs_program('file') @needs_program(program) def test_arc_f...
# -*- encoding: utf-8 -*- """ staticDHCPd module: web Purpose ======= Provides a web interface for viewing and interacting with a staticDHCPd server. Legal ===== This file is part of staticDHCPd. staticDHCPd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public Lice...
from .resource import Resource class Rule(Resource): """Description of Rule Resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :ivar name: Resource name :vartype name: str :ivar type: Resource type ...
try: from neutronclient.neutron import client from keystoneclient.v2_0 import client as ksclient except ImportError: print("failed=True msg='neutronclient and keystone client are required'") _os_keystone = None _os_tenant_id = None def _get_ksclient(module, kwargs): try: kclient = ksclient.Cli...
import os import sys import datetime import glob import pcraster as pcr from pcraster.framework import DynamicModel from pcraster.framework import DynamicFramework from configuration_for_modflow import Configuration from currTimeStep import ModelTime from reporting_for_modflow import Reporting from modflow import Mo...
from .__meta__ import * from tracer.resources.applications import Applications, Application from tracer.resources.collections import ApplicationsCollection, ProcessesCollection class TestApplications(unittest.TestCase): def test_apps_types(self): self.assertIsInstance(Applications.all(), ApplicationsCollection) ...
# -*- coding: utf-8 -*- """ This package contains a set of widgets that might be useful when writing pyqode applications: - TextCodeEdit: code edit specialised for plain text - GenericCodeEdit: generic code edit, using PygmentsSH. Not really fast, not really smart. - InteractiveConsole: QTextEdit mad...
import os from Biskit.tools import * time_offset = 40.0 ## (start time) def get_rst_time( frst ): """extract time of last snapshot""" f = open( frst ) f.readline() l = f.readline() f.close() t = float( l.split()[1] ) return t def rename_current_files( folder, current_time, exclude=[] ...
from functools import total_ordering class InvalidPeriodError(Exception): pass def validate_year(year): if year < 1970 or year > 9999: raise InvalidPeriodError("Year must be between 1970 and 9999") def validate_month(month): if month < 1 or month > 12: raise InvalidPeriodError("Month m...
def startPython(name): work = open(name, 'r') output = open(name + '.ShowCode', 'w') if name.endswith('.java'): java(work, output) def java_count_braces(line, current_amount): if line.find('{') != -1: current_amount = current_amount + 1 elif line.find('}') != -1: current_amount = current_amount ...
#!/usr/bin/python # # Bertrone Matteo - Polytechnic of Turin # November 2015 # # eBPF application that parses HTTP packets # and extracts (and prints on screen) the URL # contained in the GET/POST request. # # eBPF program http_filter is used as SOCKET_FILTER attached to eth0 interface. # Only packets of type ip and tc...
import functools from oslo_serialization import jsonutils as json from six.moves import http_client from six.moves.urllib import parse as urllib from tempest.lib.common import api_version_utils from tempest.lib.common import rest_client # NOTE(vsaienko): concurrent tests work because they are launched in # separate p...
"""Experiment loop.""" import haiku as hk import jax def run_loop( agent, environment, accumulator, seed, batch_size, train_episodes, evaluate_every, eval_episodes): """A simple run loop for examples of reinforcement learning with rlax.""" # Init agent. rng = hk.PRNGSequence(jax.random.PRNGKey(seed)) ...
from datetime import datetime import urlparse import logging from BeautifulSoup import BeautifulSoup from consts.event_type import EventType from datafeeds.parser_base import ParserBase from helpers.event_helper import EventHelper class UsfirstEventOffseasonListParser(ParserBase): @classmethod def parse(se...
from django.test import TestCase, Client from django.test.client import RequestFactory from django.core.urlresolvers import reverse from django.contrib import admin from django.contrib.flatpages.models import FlatPage from admin_extras.admin import ReadOnlyMixin from .utils import ( create_staff_user, create_...
import random def read_sudoku(filename): """ Прочитать Судоку из указанного файла """ digits = [c for c in open(filename).read() if c in '123456789.'] grid = group(digits, 9) return grid def display(values): """Вывод Судоку """ width = 2 line = '+'.join(['-' * (width * 3)] ...
''' QuickGrid library - very simple communication with spreadsheets. v1 ''' import csv import unicodecsv as ucsv import os from itertools import groupby from collections import Counter import codecs import sys import six csv.field_size_limit(sys.maxsize) try: from openpyxl import load_workbook ...
#!/usr/bin/env python ''' Digit recognition adjustment. Grid search is used to find the best parameters for SVM and KNearest classifiers. SVM adjustment follows the guidelines given in http://www.csie.ntu.edu.tw/~cjlin/papers/guide/guide.pdf Usage: digits_adjust.py [--model {svm|knearest}] --model {svm|knearest}...
from bibliopixel.animation.matrix import Matrix from bibliopixel.util import log import numpy as np try: import cv2 except ImportError: log.error('Could not import cv2 library') import os grab = None if os.name == 'nt': try: from desktopmagic.screengrab_win32 import getRectAsImage, getScreenAsImag...
import asyncio import functools import blinker from . import errors from .utils import SleepUneasy from ..logging import make_logger # isort:skip log = make_logger(__name__) def _func_call_str(func, *posargs, **kwargs): if func is None: return '<None>' elif hasattr(func, '__qualname__'): n...
#!/usr/bin/env python """Simple tool for generating a client library. Relevant links: https://developers.google.com/discovery/v1/reference/apis#resource """ from six.moves import urllib_parse from apitools.base.py import base_cli from apitools.gen import command_registry from apitools.gen import message_registry f...
import pytest import numpy as np import os import quantities as pq import exdir from exdir.core import Attribute, File, Dataset from exdir.plugins.quantities import convert_quantities, convert_back_quantities def test_create_quantities_file(setup_teardown_folder): f = exdir.File(setup_teardown_folder[1], 'w', p...
import os import shutil import tempfile from unittest import TestCase from ..test_base import PackstackTestCaseMixin from packstack.installer.core.drones import * class SshTarballTransferMixinTestCase(PackstackTestCaseMixin, TestCase): def setUp(self): # Creating a temp directory that can be used by test...
from __future__ import print_function, unicode_literals from functools import reduce from nltk.tree import Tree, ProbabilisticTree from nltk.compat import python_2_unicode_compatible from nltk.parse.api import ParserI ##////////////////////////////////////////////////////// ## Viterbi PCFG Parser ##//////...
from __future__ import division, print_function, absolute_import import numpy as np from numpy.testing import assert_allclose, assert_equal from scipy import linalg import cvxopt import cvxpy import warnings from cvxpy.tests.base_test import BaseTest class TestNonOptimal(BaseTest): def test_singular_quad_form(se...
#!/usr/bin/python3 import subprocess as sp import re import os import hashlib MAIN_CM_FOLDER = os.path.dirname(os.path.dirname(__file__)) DEVEL_INPUT_HTML = os.path.join(MAIN_CM_FOLDER, 'res/devel.html') MAIN_OUTPUT_HTML = os.path.join(MAIN_CM_FOLDER, 'res/dist/main.html') LESSC = 'lessc' JSMIN = 'jsmin' def prog_...
''' GooMPy: Google Maps for Python Copyright (C) 2015 Alec Singer and Simon D. Levy This code is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any lat...
"""Quantize local features and aggregate them using the Vector of Locally Aggregated Descriptors (VLAD) encoding""" import numpy as np from sklearn import cluster from sklearn.metrics import pairwise_distances from .base import BaseAggregator class Vlad(BaseAggregator): """Compute a VLAD model and aggregate loc...
import numpy as np from opensfm import config, multiview, pymap, reconstruction, types def test_corresponding_tracks(): t1 = {1: pymap.Observation(1.0, 1.0, 1.0, 0, 0, 0, 1, 1, 1)} t2 = {1: pymap.Observation(1.0, 1.0, 1.0, 0, 0, 0, 2, 2, 2)} correspondences = reconstruction.corresponding_tracks(t1, t2) ...
import urllib,urllib2,re,cookielib,os,sys import xbmc, xbmcgui, xbmcaddon, xbmcplugin from resources.libs import main #Mash Up - by Mash2k3 2012. from t0mm0.common.addon import Addon addon_id = 'plugin.video.movie25' selfAddon = xbmcaddon.Addon(id=addon_id) addon = Addon('plugin.video.movie25', sys.argv) art = main.a...
# -*- coding: utf-8 -*- """ Created on Thu Apr 09 10:39:38 2015 @author: 108630 """ import os import pandas as pd import numpy as np import cPickle as pickle #test_data_dir = os.path.dirname(os.path.realpath(__file__)) #data_dir = os.path.join(test_data_dir, "environmental") # #table_path = os.path.join(data_dir, "s...
#!/usr/bin/python3 # This script is a simple introduction to the python elasticsearch API. # # This script will populate an elasticsearch index from a file and then give a simple command line query interface. # Each line of the input file will be mapped into a JSON document of the form { "text": "my file line......
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Procedures to handle Roche 454 sff data, mostly use sff-tools supplied by Roche. """ import os.path as op import sys import logging from jcvi.apps.base import OptionParser, ActionDispatcher, mkdir, sh, glob def main(): actions = ( ('mid', 'produce a MI...
import os import glob from datetime import datetime, timedelta try: import OpenSSL.crypto HAS_OPENSSL = True except: HAS_OPENSSL = False try: import pyrad.packet from pyrad.client import Client from pyrad.dictionary import Dictionary HAS_PYRAD = True except: HAS_PYRAD = False try: im...
""" sentry.templatetags.sentry_activity ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import logging from django import template from django.utils.html import esca...
# pylint: disable=missing-docstring from unittest import TestCase import ddt from track import contexts @ddt.ddt class TestContexts(TestCase): COURSE_ID = 'test/course_name/course_run' SPLIT_COURSE_ID = 'course-v1:test+course_name+course_run' ORG_ID = 'test' @ddt.data( (COURSE_ID, ''), ...
"""Widgets for Track Channels Tab""" import cairo from gi.repository import Gdk, Gtk from olc.define import App from olc.widgets import rounded_rectangle_fill class TrackChannelsHeader(Gtk.Widget): """Header widget""" __gtype_name__ = "TrackChannelsHeader" def __init__(self, channels): Gtk.Widg...
class Node(object): def __init__(self, data): self.data = data; self.left = None; self.right = None; def insert(self,data): newNode = Node(data); if data < self.data : if self.left is None: self.left = newNode; e...
# -*- coding: utf-8 -*- """ """ from __future__ import absolute_import, with_statement import copy import operator import re import threading class _Config(object): @property def lock(self): return self._lock @property def use_unicode(self): with self.lock: return copy.c...
# -*- coding: utf-8 -*- __all__ = [ 'CopperError', ] class CopperErrorMeta(type): def __new__(meta, name, bases, bodydict): cls = type.__new__(meta, name, bases, bodydict) copper_error = bodydict.get('copper_error') if copper_error is not None: classes_by_code = cls.classes_...
from reclass.datatypes import Classes from reclass.datatypes.classes import INVALID_CHARACTERS_FOR_CLASSNAMES import unittest try: import unittest.mock as mock except ImportError: import mock from reclass.errors import InvalidClassnameError TESTLIST1 = ['one', 'two', 'three'] TESTLIST2 = ['red', 'green', 'blue...
from __future__ import absolute_import import os import logging import stat try: import threading except ImportError: #pragma: no cover import dummy_threading as threading from tg.support.converters import asbool from markupsafe import Markup from tg.render import cached_template from .base import RendererFa...
import sys import hmac import base64 import Config from logging import debug from Utils import encode_to_s3, time_to_epoch, deunicodise import datetime import urllib # hashlib backported to python 2.4 / 2.5 is not compatible with hmac! if sys.version_info[0] == 2 and sys.version_info[1] < 6: import sha as sha1 ...
import Obit, UV, Table, OErr # SN table smoothing Soln2CalInput={ 'structure':['PSoln2Cal',[('solnVer', 'Input Solution (SN) table version '), ('calIn', 'Input Cal (CL) table version, 0=high, -1=none'), ('calOut', 'Output Calibration table version, ...
import itertools import json import os import subprocess as sp import sys from enum import Enum, auto from numbers import Number from os import path from subprocess import DEVNULL, PIPE from typing import NamedTuple, Iterator, Iterable, List, Optional, Sequence import numpy as np from audio_io.cue.cue_parser import C...
import math class Electrons: def __init__(self, g_min, g_max, p_law, ene_dens): #energy density in GeV/m^3 self.value = self.kappa(g_min, g_max, p_law, ene_dens) def kappa(self, g_min, g_max, p_law, ene_dens): mc2 = 8.187111168006824e-14 e_density = (ene_dens)/mc2 ...
# Standard imports import json import requests import logging import arrow import attrdict as ad # Our imports import emission.core.get_database as edb import emission.net.ext_service.habitica.proxy as proxy import emission.analysis.result.metrics.simple_metrics as earmts import emission.analysis.result.metrics.time_g...
""" Utility for caching master images. """ import os import tempfile import time import uuid from oslo_concurrency import lockutils from oslo_config import cfg from oslo_log import log as logging import six from ironic.common import exception from ironic.common.glance_service import service_utils from ironic.common....
#!/usr/bin/env python3 from model_weights import * import argparse import yaml if __name__ == "__main__": parser = argparse.ArgumentParser(description='See what variables are stored in model.npy file') parser.add_argument('-c', '--clean', dest='remove_unmapped', action='store_true', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('categories', '0004_auto_20140904_0927'), ] operations = [ migrations.AlterField( ...
#!/usr/bin/env python # Import the file being tested from piheat import * # Remove the 'FileHandler' set in piheat.py so that output from the test suite can be logged in a different file. log = logging.getLogger() for hdlr in log.handlers[:]: # remove all old handlers log.removeHandler(hdlr) # Set the logging...
from msrest.serialization import Model class Capability(Model): """Describes the capabilities/features allowed for a specific SKU. :param name: Name of the SKU capability. :type name: str :param value: Value of the SKU capability. :type value: str :param reason: Reason of the SKU capability. ...
# -*- coding: utf-8 -*- """ Created on Wed Oct 7 21:35:43 2015 @author: nouamanelaanait """ import numpy as np import math from skimage.transform import ProjectiveTransform import multiprocess as mp import warnings from scipy.signal import find_peaks_cwt, cwt def pickle_keypoints(keypoints): ''' Function to pic...
import logging import requests from flask import current_app as app from structlog import wrap_logger from frontstage.controllers import case_controller from frontstage.exceptions.exceptions import ApiError, CiUploadError logger = wrap_logger(logging.getLogger(__name__)) def download_collection_instrument(collecti...
# Transect Extraction module # possible categories: preprocess, create, calculate import time import os import collections import pandas as pd import numpy as np from operator import add def print_duration(start, suppress=False): duration = time.clock() - start hours, remainder = divmod(duration, 3600) mi...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Y:\eric6_workspace\Pyquino\graphy\graphy.ui' # # Created by: PyQt5 UI code generator 5.7 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dia...
"""Support for GPSD.""" import logging import socket from gps3.agps3threaded import AGPS3mechanism import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_MODE, CONF_HOST, CONF_NAME, CONF_PORT, )...
"""SCons.Tool.applelink Tool-specific initialization for the Apple gnu-like linker. 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 - 2015 The SCons Foundation # # Permission is hereby...
import time import struct import base64 import crypto import settings BOX = crypto.Toolbox(settings.EKEY, settings.AKEY) MAX_USER_LEN = 12 MAX_TOKEN_LEN = 16 USER_PADDING = '\0' def generate_token(username, ttl=7200): # A token is a base64-encoded, encrypted, binary structure as follows: # [padded username ...
from string import * import sys, os.path import urllib import urllib2 import re, random, string import xbmc, xbmcgui import re, os, time, datetime, traceback import shutil import os from libs2 import * from settings import * try: Emulating = xbmcgui.Emulating except: Emulating = False IMAGE_RATING = 142 BUTTON_RATE1 ...
from django import forms from django.core.exceptions import ValidationError from django.template import Context from ietf.dbtemplate.models import DBTemplate from ietf.dbtemplate.template import PlainTemplate, RSTTemplate, DjangoTemplate import debug # pyflakes:ignore class DBTemplateForm(...
import Axon import zlib import os import pygame from datetime import datetime from zipfile import ZipFile from Tkinter import Tk from tkFileDialog import askopenfilename from tkSimpleDialog import askstring from tkMessageBox import askyesno from Axon.Ipc import WaitComplete, producerFinished, shutdownMicroprocess fr...
#! /usr/bin/env python3.4 """ Usage: samsoul [-si] samsoul -u [<login>] samsoul --generate-conf Options: -s Start netsoul deamon -i Launch interactive session --generate-conf Generate a conf from actual PIE network mapping -u List user...
from config import defaut_lang from utils.database import * from utils.tools import * from importlib import import_module as import_lang import dataset def get_user_lang(self): db = dataset.connect('sqlite:///db' + hash) table = db['user:' + str(self.bot_type) + str(self.chat_id)] r = table.find_one(info='lang') i...
"""remove bad autoincrements Revision ID: 5b141f32ea38 Revises: 4653b4902dc0 Create Date: 2017-07-27 22:51:11.172610+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.schema import Sequence, CreateSequence # revision identifiers, used by Alembic. revision = '5b141f32ea38' down_revision = '465...
import mysql.connector as mc class Database(): def __init__(self, host, user, passwd, database, debug=None): self.debug = debug self.conn = mc.connect(user=user, password=passwd, host=host, database=database) self.cursor = self...
from framework.templates import optical_module_template from c1218.errors import C1218ReadTableError from c1219.access.general import C1219GeneralAccess class Module(optical_module_template): def __init__(self, *args, **kwargs): optical_module_template.__init__(self, *args, **kwargs) self.version = 1 self.autho...
"""Unit tests for the `iris.plot.plot` function.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests # isort:skip import numpy as np import iris.coord_systems as ics import iris.coords as coords from iris.tests.unit.plot import TestGraphic...
from time import sleep import pytest from pynq import Overlay from pynq.overlays.base import BaseOverlay from pynq.tests.util import user_answer_yes __author__ = "Giuseppe Natale, Yun Rock Qu" __copyright__ = "Copyright 2016, Xilinx" __email__ = "<EMAIL>" try: ol = Overlay('base.bit', download=False) flag0 ...
import errno import platform from setuptools import setup, Extension, find_packages from setuptools.command.build_ext import build_ext from distutils.errors import DistutilsPlatformError import subprocess class build_ext_with_protpbuf(build_ext): def run(self): try: proc = subprocess.Popen( ...
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import AllowAny from edctf.api.models import scoreboard, team from edctf.api.serializers import scoreboard_serializer, team_serializer import time class scoreboard_view(APIView): """ Manages score...
#!/usr/bin/env python # Run this test like so: # vtkpython TestTensorGlyph.py -D $VTK_DATA_ROOT \ # -B $VTK_DATA_ROOT/Baseline/Graphics/ import os import vtk from vtk.test import Testing class SimpleGlyph: """A simple class used to test vtkTensorGlyph.""" def __init__(self, reader): self.reader = re...
#!/usr/bin/env python import os, tarfile, hashlib, re, shutil, sys def scrub(b): if sys.version_info >= (3,) and type(b) == bytes: return b.decode('ascii') else: return b snapshot_dir = scrub(os.getenv("SNAPSHOTDIR")) if not snapshot_dir: raise Exception("missing env var SNAPSHOTDIR: which should spe...
from chowaudio import (Sound, listener, open as open_audio, close as close_audio, AudioError) open_audio() MUTED = False if MUTED: listener.volume = 0.0 class Track(object): volume = 1.0 volume_add = None sound = None def __init__(self, filename): self.filename = filename de...
'''This example demonstrates the use of Convolution1D for text classification. Run on GPU: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python imdb_cnn.py Get to 0.835 test accuracy after 2 epochs. 100s/epoch on K520 GPU. ''' from __future__ import print_function import numpy as np np.random.seed(1337) # fo...
# -*- coding: utf-8 """ Contains unit tests for :mod:`mr_freeze.devices.abstract_cryomagnetics_device` """ import unittest import unittest.mock as mock from threading import Lock from mr_freeze.devices.abstract_cryomagnetics_device import \ AbstractCryomagneticsDevice class ConcreteCryomagneticsDevice(AbstractCry...
import gym import random import numpy as np import os import copy import torch import torch.optim as optim import logging from collections import deque from codecs import open from gtd.ml.torch.training_run import TorchTrainingRun from gtd.ml.torch.utils import try_gpu from gtd.ml.training_run import TrainingRuns from ...
# coding=utf-8 """InaSAFE Disaster risk tool by Australian Aid - Flood Raster Impact on OSM Buildings Contact : <EMAIL> .. note:: This 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 ver...
"""Record field function.""" from invenio_records.signals import before_record_insert from invenio.modules.search.api import Query from invenio.utils.datastructures import LazyDict from six import iteritems COLLECTIONS_DELETED_RECORDS = '{dbquery} AND NOT collection:"DELETED"' def _queries(): """Preprocess col...
""" This module holds a ID3Tag class which takes a file and constructs an object representing the tag. """ import os import sys import frame as Frame from mutagen.mp3 import MP3 from mutagen.id3 import ID3, ID3NoHeaderError, ID3TimeStamp, TPE1 from compatid3 import CompatID3 class ID3TagInvalidFrame(Exception): ...
import numpy as np from pyscf import lib from pyscf.lib import logger #einsum = np.einsum einsum = lib.einsum # Ref: Gauss and Stanton, J. Chem. Phys. 103, 3561 (1995) Table III # Section (a) def make_tau(t2, t1a, t1b, fac=1, out=None): t1t1 = einsum('ia,jb->ijab', fac*0.5*t1a, t1b) t1t1 = t1t1 - t1t1.trans...
from builtins import str import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils def separator_test(): #Test tab seperated files by giving separator argument path_tab = "smalldata/parser/tabs.tsv" tab_test = h2o.import_file(path=pyunit_utils.locate(path_tab), destination_frame="ta...
""" Routines for removing redundant (linearly dependent) equations from linear programming equality constraints. """ from __future__ import division, print_function, absolute_import import numpy as np from scipy.linalg import svd import scipy def _row_count(A): """ Counts the number of nonzeros in each row o...
# -*- coding: utf-8 -*- from bs4 import FeatureNotFound import pytest from subliminal.providers import ParserBeautifulSoup, Provider, get_version from subliminal.video import Episode, Movie def test_parserbeautifulsoup_reject_features(): with pytest.raises(ValueError): ParserBeautifulSoup('', ['lxml', 'h...
import unittest import bifrost as bf from bifrost.blocks import * import os import shutil class TemporaryDirectory(object): def __init__(self, path): self.path = path os.makedirs(self.path) def remove(self): shutil.rmtree(self.path) def __enter__(self): return self def...
import os import yaml import popper.scm as scm from hashlib import shake_256 from popper.cli import log as log from box import Box class ConfigLoader(object): @staticmethod def load( engine_name=None, resman_name=None, config_file=None, workspace_dir=os.getcwd(), reu...