content
stringlengths
4
20k
import unittest from collections import namedtuple from Vintageous.vi.utils import modes from Vintageous.tests import set_text from Vintageous.tests import add_sel from Vintageous.tests import get_sel from Vintageous.tests import first_sel from Vintageous.tests import ViewTest def get_text(test): return test.vi...
"""Support for switch sensor using I2C MCP23017 chip.""" import logging import voluptuous as vol import board # pylint: disable=import-error import busio # pylint: disable=import-error import adafruit_mcp230xx # pylint: disable=import-error import digitalio # pylint: disable=import-error from homeassistant.compon...
""" Tests For Volume Number Weigher. """ import mock from oslo_config import cfg from cinder import context from cinder.db.sqlalchemy import api from cinder.scheduler import weights from cinder import test from cinder.tests.unit.scheduler import fakes from cinder.volume import utils CONF = cfg.CONF def fake_volume...
import os, common from proton import * from uuid import uuid3, NAMESPACE_OID class Test(common.Test): def setup(self): self.msg = Message() def teardown(self): self.msg = None class AccessorsTest(Test): def _test(self, name, default, values): d = getattr(self.msg, name) assert d == default, ...
from ducktape.utils.util import wait_until from ducktape.tests.test import Test from ducktape.mark.resource import cluster from ducktape.mark import matrix from ducktape.mark import parametrize, ignore from kafkatest.services.kafka import KafkaService from kafkatest.tests.kafka_test import KafkaTest from kafkatest.serv...
from __future__ import unicode_literals import os from pyupdater.utils.config import TransistionDict, Loader class DevConfig(object): TESTING = True TEST_LOVE = True MORE_INFO = 'No Thanks' Bad_Attr = True class ProdConfig(object): TESTING = False DEBUG = False MORE_INFO = 'Yes Please'...
''' Created on Nov 14, 2014 @author: rch ''' from traits.api import \ HasStrictTraits, WeakRef, Property, Str from traitsui.api import \ View, Item class OptComponent(HasStrictTraits): '''Component of the optimization problem. Base class for goal functions, equality constraints, and inequality ...
import flask from flask import json from dci.api.v1 import api from dci import decorators @api.route('/identity', methods=['GET']) @decorators.login_required @decorators.check_roles def get_identity(identity): """Returns some information about the currently authenticated identity""" return flask.Response( ...
import json from unittest import TestCase from common.cloud.aws.aws_service import filter_instance_data_from_aws_response __author__ = "shay.nehmad" class TestAwsService(TestCase): def test_filter_instance_data_from_aws_response(self): json_response_full = """ { "InstanceInformationL...
# encoding: utf-8 import urllib, urllib2, re, datetime, traceback, sys, os, subprocess from BeautifulSoup import BeautifulSoup from django.conf import settings from committees.models import Committee, CommitteeMeeting from simple.management.utils import antiword import logging from knesset.utils import send_chat_notif...
from termcolors.terminal_query import (TerminalQueryContext, TerminalQueryError, TerminalSetupError, NoResponseError, TerminalUninitializedError) from termcolors.c...
import subprocess import snaps_tests class PyHookCase(snaps_tests.SnapsTestCase): snap_content_dir = 'pyhooks' def test_pyhooks(self): snap_path = self.build_snap(self.snap_content_dir) self.install_snap(snap_path, 'pyhooks', '1.0') # Regular `snap set` should succeed. self....
import logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('socketUdpDispatcher') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import time import threading from pydispatch import dispatcher import socketUdp import coapUtils as u class socketUdpDi...
"""Site administration functionality.""" __author__ = 'Pavel Simakov (<EMAIL>)' import cgi import cStringIO import datetime import os import sys import time import urllib from appengine_config import PRODUCTION_MODE from controllers import sites from controllers.utils import ReflectiveRequestHandler import jinja2 fro...
import commands class HeavyProcessStat(object): def __init__(self, options): if "proc_number" in options: self.howMany = int(options["proc_number"]) else: self.howMany = 5 self.prevCpuDict = {} self.prevMemDict = {} def report(self): howMany =...
#encoding: utf-8 from twisted.trial.unittest import TestCase from vusion import clean_keyword from vusion.utils import ( clean_phone, get_keyword, escape_nested, unescape_nested) class TestCleanKeyword(TestCase): def test_str(self): self.assertEqual( clean_keyword('STRUFF'), '...
from PyPedal import * options = {} options['simulate_pedigree'] = 1 options['simulate_mp'] = 0 options['pedigree_save'] = 1 options['pedigree_summary'] = 2 options['messages'] = 'quiet' options['renumber'] = 1 options['pedformat'] = 'asdxg' if __name__ == '__main__': sizes = [100, 1000, 10000, 100000] #sizes = [10...
from core.blit import Layer from core.blit.blends import multiply, screen, add, subtract, linear_light, \ hard_light import numpy as np BLEND_MODE_NORMAL = 'normal' BLEND_MODE_MULTIPLY = 'multiply' BLEND_MODE_SCREEN = 'screen' BLEND_MODE_ADD = 'add' BLEND_MODE_SUB = 'subtract' BLEND_MODE_LINEAR_LIGHT = 'linear lig...
# -*- coding:utf-8 -*- from __future__ import unicode_literals from django_fsm_log.conf import settings from django import VERSION as django_version if django_version < (1, 7): from django.contrib.contenttypes.generic import GenericForeignKey else: from django.contrib.contenttypes.fields import GenericForeignK...
"""Experimental contributions""" from . import symbol from . import ndarray from . import symbol as sym from . import ndarray as nd from . import autograd from . import tensorboard from . import text from . import onnx from . import io from . import quantization from . import quantization as quant from . import ten...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import __all__ = [] import kplr import numpy as np import matplotlib.pyplot as pl client = kplr.API() def build_matrix(x, nwindow): nx, nt = x.shape X = np.empty((nt - nwindow, nx * nwindow)) for i...
# vim: set ts=4:et from charmhelpers.core.hookenv import ( config, relation_ids, related_units, relation_get, local_unit, unit_get, log ) from charmhelpers.contrib.openstack.context import ( OSContextGenerator, HAProxyContext, context_complete ) from charmhelpers.contrib.hahelper...
""" Django settings for satisfactory project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, .....
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Nibabel-based interfaces.""" import numpy as np import nibabel as nb from nipype import logging from nipype.utils.filemanip import fname_presuffix from nipype.interfaces.base import ( traits, Tra...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from wagtail.wagtailcore.models import Page from privagal.gallery.factories import GalleryFactory from privagal.gallery.models import Gallery from privagal.timeline.factories import TimelineFactory from privagal.timeline...
from unittest import TestCase # this import required to enable PyQt API v2 # noinspection PyUnresolvedReferences import qgis # pylint: disable=unused-import from qgis.core import QgsMapLayerRegistry from PyQt4 import QtCore from safe.test.utilities import get_qgis_app, get_dock QGIS_APP, CANVAS, IFACE, PARENT = get...
from __future__ import absolute_import, print_function, division """ This file contains different error/loss functions. """ ###### Imports ######################################## from abc import ABCMeta, abstractmethod import theano import theano.tensor as T ###### loss funct...
from datetime import date from factory import SubFactory from iati.factory.iati_factory import ( ActivityFactory, CountryFactory, NoDatabaseFactory, RegionFactory, RegionVocabularyFactory, SectorFactory, SectorVocabularyFactory ) from iati.transaction.models import ( Transaction, TransactionDescription, T...
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from hpOneView.resources.resource import ResourceClient class FcNetworks(object): """ F...
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from functools import partial from django.conf import settings from django.contrib.auth.decorators import login_required from django.views.decorators.http import etag from django_tins...
from textwrap import dedent import pytest import copier from copier.config.user_data import load_answersfile_data from .helpers import PROJECT_TEMPLATE SRC = f"{PROJECT_TEMPLATE}_answersfile" @pytest.mark.parametrize("answers_file", [None, ".changed-by-user.yaml"]) def test_answersfile(tmp_path, answers_file): ...
print(__doc__) from time import time import pylab as pl from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter import numpy as np from sklearn import manifold, datasets # Next line to silence pyflakes. This import is needed. Axes3D n_points = 1000 X, color = datasets.samples_generator....
# Based on http://appengine-cookbook.appspot.com/recipe/extended-jsonify-function-for-dbmodel, # with modifications for flask and performance. # use json in Python 2.7, fallback to simplejson for Python 2.5 try: import json except ImportError: import simplejson as json from google.appengine.ext import db from...
"""Module displaying build output in a Sublime output panel.""" import sublime import os import re from . import rust_proc, messages, util, semver # Use the same panel name that Sublime's build system uses so that "Show Build # Results" will open the same panel. I don't see any particular reason why # this would be...
# Advent of Code Day 6 import re def turnOn(x,y): addBrightness(x,y,1) def turnOff(x,y): addBrightness(x,y,-1) def toggleLight(x,y): addBrightness(x,y,2) def addBrightness(x,y,bright): global turnoffcount global turnoncount if bright > 0: turnoncount += bright elif bright < 0: turnoffcount += bright ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import sys import argparse import os, os.path import fnmatch import pdb from src import md2ogp METADATA_OPTIONS = ['mgmg','fgdc','arcgis','marc','iso','guess','eod','gdrs'] def main(): parser = argparse.ArgumentParser() par...
""" Index ----- Index Resource ************** .. http:get:: /api/ This links to the main top-level API endpoints. """ from collections import OrderedDict from rest_framework import status from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from res...
""" Application specific authentication module. """ __author__ = 'Waseem Ahmad <<EMAIL>>' import logging import re import urllib import webapp2 from gaesessions import get_current_session from models import models from models.webapputils import render_page CAS_SERVER = "https://netid.rice.edu" class LoginRespon...
from lino.django.contacts.models import Person, Organisation, Contact, Country, City, Place from django.contrib import admin class PersonAdmin(admin.ModelAdmin): fieldsets = [ (None, dict(fields=['title','firstname','name'])), ('Date information', dict(fields=['birthdate'], ...
import csv import os.path import time from . import crypt, util class Format(object): def __init__(self, fs, crypt_dev): self.fs = fs self.crypt_dev = crypt_dev def run(self): util.run("mkfs", "-t", self.fs, self.crypt_dev) def undo(self): pass class Mount(object): def __init__(self, crypt_dev, mount_d...
# coding=utf-8 from PyQt5 import QtGui, QtCore from kataja.KatajaAction import KatajaAction from kataja.singletons import ctrl # ==== Class variables for KatajaActions: # # k_action_uid : unique id for calling this action. required, other are optional # k_command : text used for menu command and log feedback, unless...
"""Blueprint used for loading templates. The sole purpose of this blueprint is to ensure that Invenio can find the templates and static files located in the folders of the same names next to this file. """ from __future__ import absolute_import, print_function import json from os.path import join from elasticsearch...
import logging from grano.core import db from grano.model import Entity, Relation, Project from grano.logic import entities, relations, projects, accounts from grano.logic.validation import Invalid log = logging.getLogger(__name__) class ObjectLoader(object): # Abstract parent def _setup(self, loader, sch...
# Time: O(n) # Space: O(n) # For a undirected graph with tree characteristics, we can # choose any node as the root. The result graph is then a # rooted tree. Among all possible rooted trees, those with # minimum height are called minimum height trees (MHTs). # Given such a graph, write a function to find all the # ...
from __future__ import print_function import numpy as np import pytest from keras.utils.test_utils import get_test_data, keras_test from keras.models import Sequential from keras.layers.core import Dense, Flatten, Activation from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.utils.np_utils i...
# -*- coding: utf-8 -*- # Last modified: 2017-11-23 # Original data: Ciddor 1996, https://doi.org/10.1364/AO.35.001566 ############################################################################### import numpy as np import matplotlib.pyplot as plt π = np.pi def Z(T,p,xw): #compressibility t=T-273.15 a0 = ...
from conans.model.profile import Profile from conans.errors import ConanException from collections import defaultdict, OrderedDict from conans.model.env_info import EnvValues from conans.model.options import OptionsValues from conans.model.scope import Scopes def profile_from_args(args, cwd, default_folder): """ ...
"""Test the SimplePooledPg module. Note: We don't test performance here, so the test does not predicate whether SimplePooledPg actually will help in improving performance or not. Copyright and credit info: * This test was contributed by Christoph Zwerschke """ __version__ = '1.1' __revision__ = "$Rev: 8218 $" __d...
from fnmatch import fnmatch import logging from urlparse import urlparse from appengine_url_fetcher import AppEngineUrlFetcher from caching_file_system import CachingFileSystem from caching_rietveld_patcher import CachingRietveldPatcher from chained_compiled_file_system import ChainedCompiledFileSystem from compiled_f...
from __future__ import print_function import os import tempfile import argparse import itertools import subprocess from datetime import datetime from contextlib import closing import sqlite3 from progressbar import ProgressBar local_dir = os.path.dirname(os.path.realpath(__file__)) # noqa os.sys.path.append(os.path...
from django.shortcuts import render_to_response, redirect from django.template import RequestContext from forms import PageForm from models import Page def index(request): """Lists all pages stored in the wiki.""" context = { 'pages': Page.objects.all(), } return render_to_response('wiki/ind...
import json import logging from django.utils.html import escape from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from desktop.conf import USE_NEW_EDITOR from desktop.lib.django_util import JsonResponse, render from desktop.lib.exceptions_renderable import PopupException ...
"""Test check_config script.""" import asyncio import logging import os import unittest import homeassistant.scripts.check_config as check_config from tests.common import patch_yaml_files, get_test_config_dir _LOGGER = logging.getLogger(__name__) BASE_CONFIG = ( 'homeassistant:\n' ' name: Home\n' ' lat...
from Sire.IO import * from Sire.Mol import * from Sire.System import * from Sire.MM import * from Sire.CAS import * import glob import os from nose.tools import assert_equal d = "../io/cathepsin" prms = glob.glob("%s/*.parm7" % d) inputs = {} for prm in prms: root = prm[0:-6] rst = glob.glob("%s*.rst7" % ...
# # This is a py.test based testing system. Anything you can do with # py.test, you can do with this too. There are a few magic parameters # provided as fixtures that will allow your tests to access the robot # code and stuff # # robot - This is whatever is returned from the run function in robot.py # wpil...
"""empty message Revision ID: c51c40a0de Revises: None Create Date: 2015-11-13 22:46:22.836216 """ # revision identifiers, used by Alembic. revision = 'c51c40a0de' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### ...
import os constants = { "DEFAULT_ZONE": 'us-central2-b', "API_VERSION": 'v1', "PROJECT_ID": 'de-novo-experiment', "GCE_USER": 'smoitra', "CLIENT_SECRETS": os.path.expanduser('~/Downloads/client_secrets.json'), "GCE_PRIVATE_KEY": os.path.expanduser('~/.ssh/google_compute_engine'), "OAUTH2_ST...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('emailApp', '0003_email_removedcontent'), ] operations = [ migrations.RemoveField( model_name='email', ...
import json import logging from django.db import models from django.db.models import CASCADE from django.core.exceptions import ObjectDoesNotExist from chroma_core.models import AlertStateBase from chroma_core.models import AlertEvent from chroma_core.models import DeletableStatefulObject from chroma_core.models impo...
import numpy from src.stats.bulk_stats import BulkStats class GlobalStats(object): def __init__(self): super(GlobalStats, self).__init__() self.bulks = [] def __del__(self): # print 'GlobalStats.__del__' del self.bulks def get_new_bulk_stats(self, **info): self.bu...
import os import unittest import svn.constants import svn.test_support class TestLocalClient(unittest.TestCase): def test_status(self): with svn.test_support.temp_repo(): with svn.test_support.temp_checkout() as (_, lc): svn.test_support.populate_bigger_file_changes1() ...
"""Self-testing for PyCrypto hash modules""" __revision__ = "$Id$" import sys import unittest from binascii import a2b_hex, b2a_hex # For compatibility with Python 2.1 and Python 2.2 if sys.hexversion < 0x02030000: # Python 2.1 doesn't have a dict() function # Python 2.2 dict() function raises TypeError if y...
#! /usr/bin/env python # -*- coding: utf-8 -*- import unittest import number_to_letter class TestToWord(unittest.TestCase): def setUp(self): self.list_number = [ 1, 100, 2000, 300000, 4000000, 500000000, 999999998, 6000000000, ] self.list_co...
from functools import partial import itertools import numpy as np import pyarrow as pa from . import common DEFAULT_NONE_PROB = 0.3 # TODO: # - test dates and times # - test decimals class BuiltinsGenerator(object): def __init__(self, seed=42): self.rnd = np.random.RandomState(seed) def sprinkl...
import threading import shared import time import sys import os import pickle import tr#anslate from helper_sql import * from helper_threading import * from debug import logger """ The singleCleaner class is a timer-driven thread that cleans data structures to free memory, resends messages when a remote node doesn't...
import numpy as np import pyscf.pbc from pyscf.pbc import cc as pbccc import pyscf.tools as tools import pyscf.pbc.tools.pbc as tools import ase.dft.kpoints import pyscfdump import shutil def run_kccsd(mf): cc = pbccc.KCCSD(mf) cc.verbose = 7 cc.ccsd() return cc def run_krccsd(mf): cc = pbccc.K...
#!/usr/bin/env python3 #script for Loging CSV data from Serial import serial import time import os import sys import os import json ################################################ #code that stops this process from running twice pid = str(os.getpid()) #get process id pidfile = 'pyCSVlog.pid' if 0:#os.path.isfile(p...
"""Dumps a Windows shortcut's property bag to stdout. This is required to confirm correctness of properties that aren't readily available in Windows UI. """ import optparse from pywintypes import IID import sys from win32com.propsys import propsys from win32com.propsys import pscon def BuildPKeyToNameMapping(): "...
import os from mapnik import * base_dir = '/Users/monad/Work/data' out_dir = 'out_usa50_10m' cult10m_dir = os.path.join(base_dir, '10m_cultural', '10m_cultural') phys10m_dir = os.path.join(base_dir, '10m_physical') proj4_usa = '+proj=lcc +lat_1=33 +lat_2=45 +lat_0=39 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no...
VERSION = '2.6-local' import sys if sys.platform == 'cli': from serial.serialcli import * else: import os # chose an implementation, depending on os if os.name == 'nt': #sys.platform == 'win32': from serial.serialwin32 import * elif os.name == 'posix': from serial.serialposix impor...
from time import time, sleep from threading import Thread import socket from collections import deque from tmq import define as td class tsocket: '''The core socket class for Token Message Queue Args: context: the context manager for this socket. Get a context with tmq.tmq_init() functio...
"""Defines the command line method for moving a file""" from __future__ import unicode_literals import logging import sys from django.core.management.base import BaseCommand from storage.brokers.broker import FileMove from storage.models import ScaleFile logger = logging.getLogger(__name__) class Command(BaseComm...
#ООП # Все родительские классы наследуются от класса object class Person(object): last_id=1 # статическое свойство, привязано к классу, а не к отдельным объектам класса '''Имя класса пишем с большой буквы''' def __init__(self, firstname, lastname, phone): # Это специальный метод, который вызывается автоматическ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from six.moves import queue as Queue import time from ansible.errors import * from ansible.executor.task_result import TaskResult from ansible.inventory.host import Host from ansible.inventory.group import Group from ansible.playb...
import numpy import pylab def dumb(f): return f * numpy.pi def pade(f): return f * -0.90585 / (-0.28833 + f * f) def poly3taylor(f): fsq = f * f r = 0.3333333 * numpy.pi ** 3 r *= fsq r += numpy.pi r *= f return r def poly3gradient(f, a=3.736e-01): fsq = f * f r = a * numpy.pi ** 3 r *= fsq ...
import numpy as np import theano from ..utils.activation import * from ..utils.cost import * from ..utils import weights from .base import Layer __all__ = [ "OutputLayer" ] class OutputLayer(Layer): ''' Standard Dense Hidden Layer ''' def __init__( self, numUnits=None, activation=SoftMax, cost=CrossEntropy...
#-*- coding:utf-8 -*- """ This file is part of openexp. openexp 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. openexp is distributed in ...
import asyncio __version__ = '1.2.0' class timeout: """timeout context manager. Useful in cases when you want to apply timeout logic around block of code or in cases when asyncio.wait_for is not suitable. For example: >>> with timeout(0.001): ... async with aiohttp.get('https://github.com'...
""" Quantum ESPRESSO basic parser Author: Evgeny Blokhin TODO: check ibrav settings, parsing might be wrong """ from __future__ import division import os import datetime, time from numpy import dot, array, transpose, linalg from tilde.parsers import Output from tilde.core.electron_structure import Ebands from ase i...
from .main import Searcher def start(): return Searcher() config = [{ 'name': 'searcher', 'order': 20, 'groups': [ { 'tab': 'searcher', 'name': 'searcher', 'label': 'Basics', 'description': 'General search options', 'options': [ ...
# -*- coding: utf-8 -*- # Scrapy settings for DistributedWeiboSpider project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedoc...
import glob, os, sys from astropy.io import fits as pyfits import matplotlib.pyplot as plt from astropy.io import ascii import numpy as np if sys.platform == 'darwin': BASEDIR='/Users/kkozarev/Desktop/MWA_CME_project/test_mwaprep_alignment/' OBSID='1130642936' CHANNEL='113-114' REFCHAN='153-154' FINCHAN='8-14' TIME='0...
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Properties handler :author: Thomas Calmant :copyright: Copyright 2016, Thomas Calmant :license: Apache License 2.0 :version: 0.6.4 .. Copyright 2016 Thomas Calmant Licensed under the Apache License, Version 2.0 (the "License"); you may not use th...
"""Unit tests statistics aggregations.""" from datetime import datetime, timedelta from elasticsearch_dsl import Search from elasticsearch_dsl.query import Ids from invenio_search.proxies import current_search_client from invenio_search.utils import build_alias_name from stats_helpers import create_stats_fixtures d...
""" Extermely under construction. Some parts are copied from https://gist.github.com/he7d3r/f99482f4f54f97895ccb/9205f3271fe8daa2f694f4ce3ba9b29213dbad6c """ from nltk.tokenize import RegexpTokenizer import sys from mw.lib import reverts from pywikibot import xmlreader import pywikibot import re import time import rege...
import copy import json import os import yaml try: from collections import OrderedDict except ImportError: # pragma: no cover from ordereddict import OrderedDict # minimalistic raml loader. Support !include tags, and mapping as OrderedDict class RamlLoader(yaml.SafeLoader): pass def construct_include...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tracker', '0028_auto_20180820_2000'), ] operations = [ migrations.CreateModel( name='Subtopic', fiel...
"""JSONEncoder with dict keys' hook. """ from __future__ import absolute_import from json import JSONEncoder as JSONEncoder_ from json.encoder import encode_basestring_ascii, encode_basestring, floatstr class JSONEncoder(JSONEncoder_): key_hook = None key_default = None def __init__(self, skipkeys=False...
# -*- coding: utf-8 -*- import os import sys import xbmc import xbmcgui import xbmcplugin import xbmcaddon import urllib2 import urlparse import json import re # plugin constants __plugin__ = "plugin.video.sportube" __author__ = "Nightflyer" Addon = xbmcaddon.Addon() # plugin handle handle = int(sys.argv[1]) # uti...
# coding: utf-8 # ## 电影文本情感分类 # [Github地址](https://github.com/lijingpeng/kaggle/tree/master/competitions/Bag_of_Words) # [Kaggle地址](https://www.kaggle.com/c/word2vec-nlp-tutorial/) # # 这个任务主要是对电影评论文本进行情感分类,主要分为正面评论和负面评论,所以是一个二分类问题,二分类模型我们可以选取一些常见的模型比如贝叶斯、逻辑回归等,这里挑战之一是文本内容的向量化,因此,我们首先尝试基于TF-IDF的向量化方法,然后尝试word2vec。 ...
"""Disables an AutoScale Vm Group""" from baseCmd import * from baseResponse import * class disableAutoScaleVmGroupCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "true" """the ID of the autoscale group""" """Required""" self.id = None self.typeInfo['id...
""" Machine limits for Float32 and Float64 and (long double) if available... """ __all__ = ['finfo','iinfo'] from machar import MachAr import numpy.core.numeric as numeric import numpy.core.numerictypes as ntypes from numpy.core.numeric import array import numpy as np def _frz(a): """fix rank-0 --> rank-1""" ...
# -*- coding: utf-8 -*- """Admin section, including Role and Permission authorized.""" from flask import Blueprint, flash, redirect, render_template, request, url_for, abort from flask_login import current_user, login_required, login_user, logout_user from flask_menu import register_menu from goldeneye.extensions impo...
"""Exporter using translate-toolkit""" from __future__ import unicode_literals import string from django.http import HttpResponse import six from translate.misc.multistring import multistring from translate.storage.po import pofile from translate.storage.mo import mofile, mounit from translate.storage.poxliff impor...
from pprint import pprint from threading import Thread from copy import deepcopy from time import time from random import randint from django.conf import settings from django.db import connections from django.test.utils import CaptureQueriesContext from rest_framework.reverse import reverse from rest_framework.test im...
"""Monte Carlo integration and helpers. See the @{$python/contrib.bayesflow.monte_carlo} guide. @@expectation @@expectation_importance_sampler @@expectation_importance_sampler_logspace """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.py...
#! /usr/bin/env python # This script is obsolete -- it is kept for historical purposes only. # # Fix Python source files to use the new class definition syntax, i.e., # the syntax used in Python versions before 0.9.8: # class C() = base(), base(), ...: ... # is changed to the current syntax: # class C(base...
from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from django.views.decorators.cache import cache_page from django.utils import timezone from django.conf import settings from datetime import datetime from datetime import date from icalendar i...
"""The tests for the Template automation.""" import unittest from homeassistant.bootstrap import _setup_component import homeassistant.components.automation as automation from tests.common import get_test_home_assistant class TestAutomationTemplate(unittest.TestCase): """Test the event automation.""" def s...
import win32com.client import os import fnmatch import time import random import zlib from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP doc_type = ".doc" username = "<EMAIL>" password = "testpassword" public_key = """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyXU...