content stringlengths 4 20k |
|---|
"""
Exception definitions.
Deprecated since v0.7.1. Use 'keystoneclient.exceptions' instead of
this module.
"""
import warnings
from keystoneclient.exceptions import * # noqa
warnings.warn("The 'keystoneclient.apiclient.exceptions' module is deprecated "
"since v.0.7.1. Use 'keystoneclient.except... |
#Why is there so many races
#This is the holding file for information on all the races
#I hate this. So much
import Laws
#This means that it will have access to the laws set out in other files
#This shall be long winded and unfun
if Laws.user_race == 'Aarakocra':
print('Something about being BS')
... |
"""Provide the Auth class."""
from prawcore import (
Authorizer,
ImplicitAuthorizer,
UntrustedAuthenticator,
session,
)
from .base import PRAWBase
from ..exceptions import ClientException
class Auth(PRAWBase):
"""Auth provides an interface to Reddit's authorization."""
@property
def limi... |
"""This module wraps Android's adb tool.
This is a thin wrapper around the adb interface. Any additional complexity
should be delegated to a higher level (ex. DeviceUtils).
"""
import errno
import os
from pylib import cmd_helper
from pylib.device import decorators
from pylib.device import device_errors
_DEFAULT_TI... |
#!/usr/bin/python
"""
Copyright (C) International Business Machines Corp., 2005, 2006
Authors: Dan Smith <<EMAIL>>
Daniel Stekloff <<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 Foundat... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy
from tensorflow.contrib.checkpoint.python import python_state
from tensorflow.python.client import session
from tensorflow.python.eager import test
from tensorflow.python.framework impo... |
"""
Matplotlib Animation Example
author: Jake Vanderplas
email: <EMAIL>
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3... |
# -*- 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):
# Removing unique constraint on 'IntranetProfile', fields ['user']
db.delete_unique(u'intranet_intranetprofi... |
"""
Data files helpers.
"""
import shutil
import os
from weblate import appsettings
def create_and_check_dir(path):
"""Ensure directory exists and is writable by us"""
if not os.path.exists(path):
os.makedirs(path)
else:
if not os.access(path, os.W_OK):
raise OSError(
... |
"""
WSGI config for test_remote_project project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_AP... |
__version__ = "0.4"
from . import Image, ImageFile, ImagePalette
from ._binary import i8, i16be as i16, i32be as i32
MODES = {
# (photoshop mode, bits) -> (pil mode, required channels)
(0, 1): ("1", 1),
(0, 8): ("L", 1),
(1, 8): ("L", 1),
(2, 8): ("P", 1),
(3, 8): ("RGB", 3),
(4, 8): ("CMY... |
import logging
import json
import requests
logging.basicConfig(level=logging.DEBUG)
url = 'https://review.openstack.org/projects/'
# This is what a project looks like
'''
"openstack-attic/akanda": {
"id": "openstack-attic%2Fakanda",
"state": "READ_ONLY"
},
'''
def is_in_openstack_namespace(proj):
# ... |
class ModuleDocFragment(object):
DOCUMENTATION = r'''
options:
client:
description:
- A dict object containing connection details.
suboptions:
version:
description:
- REST API version.
type: str
choices: [ v1 ]
default: v1
scheme:
descrip... |
# -*- encoding: utf-8 -*-
"""
Tests for django.core.servers.
"""
from __future__ import unicode_literals
import contextlib
import errno
import os
import socket
from django.core.exceptions import ImproperlyConfigured
from django.test import LiveServerTestCase, override_settings
from django.utils._os import upath
from ... |
from django.conf import settings
from django.db import models
from django.utils import timezone
class NameAsStrMixin(object):
name = None
def __str__(self, *args, **kwargs):
return self.name
class UserTimeStampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True, editable=Fal... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class mrp_config_settings(osv.osv_memory):
_name = 'mrp.config.settings'
_inherit = 'res.config.settings'
_columns = {
'module_mrp_repair': fields.boolean("Manage repairs of products ",
help='Allows to manage all... |
# You are given an n x n 2D matrix representing an image.
# Rotate the image by 90 degrees (clockwise).
# Note:
# You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
# Example 1:
# Given input matrix =
# [
# [1... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Developed by Massimo Di Pierro <<EMAIL>>,
limodou <<EMAIL>> and srackham <<EMAIL>>.
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import os
import sys
import code
import logging
import types
import re
import... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# http://binux.me
# Created on 2014-10-07 10:33:38
import os
import six
import time
import unittest2 as unittest
from pyspider.libs import utils
class TestMessageQueue(object):
@classmethod
def setUpCla... |
"""
Parsers are used to parse the content of incoming HTTP requests.
They give us a generic way of being able to handle various media types
on the request, such as form content or json encoded data.
"""
from django.conf import settings
from django.core.files.uploadhandler import StopFutureHandlers
from django.http imp... |
"""Functions to plot on circle as for connectivity
"""
from __future__ import print_function
# Authors: Alexandre Gramfort <<EMAIL>>
# Denis Engemann <<EMAIL>>
# Martin Luessi <<EMAIL>>
#
# License: Simplified BSD
from itertools import cycle
from functools import partial
import numpy as np
from .... |
"""
OpenStreetMap OAuth support.
This adds support for OpenStreetMap OAuth service. An application must be
registered first on OpenStreetMap and the settings
SOCIAL_AUTH_OPENSTREETMAP_KEY and SOCIAL_AUTH_OPENSTREETMAP_SECRET
must be defined with the corresponding values.
More info: http://wiki.openstreetmap.org/wiki/... |
#!/usr/bin env python
from tests.unit import AWSMockServiceTestCase
from boto.cloudsearch.domain import Domain
from boto.cloudsearch.layer1 import Layer1
class TestCloudSearchCreateDomain(AWSMockServiceTestCase):
connection_class = Layer1
def default_body(self):
return b"""
<CreateDomainResponse xml... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from sklearn import datasets
from sklearn import metrics
from sklearn.cross_validation import train_test_split
import tensorflow as tf
def optimizer_exp_decay():
global_step = tf.contrib.framework.get_or_cr... |
"""
Acceptance tests for Home Page (My Courses / My Libraries).
"""
from bok_choy.web_app_test import WebAppTest
from opaque_keys.edx.locator import LibraryLocator
from ...fixtures import PROGRAMS_STUB_URL
from ...fixtures.config import ConfigModelFixture
from ...fixtures.programs import ProgramsFixture
from ...pages.... |
"""
This module contains helper functions for controlling caching. It does so by
managing the "Vary" header of responses. It includes functions to patch the
header of response objects directly and decorators that change functions to do
that header-patching themselves.
For information on the Vary header, see:
http... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A tool to help keep .mailmap and AUTHORS up-to-date.
"""
# TODO:
# - Check doc/src/aboutus.rst
# - Make it easier to update .mailmap or AUTHORS with the correct entries.
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys... |
"""A shim module for deprecated imports
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
import types
from .importstring import import_item
class ShimWarning(Warning):
"""A warning to show when a module has moved, and a shim is in its place."""
... |
# -*- coding: utf-8 -*-
# Automatic provisioning of Azure Queues.
import os
import azure
from nixops.util import attr_property
from nixops.azure_common import StorageResourceDefinition, StorageResourceState
from nixops.resources.azure_resource_group import AzureResourceGroupState
from nixops.resources.azure_storage... |
from __future__ import absolute_import, division, print_function
import datashape
from datashape import Record, DataShape, dshape, TimeDelta
from datashape import coretypes as ct
from datashape.predicates import iscollection, isboolean, isnumeric, isdatelike
from numpy import inf
from odo.utils import copydoc
import t... |
#!/usr/bin/python
import urllib2
from bs4 import BeautifulSoup
import time
import datetime
import MySQLdb
import sys, os
sys.path.append(os.path.abspath('{0}/../../'.format(os.path.abspath(__file__))))
from laptimes import config
def main():
while True:
racer_id = thread_control()
if racer_id:
print 'proces... |
{
'name': 'Stock picking lines with sequence number',
'version': '0.1',
'category': 'Warehouse Management',
'description': '''
Provide a new field on stock moves, allowing to manage the orders of moves
in a picking.
''',
'author': "Camptocamp,Odoo Community Association (OCA)",
'website': 'ht... |
import datetime
from django.shortcuts import render
from django.utils import timezone
from django.db.models import Count
from airmozilla.base.utils import paginate
from airmozilla.search.models import LoggedSearch
from .decorators import superuser_required
@superuser_required
def loggedsearches(request):
searc... |
from openerp import exceptions
from openerp.osv import osv, fields
from openerp.tools.translate import _
class ir_filters(osv.osv):
_name = 'ir.filters'
_description = 'Filters'
def _list_all_models(self, cr, uid, context=None):
cr.execute("SELECT model, name FROM ir_model ORDER BY name")
... |
#
# ASN.1 subtype constraints classes.
#
# Constraints are relatively rare, but every ASN1 object
# is doing checks all the time for whether they have any
# constraints and whether they are applicable to the object.
#
# What we're going to do is define objects/functions that
# can be called unconditionally ... |
"""Class representing application/* type MIME documents."""
__all__ = ["MIMEApplication"]
from email import encoders
from email.mime.nonmultipart import MIMENonMultipart
class MIMEApplication(MIMENonMultipart):
"""Class for generating application/* MIME documents."""
def __init__(self, _data, _subtype='oct... |
'''
- login and get token
- process 2FA if 2FA is setup for this account
- Get cashflow earnings for a given user
'''
import requests
import json
get_token_url = "https://api.canopy.cloud:443/api/v1/sessions/"
validate_otp_url = "https://api.canopy.cloud:443/api/v1/sessions/otp/validate.json" #calling the productio... |
import pytest
import numpy as np
from astropy import units as u
from astropy.coordinates.builtin_frames import ICRS, Galactic, Galactocentric
from astropy.coordinates import builtin_frames as bf
from astropy.coordinates import galactocentric_frame_defaults
from astropy.units import allclose as quantity_allclose
from a... |
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# from __future__ import unicode_literals
__author__ = "d01"
__email__ = "<EMAIL>"
__copyright__ = "Copyright (C) 2015-16, Florian JUNG"
__license__ = "MIT"
__version__ = "1.0.0"
__date_... |
"""
Tests for states.py.
"""
from __init__ import DocutilsTestSupport
def suite():
s = DocutilsTestSupport.ParserTestSuite()
s.generateTests(totest)
return s
totest = {}
totest['indented_literal_blocks'] = [
["""\
A paragraph::
A literal block.
""",
"""\
<document source="test data">
<paragraph... |
from gym.envs.mujoco.half_cheetah import HalfCheetahEnv
from gym.envs.mujoco.walker2d import Walker2dEnv
from gym.envs.mujoco import mujoco_env
import numpy as np
import os
def tolerance(x, bounds, margin):
'''Returns 1 when x is within the bounds, and decays sigmoidally
when x is within a certain margin outs... |
from __future__ import unicode_literals
import base64
import logging
import string
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.sessions.exceptions import SuspiciousSession
from django.core.exceptions import SuspiciousOperation
from django.utils import timezone
from dj... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from django.db import models
from goflow.workflow.models import Transition
from goflow.workflow.decorators import allow_tags
from django.conf import settings
class DefaultAppModel(models.Model):
"""Default implementation object class for process instances.... |
import types
import numpy
import _ni_support
import _nd_image
def _get_output_fourier(output, input):
if output is None:
if input.dtype.type in [numpy.complex64, numpy.complex128,
numpy.float32]:
output = numpy.zeros(input.shape, dtype = input.dtype)
else... |
import sys
from collections import deque, OrderedDict
from time import time
from itertools import chain
from hashlib import sha256
from . import bounds, db, sanitized as conf
from .shared import get_logger
from .utils import dump_pickle, load_pickle, get_current_hour, time_until_time
class BaseSpawns:
"""Manage... |
import mock
from oslo_utils import uuidutils
from neutron.agent.l3 import dvr_snat_ns
from neutron.agent.l3 import namespace_manager
from neutron.agent.l3 import namespaces
from neutron.agent.linux import ip_lib
from neutron.tests.functional import base
_uuid = uuidutils.generate_uuid
class NamespaceManagerTestFram... |
"""
This module defines SafeSessionMiddleware that makes use of a
SafeCookieData that cryptographically binds the user to the session id
in the cookie.
The implementation is inspired by the proposal in the following paper:
http://www.cse.msu.edu/~alexliu/publications/Cookie/cookie.pdf
Note: The proposed protocol prot... |
import binascii, ctypes, unittest
from django.contrib.gis.geos import GEOSGeometry, WKTReader, WKTWriter, WKBReader, WKBWriter, geos_version_info
class GEOSIOTest(unittest.TestCase):
def test01_wktreader(self):
# Creating a WKTReader instance
wkt_r = WKTReader()
wkt = 'POINT (5 23)'
... |
import logging
from hadoop.cloud.cluster import Cluster
from hadoop.cloud.cluster import Instance
logger = logging.getLogger(__name__)
class DummyCluster(Cluster):
@staticmethod
def get_clusters_with_role(role, state="running"):
logger.info("get_clusters_with_role(%s, %s)", role, state)
return ["dummy-c... |
import unittest
from gourmet.importers import interactive_importer
class TestConvenientImporter (unittest.TestCase):
def setUp (self):
self.ci = interactive_importer.ConvenientImporter()
def testImport (self):
self.ci.start_rec()
self.ci.add_attribute('title','Test')
self.ci... |
import urllib, httplib
import datetime
import sickbeard
from lib import MultipartPostHandler
import urllib2, cookielib
try:
import json
except ImportError:
from lib import simplejson as json
from sickbeard.common import USER_AGENT
from sickbeard import logger
from sickbeard.exceptions import ex... |
"""Running tests"""
import sys
import time
import warnings
from . import result
from .signals import registerResult
__unittest = True
class _WritelnDecorator(object):
"""Used to decorate file-like objects with a handy 'writeln' method"""
def __init__(self,stream):
self.stream = stream
def __ge... |
"""Fixer for print.
Change:
'print' into 'print()'
'print ...' into 'print(...)'
'print ... ,' into 'print(..., end=" ")'
'print >>x, ...' into 'print(..., file=x)'
No changes are applied if print_function is imported from __future__
"""
# Local imports
from .. import patcomp
from .... |
# encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python2.7/dist-packages/PyQt4/QtGui.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
class QVector4D(): # skipped bases: <type 'sip.simplewrapper'>
"""
QVector4D()
QVector4D(float, float, float, float)
QVector4D(QP... |
import cgt
import cgt.nn as nn
from cgt.tests import across_configs
import numpy as np
# Torch values obtained via this script: https://gist.github.com/ebenolson/931e879ed38f257253d2
torch_values = {'sgd': [0.81707280688755, 0.6648326359915, 0.5386151140949],
'momentum': [0.817072808743, 0.66483265161... |
from openerp.osv import osv, fields
import base64
from datetime import date, datetime
from calendar import monthrange
class reporte_mensual_wizard(osv.TransientModel):
_name = 'cfd_mx.reporte.mensual.wizard'
def _invoice_to_txt(self, invoice):
campos = [
invoice.partner_id.vat or... |
# encoding=utf-8
from Products.CMFPlone.utils import safe_unicode
from bika.lims.controlpanel.bika_analysisservices import AnalysisServicesView
from bika.lims import bikaMessageFactory as _
from bika.lims.utils import t
from plone.app.content.browser.interfaces import IFolderContentsView
from zope.interface import imp... |
import os
import logging
import numpy as np
_logger = logging.getLogger(__name__)
no_netcdf = False
try:
from netCDF4 import Dataset
which_netcdf = 'netCDF4'
except BaseException:
try:
from netCDF3 import Dataset
which_netcdf = 'netCDF3'
except BaseException:
try:
... |
import random
import math
import json
import numpy as np
from normalization import Normalizer
from cluster import Cluster
class KMeanClusterer():
def __init__(self, observations, classes, k, n):
self.FIELDSNOTUSE = 2
self.clusterNumber = k
self.clusters = []
self.observations = obs... |
# -*- coding: utf-8 -*-
import webapp2
from google.appengine.datastore.datastore_query import Cursor
from google.appengine.ext import ndb
from collections import OrderedDict, Counter
from wtforms import fields
from bp_includes import forms
from bp_includes.lib.basehandler import BaseHandler
class AdminUserGeoChartHan... |
import unittest
import paddle.fluid.framework as framework
import paddle.fluid.optimizer as optimizer
import paddle.fluid.regularizer as regularizer
from paddle.fluid.backward import append_backward
class TestL2DecayRegularizer(unittest.TestCase):
def test_l2decay_regularizer(self):
program = framework.P... |
import math
from necrobot.race import racedb
from necrobot.util import console, racetime
from necrobot.util.necrodancer.character import NDChar
from necrobot.util.singleton import Singleton
class CharacterStats(object):
def __init__(self, ndchar):
self._ndchar = ndchar
self.number_of_races = 0
... |
'''Save a set of numpy arrays to a python module file that can be imported
Author : Josef Perktold
'''
from __future__ import print_function
from statsmodels.compat.python import iterkeys
import numpy as np
class HoldIt(object):
'''Class to write numpy arrays into a python module
Calling save on the instance... |
"""IPv6 helper functions."""
import re
import dns.exception
import dns.ipv4
_leading_zero = re.compile(r'0+([0-9a-f]+)')
def inet_ntoa(address):
"""Convert a network format IPv6 address into text.
@param address: the binary address
@type address: string
@rtype: string
@raises ValueError: the ad... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('dingos', '0005_AddTaggingHistory'),
('mantis_actionables', '0011_singletonobservable_actionable_tags_cache'),
]
... |
from django.http import HttpResponse
from django.template import Template, Context
from django.template.response import TemplateResponse
from django.test import TestCase, RequestFactory
from django.utils.decorators import decorator_from_middleware
class ProcessViewMiddleware(object):
def process_view(self, reques... |
from django import forms
from django.contrib.formtools.wizard import FormWizard
from django.http import HttpResponse
class Page1(forms.Form):
name = forms.CharField(max_length=100)
thirsty = forms.NullBooleanField()
class Page2(forms.Form):
address1 = forms.CharField(max_length=100)
address2 = forms.C... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: aci_intf_policy_lldp
short_description: Manage LLDP interfac... |
from unittest import TestCase
import simplejson.encoder
CASES = [
(u'/\\"\ucafe\ubabe\uab98\ufcde\ubcda\uef4a\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?', '"/\\\\\\"\\ucafe\\ubabe\\uab98\\ufcde\\ubcda\\uef4a\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?"'),
(u'\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0... |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class R(models.Model):
is_default = models.BooleanField(default=False)
def __str__(self):
return "%s" % self.pk
get_default_r = lambda: R.... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
Created on Jun 04, 2017
@author ujnzxw <<EMAIL>>
'''
import urllib,re,sys,os,random,json
from config import momentumdash_output_file
from utils import set_background, get_desktop_environment
class MomentumdashManager():
'''
momentumdash.com backgro... |
import os
import fnmatch
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def matches_patterns(path, patterns=None):
"""
Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``).
"""
if patte... |
import hr_payroll_account
import wizard
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
#
# Copyright 2007-2016 The Python-Twitter Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of th... |
#!/usr/bin/env python
'''Test that screens can be selected for fullscreen.
Expected behaviour:
One window will be created fullscreen on the primary screen. When you
close this window, another will open on the next screen, and so
on until all screens have been tested.
Each screen will be filled ... |
#!/usr/bin/python
# interpolate scalar gradient onto nedelec space
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
from dolfin import *
import mshr
Print = PETSc.Sys.Print
# from MatrixOperations import *
import numpy as np
import PETScIO as IO
import common
import scipy
import scipy.i... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import base64
import mimetypes
import os
import sendgrid
from sendgrid.helpers.mail import Attachment, Content, Email, Mail, \
Personalization, CustomArg, Category
... |
"""
Test for export_convert_format.
"""
from unittest import TestCase
from django.core.management import call_command, CommandError
from django.conf import settings
from tempfile import mkdtemp
import shutil
from path import Path as path
from contentstore.management.commands.export_convert_format import Command, extrac... |
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr',
'name': 'LevelMgr',
'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_12/models/bossbotHQ/BossbotGreenRoom_A',
'wantDoors': 1},
1... |
from gnuradio import gru
import digital_swig
import struct
def gen_and_append_crc32(s):
crc = digital_swig.crc32(s)
return s + struct.pack(">I", gru.hexint(crc) & 0xFFFFFFFF)
def check_crc32(s):
if len(s) < 4:
return (False, '')
msg = s[:-4]
#print "msg = '%s'" % (msg,)
actual = digita... |
"""
Script for exporting courseware from Mongo to a tar.gz file
"""
import os
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.xml_exporter import export_to_xml
from xmodule.modulestore.django import modulestore
from xmodule.contentstore.django import contentstore
from xmodule... |
"""Differ module contains functions for comparing images and creating diff images
"""
import numpy as np
from PIL import Image
from ssim import compute_ssim
from .utils import extract_colors
def euclidean_distance(image1, image2):
"""Calculate `euclidean distance <https://en.wikipedia.org/wiki/Euclidean_distance... |
"""Support for plugins."""
import os.path
import sys
from coverage.misc import CoverageException
from coverage.plugin import CoveragePlugin, FileTracer, FileReporter
class Plugins(object):
"""The currently loaded collection of coverage.py plugins."""
def __init__(self):
self.order = []
self... |
#!/usr/bin/env python
# run a ROS simulator as a child process
import sys, os, pexpect, socket
import math, time, select, struct, signal, errno
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'pysim'))
import util, atexit
from pymavlink import fgFDM
class control_state(object):
... |
# coding=utf-8
# "da" means Data Access, this file contains various quick (or dirty) methods for accessing data.
import hashlib
import logging
import zlib
import pickle
from google.appengine.ext import db
from google.appengine.api import memcache
from v2ex.babel import Member
from v2ex.babel import Counter
from v2ex... |
#! /usr/bin/python2
import subprocess
import sys
import os
import time
from subprocess import PIPE
import socket
default_params = ''
output_file_prefix = 'output'
if len(sys.argv) > 1:
output_file_prefix = sys.argv[1]
#
# http://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python
#
class Logg... |
import numpy as np
from scipy import sparse
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.linear_model.randomized_l1 import (lasso_stability_path,
Randomiz... |
#coding=UTF-8
from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext
from pyspark.sql.types import *
from datetime import date, datetime, timedelta
import sys, re, os
st = datetime.now()
conf = SparkConf().setAppName('PROC_O_CEN_CBOD_CICIFADR').setMaster(sys.argv[2])
sc = SparkContext(conf = conf)
s... |
import events
def eventize(line):
tokenized = tokenize(line)
event_type = events.BaseEvent
if tokenized['command'].decode().isnumeric():
event_type = events.NumericReply
elif tokenized['command'] == 'PING':
event_type = events.Ping
elif tokenized['command'] == 'PRIVMSG':
pr... |
import array
from ctypes import byref, create_string_buffer
from .pm_ctypes import (
libpm, libpt,
pmHostError, PmEvent,
PmTimeProcPtr, NullTimeProcPtr,
PortMidiStreamPtr,
)
from . import MidiException
__all__ = [
'TRUE',
'FALSE',
'Initialize',
'Terminate',
'CountDevices',
'G... |
import unittest
from hustle import select, Table, h_sum, h_count
from setup import IMPS, PIXELS
from hustle.core.settings import Settings, overrides
class TestJoin(unittest.TestCase):
def setUp(self):
overrides['server'] = 'disco://localhost'
overrides['dump'] = False
overrides['nest'] = F... |
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from random import randint
class PongBall(Widget):
velocity_x = NumericProperty(0)
velocity_y = Numeri... |
from flask_dance.consumer import OAuth2ConsumerBlueprint
from functools import partial
from flask.globals import LocalProxy, _lookup_app_object
from flask import _app_ctx_stack as stack
__maintainer__ = "David Baumgold <<EMAIL>>"
def make_dropbox_blueprint(
app_key=None,
app_secret=None,
*,
scope=N... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLocalDefaultSettings.
.. 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 versio... |
from univention.umc import main
if __name__ == '__main__':
import sys
if sys.argv[0].endswith('__main__.py'):
sys.argv[0] = 'umc-server'
main() |
# -*- coding: utf-8 -*-
"""
jinja2.utils
~~~~~~~~~~~~
Utility functions.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import errno
from collections import deque
from threading import Lock
from jinja2._compat import text_type, string_types, impl... |
import time
from openerp.osv import osv
from openerp.report import report_sxw
class crossovered_analytic(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(crossovered_analytic, self).__init__(cr, uid, name, context = context)
self.localcontext.update( {
'time': t... |
from test.base import BaseTest
import unittest, socket, requests, json
from time import sleep
from unittest import TestCase
# supress ssl warnings.
requests.packages.urllib3.disable_warnings(
requests
.packages
.urllib3
.exceptions
.InsecureRequestWarning)
class DlistsTestCase(TestCase, BaseTest)... |
from .. import fixtures, config
from ..assertions import eq_
from sqlalchemy import Integer, String
from ..schema import Table, Column
class SimpleUpdateDeleteTest(fixtures.TablesTest):
run_deletes = 'each'
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table('plain_pk', m... |
import re
import cx_Oracle
from django.db.backends import BaseDatabaseIntrospection, FieldInfo, TableInfo
from django.utils.encoding import force_text
foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
class DatabaseIntrospection(BaseDatabaseIntrospect... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.