content stringlengths 4 20k |
|---|
from twisted.internet import threads
from Components.config import config
from enigma import eTimer, eConsoleAppContainer
from os import system, listdir, path, popen
from datetime import datetime
isBusy = None
CFG = "/usr/keys/CCcam.cfg"
def CamCheck():
global campoller, POLLTIME
POLLTIME = int(config.plugins... |
u"""
Fixer for Python 3 function parameter syntax
This fixer is rather sensitive to incorrect py3k syntax.
"""
# Note: "relevant" parameters are parameters following the first STAR in the list.
from lib2to3 import fixer_base
from lib2to3.fixer_util import token, String, Newline, Comma, Name
from libfuturize.fixer_uti... |
"""Tests for letsencrypt.cli."""
import itertools
import os
import shutil
import traceback
import tempfile
import unittest
import mock
from letsencrypt import account
from letsencrypt import configuration
from letsencrypt import errors
from letsencrypt.tests import renewer_test
from letsencrypt.tests import test_uti... |
# -*- coding: utf-8 -*-
#
# Runs in an infinite loop and watches the current health of the player
# When the health falls below 50.0, a stimpak is automatically applied
#
from pypipboy.datamanager import PipboyDataManager
pipboy = PipboyDataManager()
def currHpListener(caller, pipvalue, pathObjs):
print('Cu... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None: return None
... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
import os
import sys
# Note throughout the distinction between the artifact_root (which is where the artifacts are
# originally built and where the ca... |
from time import sleep
import traceback
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
import xmpp
log = CPLog(__name__)
autoload = 'Xmpp'
class Xmpp(Notification):
def notify(self, message = '', data = None, listener = None):
if not data: data ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime
from functools import wraps
import logging
import os
from sqlalchemy import event, exc
from sqlalchemy.pool import Pool
from airflow impor... |
#!/usr/bin/env python
#*** WARNING ************************************************
#* *
#* All the tests make extensive use of gpio 4 (pin P1-7). *
#* Ensure that either nothing or just a LED is connected to *
#* gpio 4 before running any of the tests. ... |
#!/usr/bin/env python
""" Module to convert XUnit XML to SQL database of test results of the same type used
by python system tests """
import argparse
import sys
import os
import sqlresults
from testresult import TestResult, envAsString
from xml.dom.minidom import parse, parseString
import re
import time
import dateti... |
"""
Tests for contentstore/views/user.py.
"""
import json
from contentstore.tests.utils import CourseTestCase
from contentstore.utils import reverse_course_url
from django.contrib.auth.models import User
from student.models import CourseEnrollment
from student.roles import CourseStaffRole, CourseInstructorRole
from st... |
import scipy._lib.uarray as ua
from . import _pocketfft
class _ScipyBackend:
"""The default backend for fft calculations
Notes
-----
We use the domain ``numpy.scipy`` rather than ``scipy`` because in the
future ``uarray`` will treat the domain as a hierarchy. This means the user
can install a... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
"""
Support for monitoring a Neurio energy sensor.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.neurio_energy/
"""
import logging
from datetime import timedelta
import requests.exceptions
import voluptuous as vol
from homeassistant.components.... |
from django.conf import settings
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^signout/$', 'users.views.signout', name='users_signout'),
url(r'^profile/edit/$', 'users.views.edit', name='users_edit'),
url(r'^profile/edit/links/$', 'users.views.links',
name='... |
import sys
import os
import signal
import argparse
import importlib
import six
import time
from .contrib import bottle
from .util import GlobCheckerThread
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--port", default=8080,
help="Port to bind on.")
parse... |
"""add_column_to_vnf_lcm_op_occs
Revision ID: 3adac34764da
Revises: 62d18199909e
Create Date: 2021-02-16 16:19:12.100380
"""
# revision identifiers, used by Alembic.
revision = '3adac34764da'
down_revision = '7186440a306b'
from alembic import op
import sqlalchemy as sa
from tacker.db import migration
def upgrade... |
#!/usr/bin/python
#
# <message NAME="DC_SHOT" ID="110">
# <field TYPE="int16" NAME="photo_nr"/>
# <field UNIT="cm" TYPE="int32" NAME="utm_east"/>
# <field UNIT="cm" TYPE="int32" NAME="utm_north"/>
# <field UNIT="m" TYPE="float" NAME="z"/>
# <field TYPE="uint8" NAME="utm_zone"/>
... |
from itertools import chain
import logging
from translator.hot.syntax.hot_resource import HotResource
log = logging.getLogger('heat-translator')
# Name used to dynamically load appropriate map class.
TARGET_CLASS_NAME = 'ToscaNfvScalingAspect'
HEAT_NON_SCALING_RESOURCES = ['OS::Heat::ScalingPolicy',
... |
# -*- coding: utf-8 -*-
"""
Sources:
Croatian Counties: http://en.wikipedia.org/wiki/ISO_3166-2:HR
Croatia doesn't have official abbreviations for counties.
The ones provided are in common use.
"""
from django.utils.translation import ugettext_lazy as _
HR_COUNTY_CHOICES = (
('GZG', _('Grad Zagreb')),... |
import json
import os
import sys
import unittest
from fake_url_fetcher import FakeUrlFetcher
from file_system import StatInfo
from future import Future
from subversion_file_system import SubversionFileSystem
class SubversionFileSystemTest(unittest.TestCase):
def setUp(self):
self._base_path = os.path.join(sys.p... |
from datetime import datetime
from django.utils import timezone
from django.test import TestCase
from lxml import html
from craigmine.craigslist import Craigslist
from craigmine.craigslist import CraigslistItem
from craigmine.craigslist import querystring_to_dict
from craigmine.tests.ad_samples import FULL_RESULT_PAG... |
"""
SVG export test
"""
from __future__ import division, print_function, absolute_import
import pyqtgraph as pg
import csv
import os
import tempfile
app = pg.mkQApp()
def approxeq(a, b):
return (a-b) <= ((a + b) * 1e-6)
def test_CSVExporter():
tempfilename = tempfile.NamedTemporaryFile(suffix='.csv').name
... |
"""
Scheduler host weights
"""
from nova import weights
class WeighedHost(weights.WeighedObject):
def to_dict(self):
x = dict(weight=self.weight)
x['host'] = self.obj.host
return x
def __repr__(self):
return "WeighedHost [host: %r, weight: %s]" % (
self.obj, s... |
import functools
import itertools
import operator
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import excutils
import six
from nova import block_device
from nova import exception
from nova.i18n import _LE
from nova.i18n import _LI
from nova.i18n import _LW
from nova imp... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.snobol
~~~~~~~~~~~~~~~~~~~~~~
Lexers for the SNOBOL language.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups
from pygments.token import Text,... |
"""Tests for sonnet.python.modules.residual."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import sonnet as snt
import tensorflow as tf
class ResidualTest(tf.test.TestCase):
def setUp(self):
super(Residua... |
"""Tests for tensorflow.python.framework.ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tenso... |
# coding: utf-8
from __future__ import unicode_literals
import base64
import json
import os
from .common import InfoExtractor
from ..aes import aes_cbc_decrypt
from ..compat import compat_ord
from ..utils import (
bytes_to_intlist,
ExtractorError,
float_or_none,
intlist_to_bytes,
srt_subtitles_tim... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from jinja2.exceptions import UndefinedError
from ansible.errors import AnsibleFileNotFound, AnsibleLookupError, AnsibleUndefinedVariable
from ansible.module_utils.six import string_types
from ansible.module_utils.parsi... |
# -*- coding: utf-8 -*-
import numpy as np
from fitr.environments.graph import Graph
class IGT(Graph):
""" Iowa Gambling Task """
def __init__(self,rng=np.random.RandomState()):
T = np.zeros((4, 7, 7))
T[0,1,0] = 0.9 # Deck A Reward 100 (9/10)
T[0,3,0] = 0.1 # Deck A Reward 100 + Loss -... |
"""The tests the for Locative device tracker platform."""
from unittest.mock import patch
import pytest
from homeassistant import data_entry_flow
from homeassistant.components import locative
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN
from homeassistant.components.locative imp... |
import sqlalchemy as sa
from neutron.db import model_base
class ConsistencyHash(model_base.BASEV2):
'''
A simple table to store the latest consistency hash
received from a server.
For now we only support one global state so the
hash_id will always be '1'
'''
__tablename__ = 'consistencyha... |
"""Wordcount exercise
Google's Python class
The main() below is already defined and complete. It calls print_words()
and print_top() functions which you write.
1. For the --count flag, implement a print_words(filename) function that counts
how often each word appears in the text and prints:
word1 count1
word2 count2
... |
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import compute
XMLNS = "http://docs.openstack.org/compute/ext/migrations/api/v2.0"
ALIAS = "os-migrations"
def authorize(context, action_name):
action = 'migrations:%s' % action_name
... |
"""
ISCSI Drivers for EMC VMAX arrays based on SMI-S.
"""
from oslo_log import log as logging
import six
from cinder import exception
from cinder.i18n import _, _LE, _LI
from cinder import interface
from cinder.volume import driver
from cinder.volume.drivers.emc import emc_vmax_common
LOG = logging.getLogger(__name... |
from djangotoolbox.db.base import NonrelDatabaseFeatures, \
NonrelDatabaseOperations, NonrelDatabaseWrapper, NonrelDatabaseClient, \
NonrelDatabaseValidation, NonrelDatabaseIntrospection, \
NonrelDatabaseCreation
# We don't use this, but `model` needs to be imported first due to a
# relative import in boto... |
"""Support for X10 lights."""
import logging
from subprocess import check_output, CalledProcessError, STDOUT
import voluptuous as vol
from homeassistant.const import CONF_NAME, CONF_ID, CONF_DEVICES
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
SUPPORT_BRIGHTNESS,
Light,
PLATFORM_SCHEM... |
from lxml import etree
import re
rml_parents = ['tr','story','section']
html_parents = ['tr','body','div']
sxw_parents = ['{http://openoffice.org/2000/table}table-row','{http://openoffice.org/2000/office}body','{http://openoffice.org/2000/text}section']
odt_parents = ['{urn:oasis:names:tc:opendocument:xmlns:office:1.0}... |
"""Convert graminit.[ch] spit out by pgen to Python code.
Pgen is the Python parser generator. It is useful to quickly create a
parser from a grammar file in Python's grammar notation. But I don't
want my parsers to be written in C (yet), so I'm translating the
parsing tables to Python data structures and writing a ... |
"""Tests for distutils.command.sdist."""
import os
import tarfile
import unittest
import warnings
import zipfile
from os.path import join
from textwrap import dedent
# zlib is not used here, but if it's not available
# the tests that use zipfile may fail
try:
import zlib
except ImportError:
zlib = None
try:
... |
"""Super simple fake memcache client."""
from oslo.config import cfg
from nova.openstack.common import timeutils
memcache_opts = [
cfg.ListOpt('memcached_servers',
help='Memcached servers or None for in process cache.'),
]
CONF = cfg.CONF
CONF.register_opts(memcache_opts)
def get_client(memcac... |
Textile = CTextile()
# Create a lenticular section
Section = CSectionLenticular(0.3, 0.14)
Section.AssignSectionMesh(CSectionMeshTriangulate(30))
# Create 4 yarns
Yarns = (CYarn(), CYarn(), CYarn(), CYarn())
# Add nodes to the yarns to describe their paths
Yarns[0].AddNode(CNode(XYZ(0, 0, 0)))
Yarns[0].AddNode(CNode... |
from flask import Blueprint, redirect, request, Response, render_template, url_for
from flask_login import current_user, login_required
import stripe
from pipet.models import db
from pipet.sources.stripe import StripeAccount
from pipet.sources.stripe.forms import CreateAccountForm
from pipet.sources.stripe.models impo... |
import numpy as np
from mathutils import Matrix, Vector
import bpy
from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level
from sverchok.utils.curve import SvC... |
import mimetypes
import os
import random
import time
from email import charset as Charset, encoders as Encoders
from email.generator import Generator
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.header import Header
from email.utils ... |
# -*- coding: utf-8 -*-
import fauxfactory
import pytest
from datetime import datetime, timedelta
from cfme import test_requirements
from cfme.common.vm import VM
from cfme.control.explorer import alert_profiles, policies
from cfme.infrastructure.provider import InfraProvider
from cfme.infrastructure.provider.scvmm im... |
import sys
import os
try:
from urllib2 import urlopen, URLError
except ImportError:
from urllib.request import urlopen, URLError
import zipfile
from io import BytesIO
from . import user_dir
from .skoolimage import SDMemory, BTSMemory, Udg
from .pngwriter import PngWriter, WHITE, BLACK
from .iniparser import In... |
"""Base option parser setup"""
import sys
import optparse
import os
import textwrap
from distutils.util import strtobool
from pip.backwardcompat import ConfigParser, string_types
from pip.locations import default_config_file
from pip.util import get_terminal_size, get_prog
class PrettyHelpFormatter(optparse.Indente... |
"""Tests for SparseConcat."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import sparse_tensor
from t... |
from django.core.urlresolvers import reverse as django_reverse
from django.core.urlresolvers import get_urlconf, NoReverseMatch
from django.conf import settings
from django_hosts.reverse import reverse_full
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
original_kwarg... |
"""
# Majic
# Copyright (C) 2014 CEH
#
# 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 version 2 of the License, or
# (at your option) any later version.
#
# This pr... |
#
# PKCS#10 syntax
#
# ASN.1 source from:
# http://tools.ietf.org/html/rfc2314
#
# Sample captures could be obtained with "openssl req" command
#
from pyasn1.type import tag, namedtype, namedval, univ, constraint
from pyasn1_modules.rfc2459 import *
class Attributes(univ.SetOf):
componentType = Attribute()
class ... |
from django.db.models import signals
from django.test import TestCase
from django.core import management
from django.utils import six
from . import models
PRE_MIGRATE_ARGS = ['app', 'create_models', 'verbosity', 'interactive', 'db']
MIGRATE_DATABASE = 'default'
MIGRATE_VERBOSITY = 1
MIGRATE_INTERACTIVE = False
cla... |
import io
import json
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
from pycoin.networks.default import get_current_netcode
from pycoin.serialize import b2h_rev, h2b, h2b_rev
from pycoin.tx import Spendable, Tx
class ChainSoProvider(object):
def __init__(self, n... |
import calendar
from email.utils import formatdate, parsedate
from datetime import datetime, timedelta
def expire_after(delta, date=None):
date = date or datetime.now()
return date + delta
def datetime_to_header(dt):
return formatdate(calendar.timegm(dt.timetuple()))
class BaseHeuristic(object):
... |
from .state import EOF
from .tokens import TokenEof
from .tokens_base import TOKEN_COMMAND_WRITE_AND_QUIT_COMMAND
from .tokens_base import TokenOfCommand
from Vintageous import ex
plus_plus_translations = {
'ff': 'fileformat',
'bin': 'binary',
'enc': 'fileencoding',
'nobin': 'nobinary',
}
@ex.comman... |
import sys
from optparse import OptionParser
from pylab import *
import re
parser = OptionParser(usage='Usage: %prog [options] <save_file>')
parser.add_option('-c', '--connections', dest='connections', type='string', default=None, action='store', help='connections to plot (default = all)')
parser.add_option('-w', '--w... |
from __future__ import unicode_literals
import django
from django.db import models
from django.db.models.fields.related import OneToOneField
from django.db.models.query import QuerySet
from django.core.exceptions import ObjectDoesNotExist
try:
from django.db.models.constants import LOOKUP_SEP
from django.utils... |
from oslo_middleware import request_id
import webob
from neutron import auth
from neutron.tests import base
class NeutronKeystoneContextTestCase(base.BaseTestCase):
def setUp(self):
super(NeutronKeystoneContextTestCase, self).setUp()
@webob.dec.wsgify
def fake_app(req):
self.... |
from __future__ import absolute_import, print_function, unicode_literals
import sys
import io
import os
import tempfile
import gpg
import support
_ = support # to appease pyflakes.
del absolute_import, print_function, unicode_literals
# Both Context and Data can be used as context manager:
with gpg.Context() as c, ... |
#!/usr/env python
import json,os,argparse,calendar as cal
CURR_FILE = os.path.abspath(__file__)
CURR_DIR = os.path.dirname(CURR_FILE)
HW_DIR = os.path.dirname(CURR_DIR)
JSON_FILE = os.path.join(CURR_DIR,'classes.json')
PROMPTS = {
0:"Path: {0}\nDoes not exist. Create? (Y/N) ",
1:"Path: {0}\nFile: {1}\nFile exists... |
import pygame
pygame.init()
import time
from Axon.Component import component
from Axon.Ipc import newComponent
class SpriteScheduler(component):
def __init__(self, cat_args, cat_sprites, background, display_surface, eventHandlerClass=None):
super(SpriteScheduler,self).__init__()
self.allsprites = []
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch, MagicMock
from ansible.modules.network.nxos import nxos_config
from ansible.plugins.cliconf.nxos import Cliconf
from .nxos_module import TestNxosModule, load_fixture, set_module_args
c... |
from airflow.contrib.hooks.bigquery_hook import BigQueryHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class BigQueryTableDeleteOperator(BaseOperator):
"""
Deletes BigQuery tables
:param deletion_dataset_table: A dotted
(<project>.|<project>:)<dat... |
import sys
sys.path.append('../')
import logging
import traceback as tb
import suds.metrics as metrics
from tests import *
from suds import WebFault
from suds.client import Client
errors = 0
setup_logging()
#logging.getLogger('suds.client').setLevel(logging.DEBUG)
#logging.getLogger('suds.metrics').setLevel(logging... |
import pytest
import json
from textwrap import dedent
from vdirsyncer import exceptions
from vdirsyncer.storage.base import Storage
def test_discover_command(tmpdir, runner):
runner.write_with_general(dedent('''
[storage foo]
type = "filesystem"
path = "{0}/foo/"
fileext = ".txt"
[storage ba... |
from __future__ import unicode_literals
import datetime
import unittest
from django.utils import feedgenerator
from django.utils.timezone import get_fixed_timezone
class FeedgeneratorTest(unittest.TestCase):
"""
Tests for the low-level syndication feed framework.
"""
def test_get_tag_uri(self):
... |
# coding: utf-8
import copy
import json
from typing import Union
from bson import json_util
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.pagination import _positive_int as positive_int
from shortuuid import ShortUUI... |
# ============================================
# DNSMadeEasy module specific support methods.
#
import urllib
IMPORT_ERROR = None
try:
import json
from time import strftime, gmtime
import hashlib
import hmac
except ImportError, e:
IMPORT_ERROR = str(e)
class DME2:
def __init__(self, apikey, ... |
# -*- coding:utf-8-*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from time import *
import sys
class Windows(QDialog):
def __init__(self, parent=None):
super(Windows, self).__init__(parent)
self.startButton = QPushButton("Start")
self.stopButton = QPushButton("Stop")
... |
# -*- coding: utf-8 -*-
'''
Phoenix Add-on
Copyright (C) 2015 Blazetamer
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 version 3 of the License, or
(at your option) ... |
import pythoncom
import win32com.server.util
import win32com.test.util
import unittest
from pywin32_testutil import str2bytes
class Persists:
_public_methods_ = [ 'GetClassID', 'IsDirty', 'Load', 'Save',
'GetSizeMax', 'InitNew' ]
_com_interfaces_ = [ pythoncom.IID_IPersistStreamInit ]... |
"""
Test for the post-migration fix commands that are included with this djangoapp
"""
from django.core.management import call_command
from django.test.client import RequestFactory
from openedx.core.djangoapps.course_groups.views import cohort_handler
from openedx.core.djangoapps.course_groups.cohorts import get_cohor... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'acq4/devices/AxoPatch200/devGuiTemplate.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_devGui(object):
def setupUi(self, de... |
"""
Polish-specific form helpers
"""
from __future__ import absolute_import, unicode_literals
import re
from django.contrib.localflavor.pl.pl_administrativeunits import ADMINISTRATIVE_UNIT_CHOICES
from django.contrib.localflavor.pl.pl_voivodeships import VOIVODESHIP_CHOICES
from django.core.validators import EMPTY_V... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleAction, AnsibleActionFail
from ansible.executor.module_common import get_action_args_with_defaults
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
TRANSFERS_FI... |
# -*- coding: utf-8 -*-
"""
tests.test_config
~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import pytest
import os
import flask
# config keys used for the TestConfig
TEST_KEY = 'foo'
SECRET_KEY = 'devkey'
... |
import bpy
from ..operators.mecafig import get_mecafig
from ..icons.__init__ import get_icon
def ui_template_mecafig(context, layout):
scene = context.scene
ob = context.active_object
data = scene.mecafig
mf = get_mecafig(context)
objects = []
for obj in bpy.data.objects:
if obj.type ... |
# -*- coding: utf-8 -*-
"""
The MIT License
Copyright (c) 2011 Olle Johansson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use,... |
from __future__ import print_function
from pyspark import SparkContext
# $example on$
import numpy as np
from pyspark.mllib.stat import Statistics
# $example off$
if __name__ == "__main__":
sc = SparkContext(appName="SummaryStatisticsExample") # SparkContext
# $example on$
mat = sc.parallelize(
... |
import logging
from cloudinitd.exceptions import *
#from cloudinitd.user_api import *
from cloudinitd.statics import *
import urlparse
service_state_initial = 0
service_state_launched = 2
service_state_contextualized = 4
service_state_terminated = 6
g_open_loggers = []
Version = "1.3"
def find_true():
cmds = [
... |
"""Sample usage of the Iterator pattern."""
#!/usr/bin/env python
# pylint: disable=missing-docstring,too-few-public-methods
class Europe(object):
def __init__(self):
self._est = ["Romania", "Poland", "Ukraine"]
self._south = ["Greece", "Italy", "Spain"]
self._west = ["France", "UK", "Irel... |
import frappe
import json
from frappe.model.utils.rename_field import update_reports, rename_field, update_property_setters
from frappe.custom.doctype.property_setter.property_setter import make_property_setter
def execute():
frappe.reload_doctype('Purchase Order Item')
frappe.reload_doctype('Purchase Receipt Item')... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
try:
import ldap
import ldap.modlist
import ldap.sasl
... |
# coding: utf-8
import io
import pandas.io.msgpack as msgpack
binarydata = bytes(bytearray(range(256)))
def gen_binary_data(idx):
return binarydata[:idx % 300]
def test_exceeding_unpacker_read_size():
dumpf = io.BytesIO()
packer = msgpack.Packer()
NUMBER_OF_STRINGS = 6
read_size = 16
#... |
# Django settings for semaphore project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # ... |
"""
Tests for the CyberSource processor handler
"""
from collections import OrderedDict
from django.test import TestCase
from django.test.utils import override_settings
from django.conf import settings
from student.tests.factories import UserFactory
from shoppingcart.models import Order, OrderItem
from shoppingcart.pro... |
"""Test HTML5 notify platform."""
import json
from aiohttp.hdrs import AUTHORIZATION
import homeassistant.components.html5.notify as html5
from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR
from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component
from test... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsColorRampShader.
.. 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 version 2 of the License, or
(at your option) any later version.
""... |
#!/usr/bin/env python3
from os import getenv
from pathlib import Path
from sys import argv
import hashlib
import json
if len(argv) != 2:
print("ERROR: JSON info script requires output arg")
exit(1)
json_path = Path(argv[1])
bin_dir = Path(getenv("BIN_DIR"))
image_file = bin_dir / getenv("IMAGE_NAME")
if not... |
"""
SeqFindr configuration class: 100% test coverage, > 9 PyLint score
"""
import os
import sys
import ast
class SeqFindrConfig(object):
"""
A SeqFindr configuration class - subtle manipulation to plots
"""
def __init__(self, alt_location=None):
self.config = read_config(alt_location)
d... |
# -*- coding: utf-8 -*-
"""upload_docs
Implements a Distutils 'upload_docs' subcommand (upload documentation to
PyPI's packages.python.org).
"""
import os
import socket
import zipfile
import httplib
import base64
import urlparse
import tempfile
import sys
from distutils import log
from distutils.errors import Distut... |
import collections
import pprint
import textwrap
from jsonschema import _utils
from jsonschema.compat import PY3, iteritems
_unset = _utils.Unset()
class _Error(Exception):
def __init__(
self, message, validator=_unset, path=(), cause=None, context=(),
validator_value=_unset, instance=_unset, s... |
"""
Copyright 2014-2015. Jorgen Maas <<EMAIL>>
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 version 2 of the License, or
(at your option) any later version.
This program is distributed in ... |
import re
import unittest
from memory_inspector.classification import results
from memory_inspector.classification import rules
class ResultsTest(unittest.TestCase):
def runTest(self):
rules_dict = [
{
'name': 'a*',
'regex': '^a.*',
'children': [
{
'name': 'a... |
# Added Fortran compiler support to config. Currently useful only for
# try_compile call. try_run works but is untested for most of Fortran
# compilers (they must define linker_exe first).
# Pearu Peterson
import os, signal
import warnings
import sys
from distutils.command.config import config as old_config
from dist... |
"""Tests for tensorflow.ops.compare_and_bitpack_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
class CompareAndBitpackTest(test.TestCase):
... |
"""
Utilities for use in Mako markup.
"""
from django.utils.translation import ugettext as django_ugettext
from django.utils.translation import ungettext as django_ungettext
import markupsafe
# So that we can use escape() imported from here.
escape = markupsafe.escape # pylint: disable=invalid-n... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.