content
stringlengths
4
20k
# coding:utf-8 ''' Created on 2017/12/29. @author: chk01 ''' from practice_one.Company.load_material.utils import * from practice_one.model.utils import * from imblearn.over_sampling import RandomOverSampler def preprocessing(trX, teX, trY, teY): res = RandomOverSampler(ratio={0: 700, 1: 700, 2: 700}) m, w, ...
# coding: utf-8 from flask import current_app, url_for, render_template from flask.ext.babel import gettext as _ from flask_mail import Message from .user import create_auth_token def send_mail(app, msg): mail = app.extensions['mail'] if not mail.default_sender: return mail.send(msg) def signup...
class NumMatrix(object): def __init__(self, matrix): """ initialize your data structure here. :type matrix: List[List[int]] """ self.dp = [range(len(matrix[0])) for i in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[i])): ...
""" Feedforward layers. TODO: write more documentation """ __docformat__ = 'restructedtext en' __authors__ = ("Razvan Pascanu " "KyungHyun Cho " "Caglar Gulcehre ") __contact__ = "Razvan Pascanu <r.pascanu@gmail>" import numpy import copy import theano import theano.tensor as TT from th...
from __future__ import division, absolute_import, print_function import timeit from functools import reduce import numpy as np from numpy import float_ import np.core.fromnumeric as fromnumeric from np.testing.utils import build_err_msg # Fixme: this does not look right. np.seterr(all='ignore') pi = np.pi class ...
import vigra import vigra.graphs as vigraph import pylab import numpy np=numpy import sys import matplotlib import pylab as plt import math from matplotlib.widgets import Slider, Button, RadioButtons def makeWeights(gamma): global hessian,gradmag,gridGraph print "hessian",hessian.min(),hessian.max() print ...
# -*- coding: utf-8 -*- """ markupsafe._constants ~~~~~~~~~~~~~~~~~~~~~ Highlevel implementation of the Markup string. :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ HTML_ENTITIES = { 'AElig': 198, 'Aacute': 193, 'Acirc': 194, 'Agrave': 1...
#!/usr/bin/env python import sys from os import path,getcwd def run(verbosity=1,doctest=False,numpy=True): """Run NetworkX tests. Parameters ---------- verbosity: integer, optional Level of detail in test reports. Higher numbers provide more detail. doctest: bool, optional ...
""" Tests that policy json files import correctly when loading XML """ from nose.tools import assert_equals, assert_raises # pylint: disable=no-name-in-module from xmodule.tests.xml.factories import CourseFactory from xmodule.tests.xml import XModuleXmlImportTest class TestPolicy(XModuleXmlImportTest): """ ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import re from ansible.module_utils.basic import AnsibleModule def a_valid_tap(tap): ...
from __future__ import print_function import unittest import numpy as np from op_test import OpTest class TestSequenceExpand(OpTest): def set_data(self): x_data = np.random.uniform(0.1, 1, [3, 1]).astype('float32') y_data = np.random.uniform(0.1, 1, [8, 1]).astype('float32') y_lod = [[1, ...
"""NMEA 0183 implementation Maintainer: Bob Ippolito The following NMEA 0183 sentences are currently understood:: GPGGA (fix) GPGLL (position) GPRMC (position and time) GPGSA (active satellites) The following NMEA 0183 sentences require implementation:: None really, the others aren't generally u...
import osc.core import osc.oscerr import os from common import GET, PUT, OscTestCase FIXTURES_DIR = os.path.join(os.getcwd(), 'setlinkrev_fixtures') def suite(): import unittest return unittest.makeSuite(TestSetLinkRev) class TestSetLinkRev(OscTestCase): def setUp(self): OscTestCase.setUp(self, co...
from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import GB2312DistributionAnalysis from .mbcssm import GB2312SMModel class GB2312Prober(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) ...
import time import six import libqtile.layout import libqtile.bar import libqtile.widget import libqtile.manager import libqtile.config import libqtile.confreader from .utils import Xephyr class GBConfig: auto_fullscreen = True keys = [] mouse = [] groups = [ libqtile.config.Group("a"), ...
from distutils.errors import DistutilsOptionError from unittest import TestLoader import unittest import sys from pkg_resources import (resource_listdir, resource_exists, normalize_path, working_set, _namespace_packages, add_activation_listener, require, EntryPoint...
"""Miscellaneous utility functions and classes. This module is used internally by Tornado. It is not necessarily expected that the functions and classes defined here will be useful to other applications, but they are documented here in case they are. The one public-facing part of this module is the `Configurable` cl...
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s r...
""" Methods for exporting course data to XML """ import logging from abc import abstractmethod from six import text_type import lxml.etree from xblock.fields import Scope, Reference, ReferenceList, ReferenceValueDict from xmodule.contentstore.content import StaticContent from xmodule.exceptions import NotFoundError fr...
from rpython.annotator.argument import ArgumentsForTranslation, ArgErr from rpython.annotator import model as annmodel from rpython.rtyper import rtuple from rpython.rtyper.error import TyperError from rpython.rtyper.lltypesystem import lltype class ArgumentsForRtype(ArgumentsForTranslation): def newtuple(self, it...
import psycopg2 from django.db.backends.base.schema import BaseDatabaseSchemaEditor class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s USING %(column)s::%(type)s" sql_create_sequence = "CREATE SEQUENCE %(sequence)s" sql_delete_sequence =...
from openerp.tests.common import TransactionCase class TestMedicalMedicament(TransactionCase): def setUp(self): super(TestMedicalMedicament, self).setUp() self.test_gcn = self.env['medical.medicament.gcn'].create({}) self.test_drug_form = self.env.ref('medical_medicament.AEM') def _...
""" Implements plugin related api. To define a new plugin just subclass Plugin, like this. class AuthPlugin(Plugin): pass Then start creating subclasses of your new plugin. class MyFancyAuth(AuthPlugin): capability = ['sign', 'vmac'] The actual interface is duck typed. """ import glob import imp, os.path ...
from qtpy import QtCore, QtGui, QtWidgets from qtpy.QtCore import Signal from qtpy.QtWidgets import QMessageBox from mantidqt.interfacemanager import InterfaceManager from mantidqt.utils.qt import load_ui from .details import MoreDetailsDialog DEFAULT_PLAIN_TEXT = ( """Please enter any additional information abo...
# -*- coding: utf-8 -*- # (c) 2017 Andreas Motl <<EMAIL>> import json from pkg_resources import resource_filename from jinja2 import Template from twisted.logger import Logger from grafana_api_client import GrafanaPreconditionFailedError, GrafanaClientError from kotori.daq.services.mig import MqttInfluxGrafanaService ...
from __future__ import unicode_literals from django.contrib.syndication.views import Feed as BaseFeed from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed class GeoFeedMixin(object): """ This mixin provides the necessary routines for SyndicationFeed subclasses to produce simple GeoRSS or W3C G...
"""provides runtime services for templates, including Context, Namespace, and various helper functions.""" from mako import exceptions, util import __builtin__, inspect, sys class Context(object): """provides runtime namespace, output buffer, and various callstacks for templates.""" def __init__(self, buffer,...
# -*- 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 from django.contrib.auth import get_user_model User = get_user_model() user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name) user_mod...
""" Define names for built-in types that aren't directly accessible as a builtin. """ import sys # Iterators in Python aren't a matter of type but of protocol. A large # and changing number of builtin types implement *some* flavor of # iterator. Don't check the type! Use hasattr to check for both # "__iter__" and "...
from openerp import models, fields, api class Resource(models.Model): _name= 'project.event.resource' _inherits = {'resource.resource': 'resource_id'} @api.onchange('resource_type') def onchange_resource_type(self): self.unlimited = False @api.multi def name_get(self): result...
# encoding: utf-8 from django.contrib.admin import site, ModelAdmin from globalshorturls.models import Shorturl from django.forms import ModelForm from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec from django.utils.translation import ugettext as _ from django.utils.encoding import smart_unicode...
""" Check the speed of the conjugate gradient solver. """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import assert_equal try: from scipy import linalg, sparse from scipy.sparse.linalg import cg, minres, spsolve except ImportError: pass try: ...
# Title: AWG - Akemi's Word Game # Files: AWG_App_py2.py; SINGLE.TXT (dictionary words file) # Tested: python 2.61 # Info: Akemi's Word Game: The game where you try and guess the computer's randomly # selected word! Each letter appears only once. import sys import random import tkinter import tkinter.messa...
"""Display objects for the different kinds of charts. Not intended for end users, use the methods in __init__ instead.""" import warnings from graphy.backends.google_chart_api import util class BaseChartEncoder(object): """Base class for encoders which turn chart objects into Google Chart URLS. Object attribu...
from __future__ import absolute_import import codecs from uuid import uuid4 from io import BytesIO from .packages import six from .packages.six import b from .fields import RequestField writer = codecs.lookup('utf-8')[3] def choose_boundary(): """ Our embarassingly-simple replacement for mimetools.choose_b...
from django.conf.urls import patterns, url from . import views urlpatterns = patterns('geoparser_app.views', url(r'^$', views.index, name='index'), url(r'^extract_text/(?P<file_name>\S+)$', views.extract_text, name='extract_text'), url(r'^find_location/(?P<file_name>\S+)', views.find_location, name='find...
""" Tests for stuff in django.utils.datastructures. """ import copy import pickle import warnings from django.test import SimpleTestCase from django.utils.datastructures import (DictWrapper, ImmutableList, MultiValueDict, MultiValueDictKeyError, MergeDict, SortedDict) from django.utils import six class SortedDi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.CreateModel( name='CustomArticle', fields=[ ...
from openerp.osv import fields, osv class account_sequence_installer(osv.osv_memory): _name = 'account.sequence.installer' _inherit = 'res.config.installer' _columns = { 'name': fields.char('Name',size=64, required=True), 'prefix': fields.char('Prefix',size=64, help="Prefix value of the re...
"""Top-level presubmit script for auto-bisect. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit API. """ import imp import subprocess import os # Paths to bisect config files relative to src/tools. CONFIG_FILES = [ 'auto_bisect/config.cfg', 'run-perf-te...
import pipes import os import string import unittest from test.support import TESTFN, run_unittest, unlink, reap_children if os.name != 'posix': raise unittest.SkipTest('pipes module only works on posix') TESTFN2 = TESTFN + "2" # tr a-z A-Z is not portable, so make the ranges explicit s_command = 'tr %s %s' % (s...
# -*- coding: utf-8 -*- from Components.Converter.Converter import Converter from enigma import iServiceInformation, iPlayableService, iPlayableServicePtr, eServiceReference from ServiceReference import resolveAlternate from Components.Element import cached class ServiceName(Converter, object): NAME = 0 PROVIDER = 1...
from __future__ import absolute_import import os import sys def bindir_path(bindir, path): """Find the executable to use. :param bindir: Directory with binaries :param path: Name of the executable to run :return: Full path to the executable to run """ valpath = os.path.join(bindir, path) ...
import unittest from django.db import models from django.test.client import Client from django.contrib.auth.models import User, Group from django.contrib.comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from actstream.signals import ...
"""Stats Accumulator ops python wrappers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from tensorflow.contrib.boosted_trees.python.ops import batch_ops_utils # pylint: disable=unused-import from tensorflow.contrib.boosted_trees.python.ops imp...
""" The `compat` module provides support for backwards compatibility with older versions of Django/Python, and compatibility wrappers around optional packages. """ # flake8: noqa from __future__ import unicode_literals import django from django.conf import settings from django.db import connection, transaction from d...
class EmptyParent:pass class SomeParent: PARENT_CLASS_FIELD = 42 def __init__(self): self.parent_instance_field = "egg" def parent_func(self): pass class ChildWithDependencies(SomeParent, EmptyParent): CLASS_FIELD_FOO = 42 CLASS_FIELD_DEPENDS_ON_CLASS_FIELD_FOO = CLASS_FIELD_FOO...
from core import perf_benchmark from telemetry import benchmark from telemetry.core import discover from telemetry import story from measurements import skpicture_printer def _MatchPageSetName(story_set_name, story_set_base_dir): story_sets = discover.DiscoverClasses(story_set_base_dir, story_set_base_dir, ...
import sys import os.path from urllib2 import urlopen, HTTPError import time import re def get_app_ids(appstring): index = '"appid":' substring = 0 while True: substring = appstring.find(index, substring) if substring == -1: return pattern = re.compile('(\"appid":)([0-9...
#!/usr/bin/env python # -*- encoding: utf-8 -*- from os.path import join from setuptools import setup, find_packages import pygithub3 # Odd hack to get 'python setup.py test' working on py2.7 try: import multiprocessing import logging except ImportError: pass setup( name=pygithub3.__name__, vers...
""" Model-Based Configuration ========================= This app allows other apps to easily define a configuration model that can be hooked into the admin site to allow configuration management with auditing. Installation ------------ Add ``config_models`` to your ``INSTALLED_APPS`` list. Usage ----- Create a sub...
from wheel import signatures from wheel.signatures import djbec, ed25519py from wheel.util import binary def test_getlib(): signatures.get_ed25519ll() def test_djbec(): djbec.dsa_test() djbec.dh_test() def test_ed25519py(): kp0 = ed25519py.crypto_sign_keypair(binary(' '*32)) kp = ed25519p...
import os, sys sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from Util import * process_names = {} thread_thislock = {} thread_blocktime = {} lock_waits = {} # long-lived stats on (tid,lock) blockage elapsed time process_names = {} # long-lived pid-to-execname mappin...
from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch from django.http import HttpRequest from django.test import TestCase from django.utils import simplejson as json class NamespacedViewsTestCase(TestCase): urls = 'namespaced.api.urls' def test_urls(self): ...
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel 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 ...
""" Tools for sending email. """ # Import utilities from django.template.loader import render_to_string from django.utils.encoding import force_bytes, force_text from django.contrib.auth.tokens import default_token_generator from django.core.mail import send_mail from django.utils.http import urlsafe_base64_encode # I...
# -*- coding: utf-8 -*- import numpy as np def surv_area(durations, events=None, absolute=False): ''' Parameters: durations - array of event times (must be greater than zero) events - array of event indicators (1/True for event, 0/False for censored) absolute - if True, returns the actual area. Ot...
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Linear Regression Example ========================================================= This example uses the only the first feature of the `diabetes` dataset, in order to illustrate a two-dimensional plot of this regre...
""" Django settings for slack announcement approval project, on Heroku. For more info, see: https://github.com/heroku/heroku-django-template For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/...
""" A collection of utility routines and classes used by the spatial backends. """ def gqn(val): """ The geographic quote name function; used for quoting tables and geometries (they use single rather than the double quotes of the backend quotename function). """ if isinstance(val, basestring): ...
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from django.http import Http404 from django.views.decorators.csrf import ensure_csrf_cookie from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, redirect, HttpResponse, get_object_or_404 from django.template import...
from django.contrib import admin from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext from django.contrib.comments import get_model from django.contrib.comments.views.moderation import perform_flag, perform_approve, perform_delete class CommentsAdmin(adm...
from __future__ import (absolute_import, division, print_function) import time from ansible.module_utils.connection import Connection checkpoint_argument_spec_for_objects = dict( auto_publish_session=dict(type='bool'), wait_for_task=dict(type='bool', default=True), state=dict(type='str', choices=['presen...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, unescapeHTML, ) class SteamIE(InfoExtractor): _VALID_URL = r"""(?x) https?://store\.steampowered\.com/ (agecheck/)? (?P<urltype>video|app)/ #If the pa...
# coding=utf-8 import logging import traceback import flask_login from flask_accept import accept from flask_restx import Resource from flask_restx import abort from flask_restx import fields from mycodo.databases.models import Output from mycodo.databases.models import OutputChannel from mycodo.databases.models.outp...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re from ansible.module_utils.six.moves import reduce from ansible.module_utils.basic import bytes_to_human from ansible.module_utils.facts.utils import get_file_content, get_mount_size from ansible.module_utils.facts.har...
import warnings from typing import Any __all__ = ['Event', 'InternalEvent', 'MetaEvent'] class Event: """ An event with a name and (optionally) some data passed as named parameters. The list of parameters can be obtained using *dir(event)*. Notice that *name* and *data* are reserved names. If a *del...
import math, struct from gimpfu import * class pixel_fetcher: def __init__(self, drawable): self.col = -1 self.row = -1 self.img_width = drawable.width self.img_height = drawable.height self.img_bpp = drawable.bpp s...
import sys import platform import _pytest._code import pytest def runpdb_and_get_report(testdir, source): p = testdir.makepyfile(source) result = testdir.runpytest_inprocess("--pdb", p) reports = result.reprec.getreports("pytest_runtest_logreport") assert len(reports) == 3, reports # setup/call/teard...
import numpy as np from scipy import sparse from scipy import linalg from scipy import stats from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn...
from oslo_serialization import jsonutils as json from six.moves.urllib import parse as urllib from tempest.lib.common import rest_client from tempest.lib import exceptions as lib_exc from tempest.lib.services.volume import base_client class GroupsClient(base_client.BaseClient): """Client class to send CRUD Volum...
#!/usr/bin/env python2 import sys import zlib from lzw import lzwdecode from ascii85 import ascii85decode, asciihexdecode from runlength import rldecode from psparser import PSException, PSObject from psparser import LIT, KWD, STRICT LITERAL_CRYPT = LIT('Crypt') # Abbreviation of Filter names in PDF 4.8.6. "Inline Im...
#!/usr/bin/env python import os, sys, re, urllib2, cookielib, string from urllib import urlencode from urllib2 import urlopen from copy import copy import BeautifulSoup import htmlentitydefs import socket socket.setdefaulttimeout(15) class ParseException(Exception): pass ## # Removes HTML or XML character refere...
import unittest from mock import patch from rhsm.certificate import CertificateException from rct.cert_commands import RCTCertCommand from subscription_manager.cli import InvalidCLIOptionError class RCTCertCommandTests(unittest.TestCase): def test_file_arg_required(self): command = RCTCertCommand() ...
"""Batch reader to seq2seq attention model, with bucketing support.""" from collections import namedtuple from random import shuffle from threading import Thread import time import numpy as np import six from six.moves import queue as Queue from six.moves import xrange import tensorflow as tf import data ModelInput...
""" Module that provides a connection to the ModuleStore specified in the django settings. Passes settings.MODULESTORE as kwargs to MongoModuleStore """ from __future__ import absolute_import from importlib import import_module from django.conf import settings if not settings.configured: settings.configure() fro...
from django.template import defaultfilters from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ungettext_lazy from horizon import forms from horizon import tables from openstack_dashboard import api from openstack_dashboard import policy from openstack_dashboard import record_a...
import sys import textwrap import pip.download from pip.basecommand import Command, SUCCESS from pip.util import get_terminal_size from pip.log import logger from pip.backwardcompat import xmlrpclib, reduce, cmp from pip.exceptions import CommandError from pip.status_codes import NO_MATCHES_FOUND from pip._vendor imp...
#!/usr/bin/env python3 import sys import os import collections import datetime import flask_mail import boto.s3.key sys.path.append(os.getcwd()) import app import identity import lookups app.app.config['SERVER_NAME'] = 'cv.democracyclub.org.uk' # Get list of when last sent last_sent_by_email = lookups.candidate_ma...
import re re._MAXCACHE = 1000 remove = re.compile(u"[\.]+", re.U) # dots delimiters = re.compile(u"[\W]+", re.U) # anything except a-z, A-Z and _ delimiters_begin = re.compile(u"^[\W]+", re.U) # anything except a-z, A-Z and _ delimiters_end = re.compile(u"[\W]+$", re.U) # anything ...
from django.template import RequestContext, TemplateSyntaxError from django.test import RequestFactory, SimpleTestCase, override_settings from django.urls import NoReverseMatch, resolve from ..utils import setup @override_settings(ROOT_URLCONF='template_tests.urls') class UrlTagTests(SimpleTestCase): request_fac...
from __future__ import division, absolute_import, print_function import sys import collections import pickle from os import path import numpy as np from numpy.compat import asbytes from numpy.testing import ( TestCase, run_module_suite, assert_, assert_equal, assert_array_equal, assert_array_almost_equal, ass...
from shop.models.ordermodel import OrderExtraInfo, Order from django.test.testcases import TestCase from django.contrib.auth.models import User from shop.tests.util import Mock from shop.shop_api import ShopAPI from decimal import Decimal class ShopApiTestCase(TestCase): def setUp(self): self.user = User....
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import usb vendor = 0x054c product = 0x0268 timeout = 5000 passed_value = 0x03f5 def find_sixaxes(): res = [] for bus in usb.busses(): for dev in bus.devices: if dev.idVendor == vendor and dev.idProduct == product: res.append(dev) return r...
__author__ = 'Ruslan Spivak <<EMAIL>>' from slimit import ast class ECMAVisitor(object): def __init__(self): self.indent_level = 0 def _make_indent(self): return ' ' * self.indent_level def visit(self, node): method = 'visit_%s' % node.__class__.__name__ return getattr(...
""" .. module:: I18stxm_loader :platform: Unix :synopsis: A class for loading I18's stxm data .. moduleauthor:: Aaron Parsons <<EMAIL>> """ from savu.plugins.loaders.multi_modal_loaders.base_i18_multi_modal_loader \ import BaseI18MultiModalLoader from savu.data.data_structures.data_type import FabIO from ...
#!/usr/bin/env python """ Translation from a C code posted to a forum on the Internet. @translator Thomas Schmid """ from array import array def reflect(crc, bitnum): # reflects the lower 'bitnum' bits of 'crc' j=1 crcout=0 for b in range(bitnum): i=1<<(bitnum-1-b) i...
#!/usr/bin/env python # This will create golden files in a directory passed to it. # A Test calls this internally to create the golden files # So it can process them (so we don't have to checkin the files). # Ensure msgpack-python and cbor are installed first, using: # sudo apt-get install python-dev # sudo apt-g...
from __future__ import unicode_literals, division, absolute_import import logging from requests.auth import AuthBase from flexget import plugin from flexget.entry import Entry from flexget.event import event from flexget.utils import requests from flexget.utils.imdb import extract_id from flexget.utils.soup import ge...
from __future__ import print_function # $example on$ from pyspark.ml.feature import NGram # $example off$ from pyspark.sql import SparkSession if __name__ == "__main__": spark = SparkSession\ .builder\ .appName("NGramExample")\ .getOrCreate() # $example on$ wordDataFrame = spark.c...
from django.db import connections, models from django.test import TestCase, mock from django.test.utils import override_settings from .tests import IsolateModelsMixin class TestRouter(object): """ Routes to the 'other' database if the model name starts with 'Other'. """ def allow_migrate(self, db, ap...
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import base64 import os import random import re _default_keep_words = [ 'AAAAAAAAAAA=', 'analysis', 'anonfun', 'apply', 'beta', 'class', 'classes', '...
"""Tests for QueueRunner.""" import time import tensorflow.python.platform import tensorflow as tf class QueueRunnerTest(tf.test.TestCase): def testBasic(self): with self.test_session() as sess: # CountUpTo will raise OUT_OF_RANGE when it reaches the count. zero64 = tf.constant(0, dtype=tf.int64)...
"""Message related utilities. Note: request.connection.write/read are used in this module, even though mod_python document says that they should be used only in connection handlers. Unfortunately, we have no other options. For example, request.write/read are not suitable because they don't allow direct raw bytes writi...
# -*- coding: utf-8 -*- """ *************************************************************************** ShortestPathPointToLayer.py --------------------- Date : December 2016 Copyright : (C) 2016 by Alexander Bruy Email : alexander dot bruy at gmail dot com...
import Quartz from AppKit import NSEvent, NSScreen from .base import PyMouseMeta, PyMouseEventMeta pressID = [None, Quartz.kCGEventLeftMouseDown, Quartz.kCGEventRightMouseDown, Quartz.kCGEventOtherMouseDown] releaseID = [None, Quartz.kCGEventLeftMouseUp, Quartz.kCGEventRightMouseUp, Quartz.kCGE...
# -*- coding:utf-8 -*- #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- from __future__ import print_function import os import sys import select import tempfile import pty import itertools import re import fn...
class SecurityGroup(object): def __init__(self, connection=None): self.name = None self.owner_alias = None def __repr__(self): return 'SecurityGroup(%s, %s)' % (self.name, self.owner_alias) def startElement(self, name, attrs, connection): pass def endElement(self, name...
import logging import six.moves.urllib.parse as urlparse import swiftclient from django.conf import settings from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon.utils.memoized import memoized # noqa from openstack_dashboard.api import base from openstack_dashboard.op...
#coding=utf-8 from flask import Flask, redirect, render_template, request, Response from codepy import menulog import anydbm as dbm import shelve import os, sys import urllib from datetime import datetime import time import urllib2 import hashlib app = Flask(__name__) visit = 0 visitHome = 0 startTime = time.time() t...