content stringlengths 4 20k |
|---|
import sys
import subprocess
from string import Template
TEST_NAME = '../tests/fuzz_dma/test_clang_dma_generated_{0}.c'
def main():
with open('test_template.c') as template_file:
template = Template(template_file.read())
try:
tests = subprocess.check_output(
['../x86-obj/generate_... |
'''OpenGL extension NV.fragment_program2
This module customises the behaviour of the
OpenGL.raw.GL.NV.fragment_program2 to provide a more
Python-friendly API
Overview (from the spec)
This extension, like the NV_fragment_program_option extension, provides
additional fragment program functionality to extend the s... |
import sys
import time
py3k = sys.version_info >= (3, 0)
py33 = sys.version_info >= (3, 3)
py2k = sys.version_info < (3,)
py26 = sys.version_info >= (2, 6)
py27 = sys.version_info >= (2, 7)
jython = sys.platform.startswith('java')
win32 = sys.platform.startswith('win')
pypy = hasattr(sys, 'pypy_version_info')
if py3k... |
import MORAS as vc
import cv2
import numpy as np
'''**********************
IMAGES
**********************'''
img1 = cv2.imread('images/experiments/jardi2.jpg')
img1, imgROIGray = vc.imgPrep(img1)
img2 = cv2.imread('images/experiments/jardi_2.jpg')
img2, imgRobotGray = vc.imgPrep(img2)
psAlg = vc._HARRIS
feAlg = vc._S... |
from test.test_support import TestFailed
# A test for SF bug 422177: manifest float constants varied way too much in
# precision depending on whether Python was loading a module for the first
# time, or reloading it from a precompiled .pyc. The "expected" failure
# mode is that when test_import imports this after al... |
from ..utils import disconnect_signals
def pytest_runtest_setup(item):
disconnect_signals() |
"""
Test utilities for OAuth access token exchange
"""
import provider.constants
from social.apps.django_app.default.models import UserSocialAuth
from third_party_auth.tests.utils import ThirdPartyOAuthTestMixin
class AccessTokenExchangeTestMixin(ThirdPartyOAuthTestMixin):
"""
A mixin to define test cases fo... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
CSRF_ENABLED = True
SECRET_KEY = '\2\1thisismyscretkey\1\2\e\y\y\h'
OPENID_PROVIDERS = [
{'name': 'Google', 'url': 'https://www.google.com/accounts/o8/id'},
{'name': 'Yahoo', 'url': 'https://me.yahoo.com'},
{'name': 'AOL', 'url': 'http://open... |
"""
Views related to course tabs
"""
from student.auth import has_course_author_access
from util.json_request import expect_json, JsonResponse
from django.http import HttpResponseNotFound
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.views.dec... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.forms.util import flatatt, ErrorDict, ErrorList
from django.test import TestCase
from django.utils.safestring import mark_safe
from django.utils import six
from django.utils.translation import... |
import argparse
import getpass
import pyVim.connect as connect
# Demonstrates some simple working with sessions actions. By common sense
# you should expect that the session is None when you've logged out and
# you will lose the ability to see any session ID. It would be a massive
# security hole to allow people to s... |
"""Constants for `gwdetchar`
"""
import os
from collections import OrderedDict
from gwpy.segments import Segment
__author__ = 'Duncan Macleod <<EMAIL>>'
IFO = os.getenv('IFO', None)
ifo = os.getenv('ifo', IFO.lower() if IFO else None)
SITE = os.getenv('SITE', None)
site = os.getenv('site', SITE.lower() if SITE else... |
# I extract according to objkey, replace NAN, and find cosmics.
# All in one script.
# The database update is done right at the beginning, i.e.
# no need to wait that I'm done before launching the next scripts
# that modify the db.
execfile("../config.py")
from kirbybase import KirbyBase, KBError
from variousfct im... |
from __future__ import unicode_literals
import frappe
import frappe.model.meta
import frappe.defaults
from frappe.utils.file_manager import remove_all
from frappe import _
from rename_doc import dynamic_link_queries
from frappe.model.naming import revert_series_if_last
def delete_doc(doctype=None, name=None, force=0,... |
"""Config Drive v2 helper."""
import os
import shutil
from oslo_concurrency import processutils
from oslo_utils import fileutils
from oslo_utils import units
import six
import nova.conf
from nova import exception
from nova.objects import fields
import nova.privsep.fs
from nova import utils
from nova import version
... |
#!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
try:
import pypandoc
README = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
README = open('README.md').read()
setup(
name='django-datatable',
version='0.2.1',
author='shymonk',
author_ema... |
"""Implementation of the DOM Level 3 'LS-Load' feature."""
import copy
import xml.dom
from xml.dom.NodeFilter import NodeFilter
__all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"]
class Options:
"""Features object that has variables set for each DOMBuilder feature.
The DOMBuilder class uses a... |
import logging, time
import plugins
logger = logging.getLogger( __name__ )
# logger.setLevel( 'DEBUG' )
bot = plugins.tracking.bot
@bot.message_handler( func=lambda message: True )
def reply( message ):
localtime = time.localtime( time.time() )
t_hour = localtime.tm_hour
if message.chat.id < 0:
lo... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import copy
import json
import os
from yaml import load, YAMLError
from ansible.errors import AnsibleParserError
from ansible.errors.yaml_strings import YAML_SYNTAX_ERROR
from ansible.parsing.vault import VaultLib
from ansible.pa... |
""" This file contains functions to generate and verify tokens for Flask-User.
Tokens contain an encoded user ID and a signature. The signature is managed by the itsdangerous module.
:copyright: (c) 2013 by Ling Thio
:author: Ling Thio (<EMAIL>)
:license: Simplified BSD License, see LICENSE.txt for mor... |
"""
Useful auxilliary data structures for query construction. Not useful outside
the SQL domain.
"""
class EmptyResultSet(Exception):
pass
class MultiJoin(Exception):
"""
Used by join construction code to indicate the point at which a
multi-valued join was attempted (if the caller wants to treat that
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
from copy import deepcopy
from ansible.module_utils.basic import AnsibleModule
from... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
RESULTS = """
"""
import json
from ansible.module_utils.basic import AnsibleModule
from an... |
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
"""Write worksheets to xml representations in an optimized way"""
import atexit
from inspect import isgenerator
import os
from tempfile import NamedTemporaryFile
from openpyxl.cell import Cell
from openpyxl.worksheet import Worksheet
from ope... |
"""
Copyright [Participants AERIUS Masterclass: Marco Duiker, Peer vd Sande, Alex Bouthoorn, Laurens vd Burgt, Rik Zegers, Lotte Dijk, Kaj Fabri, Esther Kokmeyer, Christa Blokhuis, Anneke Donkersloot, Japer Harbers, Roy Laurijsse, Luc Meegens, Marike Aalbers]
Licensed under the Apache License, Version 2.0 (the "Licens... |
"""Classes and functions for manipulating strings into dates.
Some parts are specific to Google Calendar."""
__author__ = '<EMAIL> (Tom Miller)'
import datetime
import re
import googlecl.base
import time
import logging
LOG = logging.getLogger("date.py")
QUERY_DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.000Z'
ACCEPTED_DAY_TIME... |
from collections import OrderedDict
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph.parametertree as pt
import numpy as np
class CellSelector(QtCore.QObject):
"""Select a single cell from a list of cells or from a pre-segmented image.
Signals
-------
cell_selection_... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon.utils import memoized
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.networks.ports \
import views as project_... |
from __future__ import division
from .gameitem import GameItem
from .wall import WallShape
def RoomBounds(xsize, ysize, zsize):
bounds = set()
bounds = bounds.union( set(
(x, y, z)
for x in [-1, xsize]
for y in xrange(0, ysize)
for z in xrange(0, zsize)
) )
bounds = bo... |
INF = 1e30
EPS = 1e-6
class Vec:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def __neg__(self):
return Vec(-self.x, -self.y, -self.z)
def __add__(self, rhs):
return Vec(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
def __sub__(self, rhs):
return Ve... |
# -*- coding: utf-8 -*-
r"""
werkzeug.contrib.iterio
~~~~~~~~~~~~~~~~~~~~~~~
This module implements a :class:`IterIO` that converts an iterator into
a stream object and the other way round. Converting streams into
iterators requires the `greenlet`_ module.
To convert an iterator into a stream... |
# -*- coding: utf-8 -*-
from django.utils.six.moves import zip
def copy_plugins_to(old_plugins, to_placeholder,
to_language=None, parent_plugin_id=None, no_signals=False):
"""
Copies a list of plugins to a placeholder to a language.
"""
# TODO: Refactor this and copy_plugins to cle... |
from openerp.tests import common
from openerp import workflow
from openerp.tools.safe_eval import safe_eval
class testPurchasePartialInvoicing(common.TransactionCase):
def setUp(self):
super(testPurchasePartialInvoicing, self).setUp()
self.context = self.env['res.users'].context_get()
sel... |
"""## Placeholders
TensorFlow provides a placeholder operation that must be fed with data
on execution. For more info, see the section on [Feeding
data](../../how_tos/reading_data/index.md#feeding).
@@placeholder
@@placeholder_with_default
For feeding `SparseTensor`s which are composite type,
there is a convenience... |
"""Tests for distutils.command.build_scripts."""
import os
import unittest
from distutils.command.build_scripts import build_scripts
from distutils.core import Distribution
import sysconfig
from distutils.tests import support
from test.test_support import run_unittest
class BuildScriptsTestCase(support.TempdirMana... |
"""
Unit tests for extension extended attribute
"""
from oslo.config import cfg
import webob.exc as webexc
import neutron
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.common import config
from neutron import manager
from neutron.plugins.common import constants
from neutron.plu... |
from PIL import Image
from random import randrange
class PileMosaic:
def __init__(self):
self.width, self.height = 2380, 2800
self.filename = "pile_mosaic.png"
self.crema = (240, 233, 227)
self.choco = (89, 62, 53)
self.luna = (43, 97, 123)
self.latte = (195, 175, 14... |
class MovableTypeExport(object):
def __init__(self):
# List of MovalbeTypePost
self.posts = []
def ToString(self):
retval = ''
# Serialize all of the posts
for post in self.posts:
retval += post.ToString()
return retval
class MovableTypePost(object):
def __init__(self):
self... |
from datetime import datetime
import noaa
import geonames as gn
import wunderground
from utils import heading, tomph, ctof, iszip
def weather_memo(f):
'''Memoization decorator for caching the results of initiating
Weather objects.'''
cache = {}
def memoized(x, sec):
if x not in cache or (x in... |
__author__ = 'Brian Beck'
## {{{ http://code.activestate.com/recipes/410692/ (r8)
# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
class switch(object):
def __init__(se... |
from . import models
from .init_hook import pre_init_hook, post_init_hook, uninstall_hook |
"""
Sensors of a KNX Device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/knx/
"""
from enum import Enum
import logging
import voluptuous as vol
from homeassistant.const import (
CONF_NAME, CONF_MAXIMUM, CONF_MINIMUM,
CONF_TYPE, TEMP_CELSIUS
... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class GetEntityByOutsideID(Choreography):
def __init__(self, temboo_session):
"""
C... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import os
class Zfs(object):
def __init__(self, module, name, properties):
self.module = module
self.name = name
self.properties = properties
self.cha... |
"""
Example Airflow DAG that interacts with Google Data Catalog service
"""
from google.cloud.datacatalog_v1beta1 import FieldType, TagField, TagTemplateField
from airflow import models
from airflow.operators.bash_operator import BashOperator
from airflow.providers.google.cloud.operators.datacatalog import (
Cloud... |
"""DNS rdatasets (an rdataset is a set of rdatas of a given type and class)"""
import random
from io import StringIO
import struct
import dns.exception
import dns.rdatatype
import dns.rdataclass
import dns.rdata
import dns.set
from ._compat import string_types
# define SimpleSet here for backwards compatibility
Simp... |
import re
from typing import Any, Dict, List, Optional, Tuple
# stubs
ZerverFieldsT = Dict[str, Any]
SlackToZulipUserIDT = Dict[str, int]
AddedChannelsT = Dict[str, Tuple[str, int]]
# Slack link can be in the format <http://www.foo.com|www.foo.com> and <http://foo.com/>
LINK_REGEX = r"""
(<) ... |
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.utils.functional import SimpleLazyObject
from django.utils.text import format_lazy
def prefix_validation_error(error, prefix, code, params):
"""
Prefix a validation error message while maintaining the exist... |
#!/usr/bin/python
#
# Server that will accept connections from a Vim channel.
# Run this server and then in Vim you can open the channel:
# :let handle = ch_open('localhost:8765')
#
# Then Vim can send requests to the server:
# :let response = ch_sendexpr(handle, 'hello!')
#
# And you can control Vim by typing a JSON... |
"""TabIndex displayed in the statusbar."""
from PyQt5.QtCore import pyqtSlot
from qutebrowser.mainwindow.statusbar import textbase
class TabIndex(textbase.TextBase):
"""Shows current tab index and number of tabs in the statusbar."""
@pyqtSlot(int, int)
def on_tab_index_changed(self, current, count):
... |
from openerp.osv import fields,osv
import openerp.addons.decimal_precision as dp
class location_income_tax(osv.osv):
_name = "location.income.tax"
_description = "Holds data of yearly income statement"
_columns = {
'location_id' : fields.many2one('stock.location','Location', select=True, req... |
import sys
import cherrypy
from cherrypy._cpcompat import basestring, ntou, json, json_encode, json_decode
def json_processor(entity):
"""Read application/json data into request.json."""
if not entity.headers.get(ntou("Content-Length"), ntou("")):
raise cherrypy.HTTPError(411)
body = entity.fp... |
from django.test import TestCase
from curious import model_registry
from curious.query import Query
from curious_tests.models import Blog, Entry, Author
from curious_tests import assertQueryResultsEqual
import curious_tests.models
class TestQueryFilters(TestCase):
def setUp(self):
blog = Blog(name='Databases')
... |
import unittest2
import webapp2
import webtest
from datetime import datetime
from google.appengine.ext import testbed
from google.appengine.ext import ndb
from webapp2_extras.routes import RedirectRoute
from consts.auth_type import AuthType
from consts.district_type import DistrictType
from consts.event_type import E... |
from sys import argv
from Bio import SeqIO
import pandas as pd
import re
import itertools
import os.path
script, strain_name, cluster_number = argv
table1_df = pd.read_csv('../outputs/tables/%s_%s_table1.csv'%(strain_name,cluster_number), sep='\t')
def find_boarders(file_name):
with open(file_name).xreadlines() ... |
'''
Copyright (C) 2015 Dato, Inc.
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
'''
import os
import time
import logging
import platform
import sys as _sys
class GraphLabConfig:
__slots__ = ['graphlab_server', 'server_addr... |
"Database cache backend."
import base64
from datetime import datetime
from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.db import DatabaseError, connections, router, transaction
from django.db.backends.utils import typecast_timestamp
from django.utils i... |
"""This is the Bokeh charts interface. It gives you a high level API to build
complex plot is a simple way.
This is the Step class which lets you build your Step charts just
passing the arguments to the Chart class and calling the proper functions.
"""
# ----------------------------------------------------------------... |
"""
=============================
Species distribution modeling
=============================
Modeling species' geographic distributions is an important
problem in conservation biology. In this example we
model the geographic distribution of two south american
mammals given past observations and 14 environmental
varia... |
from corehq.apps.reports.graph_models import MultiBarChart, Axis
from custom.care_pathways.reports import CareBaseReport
from custom.care_pathways.filters import GeographyFilter, GenderFilter, GroupLeadershipFilter, CBTNameFilter, PPTYearFilter, ScheduleFilter, TableCardGroupByFilter, TableCardTypeFilter
from dimagi.ut... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError
class Group:
''' a group of ansible hosts '''
#__slots__ = [ 'name', 'hosts', 'vars', 'child_groups', 'parent_groups', 'depth', '_hosts_cache' ]
def __init__(self, name=None):
... |
"""Talk to a DNS server."""
from __future__ import generators
import errno
import select
import socket
import struct
import sys
import time
import dns.exception
import dns.inet
import dns.name
import dns.message
import dns.rdataclass
import dns.rdatatype
class UnexpectedSource(dns.exception.DNSException):
"""Ra... |
from boto.compat import json
from tests.compat import mock, unittest
from tests.unit.cloudsearch.test_search import HOSTNAME, \
CloudSearchSearchBaseTest
from boto.cloudsearch.search import SearchConnection, SearchServiceException
def fake_loads_value_error(content, *ar... |
from socket import *
from threading import Thread
import sys
import glob
class Server(object):
def __init__(self):
""" Função que prepara o socket """
try:
self.serverSocket = socket(AF_INET, SOCK_STREAM)
except (error):
print("Failed to create a Socket.")
... |
"""Strptime-related classes and functions.
CLASSES:
LocaleTime -- Discovers and stores locale-specific time information
TimeRE -- Creates regexes for pattern matching a string of text containing
time information
FUNCTIONS:
_getlang -- Figure out what language is being used for the locale
... |
"""
Top level of the fedhubsync Flask application.
"""
import logging
import logging.handlers
import os
import sys
import urllib2
import flask
from subprocess import Popen, PIPE
__version__ = '0.1.0'
__api_version__ = '0.1.0'
APP = flask.Flask(__name__)
APP.config.from_object('fedhubsync.default_config')
if 'FE... |
# gravity deposition, continuing with oedometric test after stabilization
# shows also how to run parametric studies with yade-batch
# The components of the batch are:
# 1. table with parameters, one set of parameters per line (ccc.table)
# 2. readParamsFromTable which reads respective line from the parameter file
# 3... |
import rpcServer
import up2dateErrors
import capabilities
import sys
import xmlrpclib
import OpenSSL
class _DoCallWrapper(object):
"""
A callable object that will handle multiple levels of attributes,
and catch exceptions.
"""
def __init__(self, server, method_name):
self._server = serve... |
import sys
def decompress_line(line):
if "(" not in line:
# print "not in", line
return len(line), 1
# There's at least one (marker).
length = 0
in_marker = False
collecting_rep = False
marker = ""
rep = ""
nchars = 0
nreps = 0
for char in line:
if coll... |
import os
import subprocess
import unittest
class TestMakeDocs(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_make_docs(self):
cmd = "make -C docs/ html"
project_root = os.path.join(os.path.dirname(__file__), "..", "..")
process = sub... |
from a10_openstack_lib.resources import validators
EXTENSION = 'a10-scaling-group'
SERVICE = "A10_SCALING_GROUP"
SCALING_GROUPS = 'a10_scaling_groups'
SCALING_GROUP = 'a10_scaling_group'
SCALING_GROUP_WORKERS = 'a10_scaling_group_workers'
SCALING_GROUP_WORKER = 'a10_scaling_group_worker'
SCALING_POLICIES = 'a10_sc... |
import re
import time
import shlex
from ansible.module_utils.basic import BOOLEANS_TRUE, BOOLEANS_FALSE
from ansible.module_utils.basic import get_exception
from ansible.module_utils.six import string_types, text_type
from ansible.module_utils.six.moves import zip
def to_list(val):
if isinstance(val, (list, tuple... |
"""Bip-0070-related functionality
Creates http response objects suitable for use with
bitcoin bip 70 using googles protocol buffers.
"""
import urllib2
# https://github.com/bitcoin/bips/blob/master/bip-0070/paymentrequest.proto
import payments_pb2
o = payments_pb2
import bitcoin
#bitcoin.SelectParams('testnet')
fro... |
#!/usr/bin/env python
from setuptools import setup
import os, re
PKG='oauth2'
VERSIONFILE = os.path.join('oauth2', '_version.py')
verstr = "unknown"
try:
verstrline = open(VERSIONFILE, "rt").read()
except EnvironmentError:
pass # Okay, there is no version file.
else:
MVSRE = r"^manual_verstr *= *['\"]([^'\... |
import urllib2
from PIL import Image
from xml.dom.minidom import parse
import dateutil.parser
from datetime import timedelta
from cStringIO import StringIO
import Cache
from ftplib import FTP
class BOM:
deflayers = ['background', 'topography', 'range',
'locations', 'copyright', 'legend.0']
backlaye... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from re import compile as re_compile, IGNORECASE
from ansible.errors import AnsibleError
from ansible.module_utils.six.moves import xrange
from ansible.parsing.splitter import parse_kv
from ansible.plugins.lookup import LookupBase... |
# -*- coding: utf-8 -*-
# pylint: disable=
""" Paver Code Quality Tasks.
Copyright (c) 2011 The PyroScope Project <<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 versio... |
'''
Dummy Socks5 server for testing.
'''
import socket, threading, queue
import traceback, sys
### Protocol constants
class Command:
CONNECT = 0x01
class AddressType:
IPV4 = 0x01
DOMAINNAME = 0x03
IPV6 = 0x04
### Utility functions
def recvall(s, n):
'''Receive n bytes from a socket, or fail'''
... |
import pytest
import subprocess
import json
import sys
from numpy.distutils import _shell_utils
argv_cases = [
[r'exe'],
[r'path/exe'],
[r'path\exe'],
[r'\\server\path\exe'],
[r'path to/exe'],
[r'path to\exe'],
[r'exe', '--flag'],
[r'path/exe', '--flag'],
[r'path\exe', '--flag'],
... |
"""
Tests for parts.py contents directive.
"""
from __init__ import DocutilsTestSupport
def suite():
s = DocutilsTestSupport.ParserTestSuite()
s.generateTests(totest)
return s
totest = {}
totest['contents'] = [
["""\
.. contents::
""",
"""\
<document source="test data">
<topic classes="contents" ids... |
"""pypyr step that parses yaml for string substitutions, writes output."""
import logging
from pypyr.steps.dsl.fileinoutrewriter import ObjectRewriterStep
from pypyr.utils.filesystem import YamlRepresenter
# logger means the log level will be set correctly
logger = logging.getLogger(__name__)
def run_step(context):
... |
# encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
compat_urllib_parse,
ExtractorError,
)
class NaverIE(InfoExtractor):
_VALID_URL = r'https?://(?:m\.)?tvcast\.naver\.com/v/(?P<id>\d+)'
_TEST = {
'url': 'http://tvcast.... |
from securionpay.resource import Resource
class CustomerRecords(Resource):
def buy(self, params):
return self._post('/customer-records', params)
def refresh(self, customer_record_id, params=None):
return self._post('/customer-records/%s' % customer_record_id, params)
def get(self, custom... |
"""
Modified version of gyp_skia, used by gyp_to_android.py to generate Android.mk
"""
import os
import sys
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
# Unlike gyp_skia, this file is nested deep inside Skia. Find Skia's trunk dir.
# This line depends on the fact that the script is three levels deep
# (s... |
'''
Created on 07.04.2015
@author: marscher
'''
from __future__ import absolute_import
from __future__ import print_function
import shutil
import tempfile
import unittest
from pyemma.coordinates.data.numpy_filereader import NumPyFileReader
from logging import getLogger
import numpy as np
class TestNumPyFileRead... |
import base64
import urllib
def xunlei_url_encode(url):
return 'thunder://'+base64.encodestring('AA'+url+'ZZ').replace('\n', '')
def xunlei_url_decode(url):
assert url.startswith('thunder://')
url = base64.decodestring(url[10:])
assert url.startswith('AA') and url.endswith('ZZ')
return url[2:-2]
def flashget_ur... |
from __future__ import unicode_literals
from django.apps import apps
from django.db import models
from django.db.utils import IntegrityError, OperationalError, ProgrammingError
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
class Cont... |
import logging
import openerp
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools.translate import _
class pos_config(osv.osv):
_inherit = 'pos.config'
_columns = {
'discount_pc': fields.float('Discount Percentage', help='The discount percentage'),
'discount_prod... |
from hashlib import blake2b
from requests import HTTPError
from blobstash.base.client import Client
from blobstash.base.error import BlobStashError
from blobstash.base.iterator import BasePaginationIterator
class BlobStoreError(BlobStashError):
"""Base error for the blobstore module."""
class BlobNotFoundErro... |
#-*- coding: cp936 -*-
import math
from PIL import Image
def swirl(image, degree = 50):
'''
@Ч¹û£ºäöÎУ¬¶ÔͼÏñ½øÐÐäöÎÐÌØÐ§´¦Àí
@param image: instance of Image
@param degree: ±íʾäöÎеĴóС[0, 100]
@return: instance of Image
'''
degree = min(max(0, degree), 100) / 1000.0
if image... |
"""Ops for building neural network layers, regularizers, summaries, etc.
See the @{$python/contrib.layers} guide.
@@avg_pool2d
@@avg_pool3d
@@batch_norm
@@convolution2d
@@convolution3d
@@conv2d_in_plane
@@convolution2d_in_plane
@@conv2d_transpose
@@convolution2d_transpose
@@conv3d_transpose
@@convolution3d_transpose
... |
import warnings
from django.conf import settings
from django.contrib.auth.models import User, Group, Permission, AnonymousUser
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.test import TestCase
from django... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User administration plugin (LDAP extension)
Copyright 2011 - 2016 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import sys
from omero.cli import CLI, ExceptionHandler, admin_only, UserGroupControl
fr... |
''' Nansat NetCDF-CF mapper
Check CF-compliance of your files here:
http://cfconventions.org/compliance-checker.html
'''
import warnings, os, datetime
import numpy as np
import collections
from nansat.utils import gdal
from dateutil.parser import parse
from netCDF4 import Dataset
from nansat.vrt import VRT
... |
"""
Request Body validating middleware.
"""
import functools
from nova.api.openstack import api_version_request as api_version
from nova.api.validation import validators
def schema(request_body_schema, min_version=None, max_version=None):
"""Register a schema to validate request body.
Registered schema wi... |
# -*- coding: utf-8 -*-
import re
import urllib
from module.plugins.captcha.ReCaptcha import ReCaptcha
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class DepositfilesCom(SimpleHoster):
__name__ = "DepositfilesCom"
__type__ = "hoster"
__version__ = "0.58"
__stat... |
"""
Tests for the `api_admin` api module.
"""
import json
from rest_framework.reverse import reverse
from django.contrib.auth.models import User
from django.test import TestCase
from openedx.core.djangoapps.api_admin.tests import factories
from openedx.core.djangolib.testing.utils import skip_unless_lms
from student... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import os
import os.path
import pipes
import subprocess
import traceback
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.plugins.connection import ConnectionBase
from ... |
"""Volume copy throttling helpers."""
import contextlib
from oslo_concurrency import processutils
from oslo_log import log as logging
from cinder import exception
from cinder.i18n import _LW, _LE
from cinder import utils
LOG = logging.getLogger(__name__)
class Throttle(object):
"""Base class for throttling ... |
from openerp.osv import fields, osv
class res_partner(osv.osv):
_inherit = 'res.partner'
_columns = {
'speaker': fields.boolean('Speaker', help="Check this box if this contact is a speaker."),
'event_ids': fields.one2many('event.event', 'main_speaker_id', 'Events', readonly=True),
'eve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.