content
string
""" Wrapper for loading templates from the filesystem. """ from django.conf import settings from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader from django.utils._os import safe_join class Loader(BaseLoader): is_usable = True def get_template_sources(self, temp...
import unittest from idl_lexer import IDLLexer from idl_ppapi_lexer import IDLPPAPILexer # # FileToTokens # # From a source file generate a list of tokens. # def FileToTokens(lexer, filename): with open(filename, 'rb') as srcfile: lexer.Tokenize(srcfile.read(), filename) return lexer.GetTokens() # # TextT...
"""Tokenization help for Python programs. generate_tokens(readline) is a generator that breaks a stream of text into Python tokens. It accepts a readline-like method which is called repeatedly to get the next line of input (or "" for EOF). It generates 5-tuples with these members: the token type (see token.py) ...
# -*- coding: utf-8 -*- """ *************************************************************************** __init__.py --------------------- Date : May 2016 Copyright : (C) 2016 by Victor Olaya Email : volayaf at gmail dot com *********************************...
import numpy as np import glob import struct import pdb import re class Nchilada(object): def __init__(self, filename): self.codedict = {1: 'int8', 2: 'uint8', 3: 'int16', 4: 'uint16', 5: 'int32', ...
""" 该文件是游戏的一些设置选项 """ class Settings(): """ 存储游戏的所有设置的类 """ def __init__(self): """ 初始化游戏的设置 """ self.screen_width = 1920 self.screen_height = 900 self.bg_color = (230, 230, 230) # 飞船设置 self.ship_limit = 3 # 设置子弹 self.bullet_width = 3 se...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} import re from ansible.module_utils.network.nxos.nxos import get_config, load_config from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args from ansible....
import io import os import sys import unittest class Test_TestProgram(unittest.TestCase): def test_discovery_from_dotted_path(self): loader = unittest.TestLoader() tests = [self] expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) self.wasRun = False ...
""" ======================================================================= Shrinkage covariance estimation: LedoitWolf vs OAS and max-likelihood ======================================================================= When working with covariance estimation, the usual approach is to use a maximum likelihood estimator,...
""" Tests for utilities that parse event logs. """ from opaque_keys.edx.locator import CourseLocator import edx.analytics.tasks.util.opaque_key_util as opaque_key_util from edx.analytics.tasks.tests import unittest VALID_COURSE_ID = unicode(CourseLocator(org='org', course='course_id', run='course_run')) VALID_LEGAC...
import os, shutil, sys, time from . import globals, builder if sys.version_info.major == 3: from tkinter import * else: from Tkinter import * # from tkFileDialog import * from PIL import Image, ImageTk class ScrollIt(): def __init__(self): self.image1 = Image.open(mGui.btn2text.get()[9:] + '-sc...
"""Public API functions for the event system. """ from __future__ import absolute_import from .. import util, exc from .base import _registrars from .registry import _EventKey CANCEL = util.symbol('CANCEL') NO_RETVAL = util.symbol('NO_RETVAL') def _event_key(target, identifier, fn): for evt_cls in _registrars[...
"""Stateless random ops which take seed as a tensor input.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.ops import gen_stateless_random_ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import ...
#!/bin/env python __author__ = "John Hover" __copyright__ = "2017 John Hover" __credits__ = [] __license__ = "GPL" __version__ = "0.9.1" __maintainer__ = "John Hover" __email__ = "<EMAIL>" __status__ = "Production" import logging import random import string class InfoConnectionFailure(Exception): ''' Network...
""" For a given aws account, go through all un-attached volumes and tag them. """ import boto import boto.utils import argparse import logging import subprocess import time import os from os.path import join, exists, isdir, islink, realpath, basename, dirname import yaml # needs to be pip installed import netaddr LO...
""" ======================================================================= Shrinkage covariance estimation: LedoitWolf vs OAS and max-likelihood ======================================================================= The usual estimator for covariance is the maximum likelihood estimator, :class:`sklearn.covariance.Em...
from indra.statements import * from bioagents.mra.model_diagnoser import ModelDiagnoser from indra.assemblers.pysb import PysbAssembler from nose.plugins.attrib import attr drug = Agent('PLX4720') raf = Agent('RAF', db_refs={'FPLX': 'RAF'}) mek = Agent('MEK', db_refs={'FPLX': 'MEK'}) erk = Agent('ERK', db_refs={'FPLX...
"""CallTips.py - An IDLE Extension to Jog Your Memory Call Tips are floating windows which display function, class, and method parameter and docstring information when you type an opening parenthesis, and which disappear when you type a closing parenthesis. """ import re import sys import types from idlelib import C...
from nova.api.validation import parameter_types reserve = { 'type': 'object', 'properties': { 'reserve': parameter_types.none, }, 'required': ['reserve'], 'additionalProperties': False, } unreserve = { 'type': 'object', 'properties': { 'unreserve': parameter_types.none, ...
import os from airflow import models from airflow.providers.google.cloud.operators.text_to_speech import CloudTextToSpeechSynthesizeOperator from airflow.providers.google.cloud.operators.translate_speech import CloudTranslateSpeechOperator from airflow.utils import dates GCP_PROJECT_ID = os.environ.get("GCP_PROJECT_I...
import unittest import getpass import os import shutil import time import tempfile from nose.plugins.skip import SkipTest from ansible.runner.action_plugins.synchronize import ActionModule as Synchronize class FakeRunner(object): def __init__(self): self.connection = None self.transport = None ...
"""Unittest for chrome_messages_json.py. """ import os import sys if __name__ == '__main__': sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) import unittest import StringIO from grit import grd_reader from grit import util from grit.tool import build class ChromeMessagesJsonFormatUnittest(unitte...
""" Query subclasses which provide extra functionality beyond simple data retrieval. """ from django.core.exceptions import FieldError from django.db import connections from django.db.models.query_utils import Q from django.db.models.sql.constants import ( CURSOR, GET_ITERATOR_CHUNK_SIZE, NO_RESULTS, ) from django...
#!/usr/bin/env python import sys from os import path, mkdir from vipsCC import * sizes = { 'ldpi':3, 'mdpi':4, 'hdpi':6, 'xhdpi':8, 'xxhdpi':12, 'xxxhdpi':16 } if ( len(sys.argv) < 2): print """ (H)Andy Image Resize ----------------------------------- This program resizes images into ldpi to xxxhdpi ** I...
class Command: def __init__(self, args, redirects): self.args = list(args) self.redirects = list(redirects) def __repr__(self): return 'Command(%r, %r)' % (self.args, self.redirects) def __eq__(self, other): if not isinstance(other, Command): return False ...
{ 'name': 'Marketing Campaign - Demo', 'version': '1.0', 'depends': ['marketing_campaign', 'crm', ], 'author': 'OpenERP SA', 'category': 'Marketing', 'description': """ Demo data for the module marketing_campaign. ============================================ Creates demo da...
"""Handle AMQP Heartbeats""" import logging import pika.exceptions from pika import frame LOGGER = logging.getLogger(__name__) class HeartbeatChecker(object): """Sends heartbeats to the broker. The provided timeout is used to determine if the connection is stale - no received heartbeats or other activit...
#! /bin/env python import sys from optparse import OptionParser import copy import matplotlib matplotlib.use('Agg') import pylab import scipy.optimize import numpy from numpy import array import dadi import os #call ms program from within dadi, using optimized parameters (converted to ms units) core = "-n 1 0.922 -n 2...
""" ViewSets are essentially just a type of class based view, that doesn't provide any method handlers, such as `get()`, `post()`, etc... but instead has actions, such as `list()`, `retrieve()`, `create()`, etc... Actions are only bound to methods at the point of instantiating the views. user_list = UserViewSet.a...
"""Jobs operating on explorations that can be used for production tests. To use these jobs, first need to register them in jobs_registry (at the moment they are not displayed there to avoid accidental use).""" from core import jobs from core.domain import exp_domain from core.domain import exp_services from core.domai...
import datetime from autobahn.twisted.wamp import ApplicationSession class Component(ApplicationSession): """ A simple time service application component. """ def onJoin(self, details): def utcnow(): now = datetime.datetime.utcnow() return now.strftime("%Y-%m-%dT%H:%M:%SZ") ...
"""Tests for License package""" import logging import json from uuid import uuid4 from random import shuffle from tempfile import NamedTemporaryFile import factory from factory.django import DjangoModelFactory from django.test import TestCase from django.test.client import Client from django.test.utils import overrid...
#!/usr/bin/python # """ Reset an Protocol in the database to 0 """ import sys import yaml from optparse import OptionParser def reset_protocol(file, dest, name, attributes=None): try: with open(file, 'r') as stream: database = yaml.load(stream) except Exception, ex: print "Excepti...
import uuid from django.http import HttpRequest from django.test import TestCase from corehq.apps.domain.shortcuts import create_domain from corehq.apps.reports.cache import CacheableRequestMixIn, request_cache from corehq.apps.users.models import WebUser class MockReport(CacheableRequestMixIn): def __init__(sel...
from __future__ import generators import sys, types import warnings from twisted.python import reflect, failure, log from twisted.python.compat import adict from twisted.internet import defer from twisted.trial import itrial, util import zope.interface as zi #*********************************************************...
import os, sys, thread, time sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf script -s sctop.py [comm] [interval]\n"; for_comm = None default_interval = 3 interval = default_inter...
"""Tests for tensorflow.ops.tf.MatrixTriangularSolve.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import numpy as np from tensorflow.compiler.tests import xla_test from tensorflow.python.framework import constant_op from tensorflow...
from boto.sdb.db.property import Property from boto.sdb.db.key import Key from boto.sdb.db.query import Query import boto from boto.compat import filter class ModelMeta(type): "Metaclass for all Models" def __init__(cls, name, bases, dict): super(ModelMeta, cls).__init__(name, bases, dict) # M...
import time from openerp.osv import fields, osv class account_analytic_journal_report(osv.osv_memory): _name = 'account.analytic.journal.report' _description = 'Account Analytic Journal' _columns = { 'date1': fields.date('Start of period', required=True), 'date2': fields.date('End of peri...
import time from report import report_sxw from osv import osv from tools.translate import _ from report import pyPdf class amd_computadoras_sale(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(amd_computadoras_sale, self).__init__(cr, uid, name, context=context) self.localc...
# -*- coding: utf-8 -*- from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import EmailUser class UserCreationForm(forms.ModelForm): """ A form for creating a new user, including the required email and passw...
""" NTLM authenticating pool, contributed by erikcederstran Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 """ try: from http.client import HTTPSConnection except ImportError: from httplib import HTTPSConnection from logging import getLogger from ntlm import ntlm from urllib3 import HTT...
from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import decimal class ScriptAddress2Test(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 3 self.setup_clean_chain = False def setup_network(self): self...
#!/usr/bin/python from operator import add from simplecv.core.camera import Camera from simplecv.display import Display from simplecv.factory import Factory cam = Camera() display = Display((800,600)) counter = 0 # load the cascades face_cascade = HaarCascade("face") nose_cascade = HaarCascade("nose") stache = Image...
from django.test import TestCase from django.core.urlresolvers import reverse from django.contrib.auth.models import User from mock import patch, call from ethicsapplication.models import EthicsApplication class IndexViewTestCase(TestCase): def setUp(self): self.user = User.objects.create_user...
import errno import logging import os import re from django.conf import settings from pootle.core.log import store_log, STORE_RESURRECTED from pootle.core.utils.timezone import datetime_min from pootle_app.models.directory import Directory from pootle_language.models import Language from pootle_store.models import St...
from __future__ import absolute_import from pychron.mv.locator import Locator class DiodeLocator(Locator): pass # ============= EOF =============================================
#!/usr/bin/python import os import sys import socket import struct from optparse import OptionParser sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/lib/python") parser = OptionParser() parser.add_option("-d", "--destip", dest="dest_addr", help="Destination IP for messages picked up from local socket", default="1...
"""Base classes for formatters. """ import abc import six @six.add_metaclass(abc.ABCMeta) class Formatter(object): @abc.abstractmethod def add_argument_group(self, parser): """Add any options to the argument parser. Should use our own argument group. """ @six.add_metaclass(abc.AB...
from django.core.exceptions import SuspiciousOperation from django.shortcuts import get_object_or_404 from django.utils import translation from django.utils.translation import ugettext_lazy as _ from igdectk.rest.handler import * from igdectk.rest.response import HttpResponseRest from main.cache import cache_manager ...
from optparse import OptionParser import pytest from apache.aurora.common.cluster import Cluster from apache.aurora.common.cluster_option import ClusterOption from apache.aurora.common.clusters import Clusters CLUSTER_LIST = Clusters(( Cluster(name='smf1'), Cluster(name='smf1-test'), )) def cluster_provider(na...
"""Python wrapper for prefetching_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.ops import iterator_ops from tensorflow.python.data.util import structure from tensorflow...
''' fs.contrib.tahoelafs ==================== This modules provides a PyFilesystem interface to the Tahoe Least Authority File System. Tahoe-LAFS is a distributed, encrypted, fault-tolerant storage system: http://tahoe-lafs.org/ You will need access to a Tahoe-LAFS "web api" service. Example (it wil...
# -*- coding: utf-8 -*- """ BR-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, CharField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ ...
""" Helper class for creating decision responses. """ class Layer1Decisions(object): """ Use this object to build a list of decisions for a decision response. Each method call will add append a new decision. Retrieve the list of decisions from the _data attribute. """ def __init__(self): ...
""" FastCGI (or SCGI, or AJP1.3 ...) server that implements the WSGI protocol. Uses the flup python package: http://www.saddi.com/software/flup/ This is an adaptation of the flup package to add FastCGI server support to run Django apps from Web servers that support the FastCGI protocol. This module can be run standal...
class InternalFlowException(Exception): pass class ReturnException(InternalFlowException): def __init__(self, value): self._value = value @property def value(self): return self._value class BreakException(InternalFlowException): pass class ContinueException(InternalFlowExcepti...
#!/usr/bin/env python # -*- coding: utf-8 -*- import rospy from nav_msgs.msg import Odometry from geometry_msgs.msg import Twist from geometry_msgs.msg import PoseStamped from tf.transformations import euler_from_quaternion import numpy as np def minAngle(ang): return np.arctan2(np.sin(ang), np.cos(ang)) def ori...
from django.conf.urls import patterns, url from django.conf import settings urlpatterns = patterns( 'shoppingcart.views', url(r'^postpay_callback/$', 'postpay_callback'), # Both the ~accept and ~reject callback pages are handled here url(r'^receipt/(?P<ordernum>[0-9]*)/$', 'show_receipt'), url(r'^don...
""" imikolov's simple dataset. This module will download dataset from http://www.fit.vutbr.cz/~imikolov/rnnlm/ and parse training set and test set into paddle reader creators. """ import paddle.v2.dataset.common import collections import tarfile __all__ = ['train', 'test', 'build_dict'] URL = 'http://www.fit.vutbr....
import Muon.GUI.Common.utilities.algorithm_utils as algorithm_utils from Muon.GUI.Common.utilities.run_string_utils import run_list_to_string from Muon.GUI.Common.muon_pair import MuonPair from typing import Iterable def calculate_group_data(context, group, run, rebin, workspace_name, periods): processed_data = g...
from django.http.cookie import SimpleCookie, parse_cookie from django.http.request import ( HttpRequest, QueryDict, RawPostDataException, UnreadablePostError, ) from django.http.response import ( BadHeaderError, FileResponse, Http404, HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, HttpResponse...
from nova.cells import opts as cells_opts from nova.cells import rpcapi as cells_rpcapi from nova import db from nova import exception from nova.network import model as network_model from nova.objects import instance_info_cache from nova.tests.objects import test_objects fake_info_cache = { 'created_at': None, ...
import datetime from peewee import * from pymongo import MongoClient from .config import Config database = Config.DATABASE # monkey patch the DateTimeField to add support for the isoformt which is what # peewee exports as from DataSet DateTimeField.formats.append('%Y-%m-%dT%H:%M:%S') DateField.formats.append('%Y-%m-...
from __future__ import unicode_literals, absolute_import from django.test import SimpleTestCase from django.test import override_settings from ci.tests import utils as test_utils from client import JobRunner, BaseClient from client.tests import utils import os, platform from distutils import spawn from mock import patc...
CONTINUE = (100, "Continue", "This means that the server has received the request headers, and that the client should proceed to send the request body (in the case of a request for which a body needs to be sent; for example, a POST request). If the request body is large, send...
class ModuleDocFragment(object): # Standard cloudstack documentation fragment DOCUMENTATION = ''' options: api_key: description: - API key of the CloudStack API. required: false default: null api_secret: description: - Secret key of the CloudStack API. required: false de...
"""This requires CGAL mesher applied to series of surfaces. See readme.txt for details. """ from __future__ import print_function # Use FEniCS for Finite Element import fenics as d # Useful to import the derivative separately from dolfin import dx # Useful numerical libraries import numpy as N import matplotlib mat...
from statsmodels.tools.eval_measures import rmse from copy import deepcopy import numpy as np import shlex import os from config import SPEC_DIR import respy def get_est_log_info(): """ Get the choice probabilities. """ with open('est.respy.info') as in_file: for line in in_file.readlines(): ...
import sys import logging import inspect import traceback from core.logger import logger formatter = logging.Formatter("%(asctime)s [ProxyPlugins] %(message)s", datefmt="%Y-%m-%d %H:%M:%S") log = logger().setup_logger("ProxyPlugins", formatter) class ProxyPlugins: ''' This class does some magic so that all we...
import numpy as np import pytest import importlib import theano import lasagne from lasagne.utils import floatX def conv2d(input, kernel, border_mode): output = np.zeros((input.shape[0], kernel.shape[0], input.shape[2] + kernel.shape[2] - 1, in...
"""Verify that starting dashd with -h works as expected.""" import subprocess from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal class HelpTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = ...
class ModuleDocFragment(object): # Dimension Data ("wait-for-completion" parameters) doc fragment DOCUMENTATION = ''' options: wait: description: - Should we wait for the task to complete before moving onto the next. required: false default: false wait_time: description: - The ...
import glob from optparse import OptionParser import subprocess import os import os.path import shutil import sys version = 'build-all.py, version 0.01' build_dir = '../all-kernels' make_command = ["vmlinux", "modules"] make_env = os.environ make_env.update({ 'ARCH': 'arm', 'CROSS_COMPILE': 'arm-none-...
import sys, os, re, subprocess, codecs, optparse CMD_PYTHON = sys.executable QOOXDOO_PATH = '../qooxdoo-master' QX_PYLIB = "tool/pylib" ## # A derived OptionParser class that ignores unknown options (The parent # class raises in those cases, and stops further processing). # We need this, as we are only interested in ...
"""Support for the PostgreSQL database via the psycopg2 driver. Driver ------ The psycopg2 driver is available at http://pypi.python.org/pypi/psycopg2/ . The dialect has several behaviors which are specifically tailored towards compatibility with this module. Note that psycopg1 is **not** supported. Connecting ---...
# encoding: utf-8 # module PyKDE4.kdeui # from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # imports import PyKDE4.kdecore as __PyKDE4_kdecore import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtGui as __PyQt4_QtGui import PyQt4.QtSvg as __PyQt4_QtSvg cl...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ExtractorError class Channel9IE(InfoExtractor): ''' Common extractor for channel9.msdn.com. The type of provided URL (video or playlist) is determined according to meta Search.PageType from web p...
from lib.data_utils import get_MNIST_data from keras.models import load_model from keras.backend import tf as ktf from keras.optimizers import RMSprop from keras.callbacks import ModelCheckpoint, EarlyStopping # Read the MNIST data. Notice that we assume that it's 'kaggle-DigitRecognizer/data/train.csv', and we use he...
"""Demo for KubeFlow Pipelines.""" import json import os from ml_pipeline_gen.models import TFModel from ml_pipeline_gen.pipelines import KfpPipeline from model.census_preprocess import load_data def _upload_data_to_gcs(model): """Calls the preprocessing fn which uploads train/eval data to GCS.""" load_data(...
''' Language tests ============== ''' import unittest from weakref import proxy from functools import partial class BaseClass(object): uid = 0 # base class needed for builder def __init__(self, **kwargs): super(BaseClass, self).__init__() self.proxy_ref = proxy(self) self.childre...
def web_socket_do_extra_handshake(request): request.extra_headers.append( ('Strict-Transport-Security', 'max-age=86400')) def web_socket_transfer_data(request): request.ws_stream.send_message('Hello', binary=False) # vi:sts=4 sw=4 et
from __future__ import absolute_import # For backwards compatibility, provide imports that used to be here. from .connection import is_connection_dropped from .request import make_headers from .response import is_fp_closed from .ssl_ import ( SSLContext, HAS_SNI, IS_PYOPENSSL, IS_SECURETRANSPORT, as...
"""Bulkloader Transform Helper functions. A collection of helper functions for bulkloading data, typically referenced from a bulkloader.yaml file. """ import base64 import datetime import os import re import tempfile from google.appengine.api import datastore from google.appengine.api import datastore_types from...
import logging import os import socket import subprocess import sys import tempfile import time from django.core.management.base import BaseCommand import redisutils import redis as redislib log = logging.getLogger('z.redis') # We process the keys in chunks of size CHUNK. CHUNK = 3000 # Remove any sets with less th...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import yaml from ansible.module_utils.six import PY3 from ansible.parsing.yaml.objects import AnsibleUnicode, AnsibleSequence, AnsibleMapping, AnsibleVaultEncryptedUnicode from ansible.utils.unsafe_proxy import AnsibleUnsafeText f...
import unittest from autothreadharness.harness_case import HarnessCase class Router_9_2_6(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '9 2 6' golden_devices_required = 4 def on_dialog(self, dialog, title): pass if __name__ == '__main__': unittest.main()
import logging log = logging.getLogger('boundaries.api.load_shapefiles') from optparse import make_option import os, os.path import sys from zipfile import ZipFile from tempfile import mkdtemp from django.conf import settings from django.contrib.gis.gdal import (CoordTransform, DataSource, OGRGeometry, ...
import scrapy from datetime import datetime from cobweb.items import PropertyItem from cobweb.utilities import extract_number, extract_unit, extract_property_id, strip, extract_listing_type class SearchSpiderTBDS(scrapy.Spider): name = 'search_spider_tbds' def __init__(self, vendor=None, crawl_url=None, typ...
"""module to handle 'new' command.""" import tempfile import os import re from subprocess import call from clint.textui import prompt, puts, indent, colored import parajumper.item as item import parajumper.config as config import parajumper.db as db EDITOR = os.environ.get('EDITOR', 'vim') def dispatch(args): ""...
from __future__ import print_function # $example on$ from pyspark.ml.feature import IndexToString, StringIndexer # $example off$ from pyspark.sql import SparkSession if __name__ == "__main__": spark = SparkSession\ .builder\ .appName("IndexToStringExample")\ .getOrCreate() # $example ...
from __future__ import unicode_literals import spotify from spotify import ffi, lib, serialized, utils __all__ = [ 'User', ] class User(object): """A Spotify user. You can get users from the session, or you can create a :class:`User` yourself from a Spotify URI:: >>> session = spotify.Se...
"""\ MDPOW version information ========================= MDPOW uses `semantic versioning`_ with the release number consisting of a triplet *MAJOR.MINOR.PATCH*. *PATCH* releases are bug fixes or updates to docs or meta data only and do not introduce new features or change the API. Within a *MAJOR* release, the user API...
from __future__ import division, absolute_import, print_function import sys import platform from numpy.testing import * import numpy.core.umath as ncu import numpy as np # TODO: branch cuts (use Pauli code) # TODO: conj 'symmetry' # TODO: FPU exceptions # At least on Windows the results of many complex functions ar...
"""NSFW urls in the Alexa top 2000 sites.""" nsfw_urls = set([ "http://xhamster.com/", "http://xvideos.com/", "http://livejasmin.com/", "http://pornhub.com/", "http://redtube.com/", "http://youporn.com/", "http://xnxx.com/", "http://tube8.com/", "http://youjizz.com/", "http://adultfriendfinder.com/"...
#!/usr/bin/env python import datetime import logging import os.path from subprocess import call import luigi from luigi_swf import cw, LuigiSwfExecutor logger = logging.getLogger(__name__) seconds = 1. minutes = 60. * seconds hours = 60. * minutes class DemoBasicTask(luigi.Task): # Workaround for when the...
import errno import logging import re from webkitpy.layout_tests.models import test_expectations _log = logging.getLogger(__name__) class LayoutTestFinder(object): def __init__(self, port, options): self._port = port self._options = options self._filesystem = self._port.host.filesystem ...
import pytest from spack.main import SpackCommand list = SpackCommand('list') def test_list(): output = list() assert 'cloverleaf3d' in output assert 'hdf5' in output def test_list_filter(): output = list('py-*') assert 'py-numpy' in output assert 'perl-file-copy-recursive' not in output ...
from _msi import * import os, string, re, sys AMD64 = "AMD64" in sys.version Itanium = "Itanium" in sys.version Win64 = AMD64 or Itanium # Partially taken from Wine datasizemask= 0x00ff type_valid= 0x0100 type_localizable= 0x0200 typemask= 0x0c00 type_long= 0x0000 type_short= 0x0...
""" Django's support for templates. The django.template namespace contains two independent subsystems: 1. Multiple Template Engines: support for pluggable template backends, built-in backends and backend-independent APIs 2. Django Template Language: Django's own template engine, including its built-in loaders, ...