content stringlengths 4 20k |
|---|
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
from ansible.module_utils.basic import AnsibleModule, env_fallback
from ansible.module_utils.... |
"""
Support for Hikvision event stream events represented as binary sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.hikvision/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.helpers.ev... |
from StringIO import StringIO
try:
OLD_SUGAR_SYSTEM = False
import json
json.dumps
from json import load as jload
from json import dump as jdump
except (ImportError, AttributeError):
try:
import simplejson as json
from simplejson import load as jload
from simplejson impor... |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Runs the framework corresponding to the event listener hook provider.
Use the ``gen_event`` shell command to generate a new service event.
Use ``gen_filtered_event`` to generate an event that will be handled
differently by the hook: after the 3rd occurrence of... |
""" Tests for analytics.distributions """
from django.test import TestCase
from nose.tools import raises
from student.models import CourseEnrollment
from student.tests.factories import UserFactory
from analytics.distributions import profile_distribution, AVAILABLE_PROFILE_FEATURES
class TestAnalyticsDistributions(T... |
from openerp.addons.website.controllers.main import Website
from openerp.http import request, route
class Website(Website):
@route()
def customize_template_get(self, xml_id, full=False):
res = super(Website, self).customize_template_get(xml_id, full=full)
if full and request.session.get('repo... |
DATE_FORMAT = 'j F Y г.'
TIME_FORMAT = 'G:i:s'
DATETIME_FORMAT = 'j F Y г. G:i:s'
YEAR_MONTH_FORMAT = 'F Y г.'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'd.m.Y'
SHORT_DATETIME_FORMAT = 'd.m.Y H:i'
FIRST_DAY_OF_WEEK = 1 # Monday
DATE_INPUT_FORMATS = (
'%d.%m.%Y', # '25.10.2006'
'%d.%m.%y', # '25.10.... |
from __future__ import unicode_literals
import errno
import json
import os
import re
from mozbuild.util import hash_file
# Regular expression to strip ANSI color sequences from a string. This is
# needed to properly analyze Clang compiler output, which may be colorized.
# It assumes ANSI escape sequences.
RE_STRIP_... |
"""
BigchainDB: A Scalable Blockchain Database
For full docs visit https://bigchaindb.readthedocs.org
"""
from setuptools import setup, find_packages
tests_require = [
'pytest',
'coverage',
'pep8',
'pyflakes',
'pylint',
'pytest',
'pytest-cov',
'pytest-xdist',
'pytest-flask',
]
de... |
from functools import wraps
from django.utils.cache import patch_vary_headers
from django.utils.decorators import available_attrs
def vary_on_headers(*headers):
"""
A view decorator that adds the specified headers to the Vary header of the
response. Usage:
@vary_on_headers('Cookie', 'Accept-languag... |
from __future__ import absolute_import
import time
import logging
from collections import namedtuple
from itertools import takewhile
import email
import re
from ..exceptions import (
ConnectTimeoutError,
MaxRetryError,
ProtocolError,
ReadTimeoutError,
ResponseError,
InvalidHeader,
)
from ..pack... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import numpy as np
from scipy.misc import factorial
import matplotlib.pyplot as p
from gencmd.model import SSP
from gencmd.util.phot_sys import col_dict, ecoeff
import emcee
from triangle import corner
def... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : <EMAIL>
**... |
data = (
'[?]', # 0x00
'[?]', # 0x01
'[?]', # 0x02
'[?]', # 0x03
'[?]', # 0x04
'B', # 0x05
'P', # 0x06
'M', # 0x07
'F', # 0x08
'D', # 0x09
'T', # 0x0a
'N', # 0x0b
'L', # 0x0c
'G', # 0x0d
'K', # 0x0e
'H', # 0x0f
'J', # 0x10
'Q', # 0x11
'X', # 0x12
'ZH', # 0x13
... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
def get_file_name(intext,filename):
ext = filename.split(".")[-1]
class UserDetails(models.Model):
full_name = models.CharField(max_length=200,null=True,blank=True)
father_name = models.CharField(max_length=... |
#!/usr/bin/env python
__author__ = 'chris'
import argparse
import os
import sys
import pandas as pd
import seaborn as sns
import numpy as np
parser = argparse.ArgumentParser(description="Create a heatmap from a delimited file.")
parser.add_argument('--tsv', help='The delimited file to plot.', type=argparse.FileType('... |
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/execute_program_in_vm.py
def execute_command(content, vm, vm_username, vm_password, program_path, args="", env=None, cwd=None):
creds... |
import urllib2, urlparse
import SCons.Builder, SCons.Node, SCons.Errors
# define an own node, for checking the data behind the URL,
# we must download only than, if the data is changed, the
# node derivates from the Python.Value node
class URLNode(SCons.Node.Python.Value) :
# overload the get_csig (copy the sour... |
from time import time
from fake_switches.netconf import dict_2_etree, XML_ATTRIBUTES
from hamcrest import assert_that, has_length, greater_than
from tests.juniper import BaseJuniper
from tests.util.global_reactor import COMMIT_DELAY
class JuniperBaseProtocolWithCommitDelayTest(BaseJuniper):
test_switch = "commit... |
import os
import re
import sys
import time
from getopt import getopt
from Summary import Summary
from Project import Project, trees
from compiler import CompilerSpec
from Build import Build
import actions, compiler
import ProjectDefs # this adds a lot of definitions to 'trees'
def error(msg):
sys.stder... |
import os.path
from subprocess import check_call
import sys
def RunBindingsGenerator(out_dir, root_dir, mojom_file, extra_flags=None):
out_dir = os.path.abspath(out_dir)
root_dir = os.path.abspath(root_dir)
mojom_file = os.path.abspath(mojom_file)
# The mojom file should be under the root directory somewhere... |
""" The file is responsable for cart in flask-webpage """
from flask import current_app as app
from flask_seguro.products import Products
class Cart(object):
""" The classe is responsable for cart in webpage """
def __init__(self, cart_dict=None):
""" Initializing class """
cart_dict = cart... |
"""
Test cases for the repr module
Nick Mathewson
"""
import sys
import os
import shutil
import unittest
from test.support import run_unittest
from reprlib import repr as r # Don't shadow builtin repr
from reprlib import Repr
def nestedTuple(nesting):
t = ()
for i in range(nesting):
t = (t,)
... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.ec2 import (camel_dict_to_snake_dict, ec2_argument_spec, HAS_BOTO3,
get_aws_connection_info, boto3_conn, AWSRetry)
... |
{
"name": "LATAM Document",
"version": "1.0",
"author": "ADHOC SA",
"category": "Localization",
"summary": "LATAM Document Types",
'description': """
Functional
----------
In some Latinamerica countries, including Argentina and Chile, some accounting transactions like invoices and vendor bills ... |
#!/usr/bin/env python
import sys
import traceback
# quick version check
if not (sys.version_info[0] == 2 and sys.version_info[1] >= 6):
print("Sorry, the Overviewer requires at least Python 2.6 to run")
if sys.version_info[0] >= 3:
print("and will not run on Python 3.0 or later")
sys.exit(1)
from... |
import os
import glob
import gettext
__trans = gettext.translation('pisilinux', fallback=True)
_ = __trans.ugettext
# pisilinux Modules
import pisilinux.context as ctx
# ActionsAPI Modules
import pisilinux.actionsapi
import pisilinux.actionsapi.get as get
from pisilinux.actionsapi.shelltools import system
from pisil... |
from sqlalchemy import Column
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy import Table
def upgrade(engine):
"""Function adds request_id field."""
meta = MetaData(bind=engine)
pci_devices = Table('pci_devices', meta, autoload=True)
shadow_pci_devices = Table('shadow_p... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.cnos import cnos_vlag
from units.modules.utils import set_module_args
from .cnos_module import TestCnosModule, load_fixture
class TestCnosVlagModule(TestCnosModule)... |
from . import Image, _imagingmath
try:
import builtins
except ImportError:
import __builtin__
builtins = __builtin__
VERBOSE = 0
def _isconstant(v):
return isinstance(v, int) or isinstance(v, float)
class _Operand(object):
"""Wraps an image operand, providing standard operators"""
def __i... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import subprocess
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables, **kwargs):
if isinstance(terms, basestring):
... |
# This class gives a common interface for logging into the grading controller
import json
import logging
import requests
from dogapi import dog_stats_api
from requests.exceptions import RequestException, ConnectionError, HTTPError
from .combined_open_ended_rubric import CombinedOpenEndedRubric, RubricParsingError
from... |
#!/usr/bin/env python
#
# SysProof - Encrypts all incoming/outgoing emails by using
# the parameters stored in the LDAP server.
#
# Written by Chema Garcia (aka sch3m4)
# <EMAIL> || http://safetybits.net
# @sch3m4
#
import sys
import ldap
import gnupg
import syslog
import email
from os.pat... |
import random
from sympy.mpmath import *
from sympy.mpmath.libmpf import *
def test_basic_string():
"""
Test basic string conversion
"""
mp.dps = 15
assert mpf('3') == mpf('3.0') == mpf('0003.') == mpf('0.03e2') == mpf(3.0)
assert mpf('30') == mpf('30.0') == mpf('00030.') == mpf(30.0)
for ... |
from __future__ import absolute_import, division, print_function, with_statement
import pycares
import socket
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.netutil import Resolver, is_valid_ip
class CaresResolver(Resolver):
"""Name resolver based on the c-ares library.
This is a non... |
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.networks.ports \
import forms a... |
from __future__ import absolute_import
import os
import shutil
from django.core.files import File
from django.core.files.images import ImageFile
from django.test import TestCase
from django.utils._os import upath
from django.utils.unittest import skipIf
from .models import Image
if Image:
from .models import (P... |
import unittest
import logging
import tempfile
from .test_commons import conn_info
import vertica_python
from vertica_python import errors
logger = logging.getLogger('vertica')
def init_table(cur):
# clean old table
cur.execute('DROP TABLE IF EXISTS vertica_python_unit_test;')
# create test table
... |
"""add functionally for differentiate miscible products and not"""
from osv import fields, osv
from tools.translate import _
class product_product(osv.osv):
"""add functionally for differentiate miscible product and not miscible product"""
_inherit = "product.product"
_columns = {
'mi... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.testtools
~~~~~~~~~~~~~~~~~~~~~~~~~~
This module implements extended wrappers for simplified testing.
`TestResponse`
A response wrapper which adds various cached attributes for
simplified assertions on various content types.
:copyright:... |
"""
Middleware for Language Preferences
"""
from __future__ import absolute_import
from django.conf import settings
from django.utils.translation import LANGUAGE_SESSION_KEY
from django.utils.translation.trans_real import parse_accept_lang_header
from openedx.core.djangoapps.lang_pref import COOKIE_DURATION, LANGUAGE... |
""" Provide a version for the Bokeh library.
This module uses `versioneer`_ to manage version strings. During development,
`versioneer`_ will compute a version string from the current git revision.
For packaged releases based off tags, the version string is hard coded in the
files packaged for distribution.
Attribute... |
from test.support import run_unittest, verbose
from platform import linux_distribution
import unittest
import locale
import sys
import codecs
enUS_locale = None
def get_enUS_locale():
global enUS_locale
if sys.platform == 'darwin':
import os
tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US")
... |
# generation commands
# h2xml.py -I $PWD -c -o pa.xml pulse/mainloop-api.h pulse/sample.h pulse/def.h pulse/operation.h pulse/context.h pulse/channelmap.h pulse/volume.h pulse/stream.h pulse/introspect.h pulse/subscribe.h pulse/scache.h pulse/version.h pulse/error.h pulse/xmalloc.h pulse/utf8.h pulse/thread-mainloop.h ... |
def add_port_mapping(port_bindings, internal_port, external):
if internal_port in port_bindings:
port_bindings[internal_port].append(external)
else:
port_bindings[internal_port] = [external]
def add_port(port_bindings, internal_port_range, external_range):
if external_range is None:
... |
"""Definition of targets to build distribution packages."""
import os.path
import sys
sys.path.insert(0, os.path.abspath('..'))
import python_utils.jobset as jobset
def create_docker_jobspec(name, dockerfile_dir, shell_command, environ={},
flake_retries=0, timeout_retries=0):
"""Creates jobspec... |
"""Pylons middleware initialization"""
from beaker.middleware import CacheMiddleware, SessionMiddleware
from paste.cascade import Cascade
from paste.registry import RegistryManager
from paste.urlparser import StaticURLParser
from paste.deploy.converters import asbool
from pylons import config
from pylons.middleware imp... |
from nose.tools import eq_, ok_, with_setup
from mock import MagicMock
from ycm.test_utils import MockVimModule
vim_mock = MockVimModule()
from ycm import base
from ycm import vimsupport
import sys
# column is 0-based
def SetVimCurrentColumnAndLineValue( column, line_value ):
vimsupport.CurrentColumn = MagicMock( re... |
from openerp.exceptions import Warning
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.workflow
class workflow(osv.osv):
_name = "workflow"
_table = "wkf"
_order = "name"
_columns = {
'name': fields.char('Name', required=True),
'osv': fields.char... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import json
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX =... |
"""
Support tool for changing course enrollments.
"""
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.db import transaction
from django.db.models import Q
from django.http import HttpResponseBadRequest
from django.urls import reverse
from django.utils.decorat... |
from django import template
import datetime
from micro_blog.models import Post
register = template.Library()
@register.assignment_tag(takes_context=True)
def get_archives(context):
archives = []
dates = []
for each_object in Post.objects.filter(status='P').order_by('created_on').values('created_on'):
... |
from __future__ import unicode_literals
from collections import namedtuple
import pytest
from django.conf.urls import url
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import TestCase, override_settings
from rest_framework import permissions, serializers, views... |
"""Utility for light control."""
import colorsys
import random
import serial
import struct
from common import pattern
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
class Dmx(pattern.Closable, pattern.Logger):
"""Class for controlling DMX lights.
Dmx lights uses COM port for communic... |
import urllib
import simplejson
from hashlib import sha1
class Stripe:
"""
Usage:
key='<api key>'
d = Stripe(key).charge(
amount=100, # 1 dollar!!!!
currency='usd',
card_number='4242424242424242',
card_exp_month='5',
card_exp_ye... |
"""Import and conditionally load custom ops for training boosted trees."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.contrib.boosted_trees.python.ops import boosted_trees_ops_loader
# pylint: enable=unuse... |
# META: timeout=long
import pytest
from tests.support.asserts import assert_dialog_handled, assert_error, assert_success
def element_clear(session, element):
return session.transport.send(
"POST", "/session/{session_id}/element/{element_id}/clear".format(
session_id=session.session_id,
... |
from __future__ import with_statement
from boto.sdb.db.model import Model
from boto.sdb.db.property import StringProperty, IntegerProperty, ListProperty, ReferenceProperty, CalculatedProperty
from boto.manage.server import Server
from boto.manage import propget
import boto.utils
import boto.ec2
import time
import trace... |
from collections import OrderedDict
from bokeh.sampledata import us_counties, unemployment
from bokeh.plotting import figure, show, output_file, ColumnDataSource
from bokeh.models import HoverTool
state = "tx"
county_xs=[
us_counties.data[code]['lons'] for code in us_counties.data
if us_counties.data[code]['... |
from __future__ import absolute_import
import time
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
from django.test import TestCase, RequestFactory
from django.utils import unittest
from django.views.generic import View, TemplateView, RedirectView
from . import views
cla... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Takeru Ichii'
import requests
import json
import argparse
class pyIncomingSlack:
def __init__(self, token_url, user_name, icon = ''):
self.token_url = token_url
self.user_name = user_name
self.icon = icon
def send(self, ... |
import os
try:
import json; json
except ImportError:
# test skipped later
json = None
from mapproxy.test.image import img_from_buf
from mapproxy.test.http import mock_single_req_httpd
from mapproxy.test.system import module_setup, module_teardown, SystemTest, make_base_config
from mapproxy.request.wms imp... |
import os
import hashlib
import binascii
import struct
import M2Crypto.RSA as RSA
import M2Crypto.BIO as BIO
from cStringIO import StringIO
# Package a pile of data, identified by user-id, into a distribution
# plus metadata.
# Input: A directory containing a bunch of files, each of whose name
# is a hexadecimal user... |
# -*- coding: utf-8 -*-
'''
ROL, Rotate Left Test
This is an Bit Manipulation of the 6502.
'''
import unittest
from pynes.compiler import lexical, syntax, semantic
class RolTest(unittest.TestCase):
def test_rol_imm(self):
tokens = list(lexical('ROL #$10'))
self.assertEquals(2, len(tokens))
... |
# imports
import os
import shutil
import argparse
import textwrap
import datetime
NOWTIME = datetime.datetime.now()
# print NOWTIME.year, NOWTIME.month, NOWTIME.day, NOWTIME.hour, NOWTIME.minute, NOWTIME.second
# evaluate arguments
parser = argparse.ArgumentParser(
prog='slideCopy',
description='This script co... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
from copy import deepcopy
from ansible.module_utils.basic import AnsibleModule
fro... |
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **Functionality related to shake data files.**
Contact : <EMAIL>
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Softwar... |
import collections
import os
import time
import uuid
from ovs.db import idl
from ovs import jsonrpc
from ovs import poller
from ovs import stream
from neutron.common import exceptions
RowLookup = collections.namedtuple('RowLookup',
['table', 'column', 'uuid_column'])
# Tables wit... |
# -*- coding: utf-8 -*-
from turbogears import controllers, expose, paginate
from turbogears import redirect, url
from turbogears import validate, validators, error_handler
from turbogears import widgets
from turbogears import flash
from turbogears import identity
from datetime import datetime
from sqlobject.sqlbuil... |
import unittest
from webkitpy.tool.grammar import join_with_separators
class GrammarTest(unittest.TestCase):
def test_join_with_separators(self):
self.assertEqual(join_with_separators(["one"]), "one")
self.assertEqual(join_with_separators(["one", "two"]), "one and two")
self.assertEqual(j... |
from haystack import indexes
from nuremberg.documents.models import Document
from nuremberg.transcripts.models import TranscriptPage
class DocumentIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
material_type = indexes.CharField(default='Document', face... |
from citest import service_testing
import spinnaker_testing.spinnaker as sk
class Front50Status(service_testing.HttpOperationStatus):
@classmethod
def new(cls, operation, original_response):
"""Factory method.
Args:
operation: [AgentOperation] The operation this status is for.
original_respon... |
import logging
import pytest
from copy import deepcopy
from subprocess import call, check_call
from testdata.common import widetable
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
from tests.util.test_file_parser import *
from tests.util.filesystem_utils import WAREHOUSE
from tests... |
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,QMainWindow
from PyQt5.QtGui import QIcon, QPixmap,QPainter, QColor, QPen,QMouseEvent
from PyQt5.Qt import Qt
from PyQt5 import QtCore
from PyQt5.QtCore import QSize, pyqtSignal
import numpy as np
from math import sin,cos,radians,sqrt,degrees,atan,aco... |
# -*- coding: utf-8 -*-
"""
Chinese-specific form helpers
"""
from __future__ import absolute_import, unicode_literals
import re
from django.contrib.localflavor.cn.cn_provinces import CN_PROVINCE_CHOICES
from django.forms import ValidationError
from django.forms.fields import CharField, RegexField, Select
from djang... |
import os
import re
from BeautifulSoup import BeautifulSoup
import sys
import string
def findindex(haystack,needle):
count = 0
for line in haystack:
if needle in line:
return count
count += 1
def getsection(file,start,end):
html = ''
for i in file[start:end]:
html = "%s\r\n%s"%(html,i)
ret... |
import os
import sys
sys.path = [os.path.abspath(os.path.dirname(__file__))] + sys.path
sys.path = [os.path.abspath(os.path.dirname(os.path.dirname(__file__)))] + sys.path
os.environ['is_test_suite'] = 'True'
from auto_ml import Predictor
import numpy as np
import utils_testing as utils
def always_return_ten_thousa... |
"""Tests for MultivariateNormal."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import distributions as tfd
... |
from django.conf import settings
# lfs imports
from lfs.core.signals import customer_added
from lfs.core.signals import order_submitted
from lfs.core.signals import order_sent
from lfs.core.signals import order_paid
from lfs.mail import utils as mail_utils
# reviews imports
from reviews.signals import review_added
... |
import re
from typing import Optional
from sqlalchemy import or_, func, cast, Text
from sqlalchemy.orm import Query
from pycroft.helpers.net import mac_regex, ip_regex
from pycroft.model.facilities import Room
from pycroft.model.host import Host, Interface, IP
from pycroft.model.user import User, Membership, Property... |
from troveclient.v1 import backups
from troveclient.v1 import databases
from troveclient.v1 import datastores
from troveclient.v1 import flavors
from troveclient.v1 import instances
from troveclient.v1 import users
from openstack_dashboard.test.test_data import utils
DATABASE_DATA_ONE = {
"status": "ACTIVE",
... |
# -*- coding: utf-8 -*-
"""
@author: Jussi Tiira
"""
from snowfall import *
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from os import path
def rangecolor(rho, rholimits=(150, 300), colors=('r', 'b', 'c', 'g', 'm')):
for i, rhomax in enumerate(rholimits):
if rho < rhomax:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from subprocess import Popen, PIPE
import sys
import shlex
################### bzrRev: uses bzr branch (if exists) information to
# determine a unique revision number
def bzrRev():
version_info = {}
if os.path.exists(".git"):
print "generating ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: multigpu.py
import tensorflow as tf
import itertools, re
from six.moves import zip, range
from ..models import TowerContext
from ..utils import logger
from ..utils.naming import *
from ..utils.concurrency import LoopThread
from ..tfutils.summary import summary_mov... |
"""Test pywin32's error semantics"""
import sys
import unittest
import win32api, win32file, pywintypes
import pythoncom
import winerror
class TestBase(unittest.TestCase):
def _testExceptionIndex(self, exc, index, expected):
# check the exception itself can be indexed if not py3k
if sys.version_info... |
# -*- coding: utf-8 -*-
import numpy as np
from numpy import abs, sum, sin, cos, pi, exp, arange, prod, sqrt
from .go_benchmark import Benchmark
class XinSheYang01(Benchmark):
r"""
Xin-She Yang 1 objective function.
This class defines the Xin-She Yang 1 [1]_ global optimization problem.
This is a mu... |
"""\
===================
Passthrough of data
===================
The PassThrough component simply passes through data from its "inbox" inbox
to its "outbox" outbox.
This can be used, for example, as a dummy 'protocol' component - slotting it
into a system where ordinarily a component would go that somehow changes or
... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Document2'
db.create_table('desktop_document2', (
('id', self.gf('django.db.mode... |
#
# Listal Downloader
# vintol.github.io/listal
#
import urllib.request,ssl
import argparse
import time
import queue
import threading
import os,sys
#
# Very Important.
ssl._create_default_https_context = ssl._create_unverified_context
def download():
global broken, failed, ls
while not qq.empty():
m... |
#!/usr/bin/kivy
'''
Touch Tracer Line Drawing Demonstration
=======================================
This demonstrates tracking each touch registered to a device. You should
see a basic background image. When you press and hold the mouse, you
should see cross-hairs with the coordinates written next to them. As
you drag... |
"""private_base will be populated from puppet and placed in this directory"""
import logging
import os
import dj_database_url
from lib.settings_base import (CACHE_PREFIX, ES_INDEXES,
KNOWN_PROXIES, LOGGING, HOSTNAME)
from .. import splitstrip
import private_base as private
ENGAGE_RO... |
import os
import tempfile
import io
import csv
from requests import Session
from requests.exceptions import (ConnectionError,
InvalidSchema,
MissingSchema,
ReadTimeout,
)
from svir.utilit... |
"""The io module provides the Python interfaces to stream handling. The
builtin open function is defined in this module.
At the top of the I/O hierarchy is the abstract base class IOBase. It
defines the basic interface to a stream. Note, however, that there is no
separation between reading and writing to streams; impl... |
"""
This module provides support for Twisted to interact with the glib mainloop.
This is like gtk2, but slightly faster and does not require a working
$DISPLAY. However, you cannot run GUIs under this reactor: for that you must
use the gtk2reactor instead.
In order to use this support, simply do the following::
|... |
from oslo_config import cfg
from murano.common.messaging import mqclient
CONF = cfg.CONF
def create_rmq_client():
rabbitmq = CONF.rabbitmq
connection_params = {
'login': rabbitmq.login,
'password': rabbitmq.password,
'host': rabbitmq.host,
'port': rabbitmq.port,
'virt... |
from .resource import Resource
class RestoreResponse(Resource):
"""Response for an app restore request.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:param name: Resource Name.
:type name: str
:param k... |
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django_comment_common.models import Role
from django.contrib.auth.models import User
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--remove',
ac... |
# -*- coding:utf-8 -*-
import unittest
import logging
import time
from ..common.utils import (
next_minute,
pre_day,
next_day,
next_trading_day,
weekday,
second2time,
TList,
... |
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = """
options:
path:
description:
- 'path to the file being managed. Aliases: I(dest), I(name)'
required: true
default: []
aliases: ['dest', 'name']
state:
description:
- If C(directory),... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.