content stringlengths 4 20k |
|---|
"""Parse (absolute and relative) URLs.
See RFC 1808: "Relative Uniform Resource Locators", by R. Fielding,
UC Irvine, June 1995.
"""
__all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag",
"urlsplit", "urlunsplit"]
# A classification of schemes ('' means apply by default)
uses_relative = ['ftp', 'htt... |
"""
Signal Processing Tools
=======================
Convolution:
convolve:
N-dimensional convolution.
correlate:
N-dimensional correlation.
fftconvolve:
N-dimensional convolution using the FFT.
convolve2d:
2-dimensional convolution (more options).
correlate2d:
... |
# coding: utf-8
from django.test import TestCase
from datetime import datetime, date
from datetime import timedelta
from regressiontests.views.models import Article, Author, DateArticle
class ObjectDetailTest(TestCase):
fixtures = ['testdata.json']
def setUp(self):
# Correct the date for the current ar... |
__all__ = [
'get_txt'
]
def get_txt_dnspython(name):
"""Return a TXT record associated with a DNS name."""
try:
a = dns.resolver.query(name, dns.rdatatype.TXT,raise_on_no_answer=False)
for r in a.response.answer:
if r.rdtype == dns.rdatatype.TXT:
return b"".join(r.i... |
__author__ = "Antonio Hernández <<EMAIL>>"
__copyright__ = "Copyright (C) 2011, Junta de Andalucía <<EMAIL>>"
__license__ = "GPL-2"
import os
import shlex
import subprocess
import crypt
import gettext
from gettext import gettext as _
gettext.textdomain('firstboot')
def read_users(min_uid=1000):
users = []
... |
from hotwire.sysdep import is_jython
if is_jython():
from .mainloop_null import *
else:
from .mainloop_g import *
def call_idle_once(func, *args, **kwargs):
def func_false():
func(*args, **kwargs)
return False
return call_idle(func_false)
def call_idle(func, *args, **kwargs):
retu... |
import numpy as np
from astropy.io import fits
from matplotlib import pyplot as plt
fima = fits.open('/scratch/prabhu/HollyWaller/IMaX_pole_data_scripts/primary_scripts/saves_Oct11/post_demod_tr2_output_21.fits')[0].data
st = int(input("Choose stokes: "))
stokes = {0:'I',1:'Q',2:'U',3:'V'}
dim = fima.shape
pri... |
from django.contrib.gis.geos import GEOSGeometry, LinearRing, Polygon, Point
from django.contrib.gis.maps.google.gmap import GoogleMapException
from django.utils.six.moves import xrange
from math import pi, sin, log, exp, atan
# Constants used for degree to radian conversion, and vice-versa.
DTOR = pi / 180.
RTOD = 18... |
m5.util.addToPath('../configs/common')
from cpu2000 import perlbmk_makerand
workload = perlbmk_makerand(isa, opsys, 'lgred')
root.system.cpu[0].workload = workload.makeLiveProcess() |
"""Base class for defining interactions.
A note on terminology: state_customization_args refers to the values of
customization args that are provided by an exploration editor. They are
formatted as
{ca_name: {value: ca_value}}
On the other hand, interaction.customization_args refers to a combination of
the inter... |
from PyQt4 import QtCore, QtWebKit
class SVGWebView(QtWebKit.QWebView):
def __init__(self, parent=None, url=None):
super(SVGWebView, self).__init__(parent)
self.urlChanged.connect(self.updateSource)
if url:
#self.setUrl(url)
self.load(url)
def updateSour... |
{ 'sequence': 500,
'name': 'Sale Order UoS Data Entry, Show Packing Info',
'version': '0.7',
'category': 'Warehouse Management',
'description': """
This modul allows to enter Uom or Uos quantities in sale order
and shows packing Info in various views.
""",
'author': 'ChriCar Beteiligungs- und Beratungs- GmbH',
'depend... |
from pybench import Test
class CompareIntegers(Test):
version = 2.0
operations = 30 * 5
rounds = 120000
def test(self):
for i in range(self.rounds):
2 < 3
2 > 3
2 == 3
2 > 3
2 < 3
2 < 3
2 > 3
2 ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from ast import literal_eval
HAS_PYTHON26 = True
except ImportError:
HAS_P... |
#!/usr/bin/python3
"""
extract.geojson_reader
~~~~~~~~~~~~~~~~~~~~~~
This module handles flight data represented as a list of positions in a format
compliant with the Geo JSON specification.
- longitude
- latitude
- altitude as well as a time in
seconds.
"""
import json
import logging
class GeoJsonReader:
de... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
r_li_pielou.py
--------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
******************************... |
import re
import os.path
from io import open
from setuptools import find_packages, setup
try:
from azure_bdist_wheel import cmdclass
except ImportError:
from distutils import log as logger
logger.warn("Wheel is not available, disabling bdist_wheel hook")
cmdclass = {}
# Change the PACKAGE_NAME only to ... |
"""The Exponential distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.distributions.python.ops import gamma
from tensorflow.python.framework import dtypes
from tensorflow.python.framework impor... |
import socket
import sys
from six import binary_type, text_type
def isomorphic_decode(s):
"""Decodes a binary string into a text string using iso-8859-1.
Returns `unicode` in Python 2 and `str` in Python 3. The function is a
no-op if the argument already has a text type. iso-8859-1 is chosen because
... |
from units.compat import unittest
from oneview_module_loader import FcoeNetworkModule
from hpe_test_utils import OneViewBaseTestCase
FAKE_MSG_ERROR = 'Fake message error'
DEFAULT_FCOE_NETWORK_TEMPLATE = dict(
name='New FCoE Network 2',
vlanId="201",
connectionTemplateUri=None
)
PARAMS_FOR_PRESENT = dict(... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class imageGreyDilate(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_mana... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_feature_facts
short_description: Gathers facts about an ESXi host's featur... |
from Orange import data
try:
import unittest2 as unittest
except:
import unittest
class TestPickClass(unittest.TestCase):
def __init__(self, testCaseName):
unittest.TestCase.__init__(self, testCaseName)
self.orig = data.Table('multitarget-synthetic')
def test_pick_first(self):
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import it... |
"""Helper for choosing which op to run next in a distributed setting."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,line-too-long,wildcard-import
from tensorflow.contrib.kfac.python.ops.op_queue import *
from tensorflow.... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that we have proper strings like Copyright notices on all the
right files in our distributions.
Note that this is a source file and packaging test, not a functional test,
so the name of this script doesn't end in *Tests.py.
"""
import fnmatch
i... |
from __future__ import unicode_literals
from flask import request, session, redirect
from werkzeug.exceptions import Forbidden
from MaKaC.webinterface.rh.conferenceBase import RHConferenceBase
from MaKaC.webinterface.rh.conferenceDisplay import RHConferenceBaseDisplay
from indico.modules.attachments.controllers.even... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import urllib
# ===========================================
# Module execution.
#
def main():
module = AnsibleModule(
argument_spec=dict(
token=dict(required=True... |
class Solution:
# @param s, a string
# @return an integer
def minCut(self, s):
# write your code here
n = len(s)
if n < 2:
return 0
isPal = [[False for j in range(n)] for i in range(n)]
for d in range(n):
isPal[d][d] = True
for l... |
import csv
import datetime
import json
import os
import shlex
import subprocess
import sys
from optparse import OptionParser
"""Start a client to fetch web pages either using wget or using quic_client.
If --use_wget is set, it uses wget.
Usage: This invocation
run_client.py --quic_binary_dir=../../../../out/Debug \
... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Canal para filmsenzalimiti
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from c... |
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
UserModel = get_user_model()
class ModelBackend:
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, request, username=None, password=None, **kwargs):
if username is No... |
#!/bin/env python3
import sys
import os
import glob
import numpy as np
import pandas as pd
from collections import OrderedDict
RUNSET = sys.argv[1].rstrip('/')
BASEDIR = './'
OUTDIR = 'out'
INTERPOLATION_METHOD = 'nearest'
STEP_FILENAME_GLOB = 'step_*'
MEDFOESP_DETAIL_FILE_GLOB = 'MED-FOESp_*_detail.txt'
DATA_O... |
# coding:utf8
from __future__ import print_function
class Property(object):
"
Emulate PyProperty_Type() in Objects/descrobject.c
该类时Property的python实现方式
参考:https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work
"
def __init__(self, fget=None, fset=None, fd... |
"""This file contains code for use with "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2014 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function, division
import unittest
import random
from collections import Counter
import ... |
from os.path import join, dirname
import numpy as np
from .. import const, os as xm_os
from .general import _savefig
from ..imprt import preset_import
from ..log import get_logger
logger = get_logger()
def scatter_on_img(pts, im, size=2, bgr=(0, 0, 255), outpath=None):
r"""Plots scatter on top of an image or ju... |
from TProtocol import TType, TProtocolBase, TProtocolException
import base64
import json
import math
__all__ = ['TJSONProtocol',
'TJSONProtocolFactory',
'TSimpleJSONProtocol',
'TSimpleJSONProtocolFactory']
VERSION = 1
COMMA = ','
COLON = ':'
LBRACE = '{'
RBRACE = '}'
LBRACKET = '['
R... |
from __future__ import unicode_literals
import datetime
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase, override_settings
from django.test.client import RequestFactory
from .mo... |
data = (
'Song ', # 0x00
'Wei ', # 0x01
'Hong ', # 0x02
'Wa ', # 0x03
'Lou ', # 0x04
'Ya ', # 0x05
'Rao ', # 0x06
'Jiao ', # 0x07
'Luan ', # 0x08
'Ping ', # 0x09
'Xian ', # 0x0a
'Shao ', # 0x0b
'Li ', # 0x0c
'Cheng ', # 0x0d
'Xiao ', # 0x0e
'Mang ', # 0x0f
'Fu ', # 0x1... |
from msrest.serialization import Model
class SloUsageMetric(Model):
"""Represents a Slo Usage Metric.
:param service_level_objective: The serviceLevelObjective for SLO usage
metric. Possible values include: 'Basic', 'S0', 'S1', 'S2', 'S3', 'P1',
'P2', 'P3', 'P4', 'P6', 'P11', 'P15', 'System', 'Elas... |
from spack import *
class RRgl(RPackage):
"""Provides medium to high level functions for 3D interactive graphics,
including functions modelled on base graphics (plot3d(), etc.) as well as
functions for constructing representations of geometric objects (cube3d(),
etc.). Output may be on screen using Op... |
""" Schema is an easy way to map couchdb object in pythoin object. It's
similar to ORMs but with all couchdb glory.
An application describes the kinds of data it uses with a Document object. A
document is a Python class that inherits from the `couchdbkit.schema.Document`
class. The document class defines a new kind of... |
"""Tests for SparseReorder."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tensorflow.python.ops import sparse_ops
from tens... |
# -*- coding: utf-8 -*-
"""
pygments.formatters.other
~~~~~~~~~~~~~~~~~~~~~~~~~
Other formatters: NullFormatter, RawTokenFormatter.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.formatter import Formatter
from pygments... |
import webob
from nova.api.openstack.compute.contrib import cloudpipe_update
from nova import db
from nova import test
from nova.tests.api.openstack import fakes
from nova.tests import fake_network
fake_networks = [fake_network.fake_network(1),
fake_network.fake_network(2)]
def fake_project_get_ne... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import assert_equal
from scipy.sparse.csgraph import reverse_cuthill_mckee,\
maximum_bipartite_matching
from scipy.sparse import diags, csr_matrix, coo_matrix
def test_graph_reverse_cuthill_mckee():
A = ... |
from django.conf.urls.defaults import *
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext, Template
from django.template.response... |
from libvmcli import *
from libguest import Guest
class Host:
def __init__(self, name, global_cluster_options, cluster_options):
self.guests = {}
self.name = name
self.global_cluster_options = global_cluster_options
self.cluster_options = cluster_options
d = os.path.join('/... |
from django.shortcuts import render
from django.db.models import Q, Count, Sum, Min, Max
from django.core.urlresolvers import reverse
from maluroam.eduroam_snort.models import Event, Blacklist, Rule, Script
from maluroam.eduroam_snort.aggregates import Concatenate, parse_concat
from maluroam.eduroam_snort.utils import... |
import copy
import datetime
import pickle
import unittest
from django.test import override_settings
from django.utils import timezone
try:
import pytz
except ImportError:
pytz = None
requires_pytz = unittest.skipIf(pytz is None, "this test requires pytz")
if pytz is not None:
CET = pytz.timezone("Europe... |
# -*- 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 field 'Poll.pub_date'
db.add_column('polls_poll', 'pub_date',
self.gf('django... |
import os
import datetime
import time
import logging
import datadog
import sys
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("dd").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
"""
Originally written by 'Jharrod La... |
import sys
from nova.virt.hyperv import rdpconsoleutils
if sys.platform == 'win32':
import wmi
class RDPConsoleUtilsV2(rdpconsoleutils.RDPConsoleUtils):
def __init__(self):
if sys.platform == 'win32':
self._conn = wmi.WMI(moniker='//./root/virtualization/v2')
def get_rdp_console_por... |
"""Logging tensorflow::tfprof::OpLog.
OpLog is used to add extra model information for offline analysis by tfprof.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import six
from tensorflow.python.framework import ops
from tensorfl... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para video4you
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core imp... |
from gnuradio import gr, blks2
import sys, time
try:
import scipy
from scipy import fftpack
except ImportError:
print "Error: Program requires scipy (see: www.scipy.org)."
sys.exit(1)
try:
import pylab
from pylab import mlab
except ImportError:
print "Error: Program requires matplotlib (se... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: win_template
version_added: "1.9.2"
short_description: Templates a file out to a remote server.
description:
- Templates are processed by ... |
# -*- coding: utf-8 -*-
"""As a programming ecosystem grows, so do the chances of runtime
variability.
Python boasts one of the widest deployments for a high-level
programming environment, making it a viable target for all manner of
application. But with breadth comes variance, so it's important to
know what you're wo... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.network.avi.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ... |
import dataset;
import numpy as np
import scipy.io;
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import networkx as nx
import scipy.stats as ss
#z = scipy.io.loadmat('tmp.dat');
#ccfull = z['ccfull']
#sx,sy = ccfull.shape
##x = np.arange(sx)
##delta = 0.025
##X, Y = np.mes... |
from __future__ import unicode_literals, division, absolute_import
import logging
import os
from flexget import plugin
from flexget.event import event
from flexget.utils.bittorrent import Torrent, is_torrent_file
log = logging.getLogger('modif_torrent')
class TorrentFilename(object):
"""
Makes sure that... |
import os
import sys
from distutils.core import setup
import py2exe
import glob
from BTL.language import languages
if os.name != 'nt':
print "This script is only for use on Win32. Use setup.py to install on a Unix OS."
sys.exit()
from BitTorrent.platform import get_shell_dir, shellcon
excludes = ["curses",
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
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.parsing.splitt... |
"""AutomaticControlDependencies and related functionality."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes as dtypes_module
from tensorflow.python.framework import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Deployment of PySpeak """
# system
import os, re
# fabric
from fabric.api import cd, env, execute, local, run, sudo, prefix
# PySpeak
from pyspeak import __version__
def fast_commit(capture=True):
""" Fast commit with generic message. """
env.warn_only = True... |
"""helper functions for image handling
"""
__author__ = '<EMAIL> (Mika Raento)'
def _debug(s):
#print s
pass
def _read_2byte(img_data, pos):
return (ord(img_data[pos]) << 8) + ord(img_data[pos + 1])
def _size_from_jpeg(img_data):
"""A very crude JPEG reader so that we can get the image size"""
# JPEG form... |
"""Project file system commands.
This modules implements file system operations used by rope. Different
version control systems can be supported by implementing the interface
provided by `FileSystemCommands` class. See `SubversionCommands` and
`MercurialCommands` for example.
"""
import os, re
import shutil
import ... |
import uno
import string
import unohelper
import xmlrpclib
from com.sun.star.task import XJobExecutor
if __name__<>"package":
from lib.gui import *
from lib.functions import *
from lib.error import ErrorDialog
from LoginTest import *
from lib.logreport import *
from lib.rpc import *
databas... |
import json
class Tag(object):
@classmethod
def from_dict(cls, tag_dict):
tag = Tag(tag_dict['name'], tag_dict['default'])
tag.mails = set(tag_dict['mails'])
return tag
@classmethod
def from_json_string(cls, json_string):
tag_dict = json.loads(json_string)
tag... |
"""The tests for the mFi sensor platform."""
import unittest
import unittest.mock as mock
from mficlient.client import FailedToLogin
import requests
import homeassistant.components.mfi.sensor as mfi
import homeassistant.components.sensor as sensor
from homeassistant.const import TEMP_CELSIUS
from homeassistant.setup ... |
from optparse import OptionParser
import os
import os.path
import sys
import shutil
def nsinstall(argv):
usage = "usage: %prog [options] arg1 [arg2 ...] target-directory"
p = OptionParser(usage=usage)
p.add_option('-D', action="store_true",
help="Create a single directory only")
p.add_option('-... |
# -*- coding: utf-8 -*-
"""
This config file runs the simplest dev environment using sqlite, and db-based
sessions. Assumes structure:
/envroot/
/db # This is where it'll write the database file
/edx-platform # The location of this repo
/log # Where we're going to write log files
"""
# We ... |
from collections import deque
from enum import IntEnum
import networkx as nx
class GraphType(IntEnum):
DIRECTED = 0
DIRECTED_MULTI = 1
class BoardGraph:
"""
Board graph implementation using NetworkX.
NetworkX is pure Python graph library, doesn't depend on external binaries and is
easily i... |
from config_common.rhn_log import log_debug
import handler_base
class Handler(handler_base.HandlerBase):
def run(self):
log_debug(2)
r = self.repository
config_channels = r.load_config_channels()
if not config_channels:
print "(no config channels associated with this s... |
"""Handles all VCS (version control) support"""
from __future__ import absolute_import
import logging
import os
import shutil
from pip._vendor.six.moves.urllib import parse as urllib_parse
from pip.exceptions import BadCommand
from pip.utils import (display_path, backup_dir, find_command,
rmtr... |
import numpy
from constellation_map_generator import *
'''
Note on the naming scheme. Each constellation is named using a prefix
for the type of constellation, the order of the constellation, and a
distinguishing feature, which comes in three modes:
- No extra feature: the basic Gray-coded constellation map; others
... |
"""Classify changes in Ansible code."""
from __future__ import absolute_import, print_function
import os
import time
from lib.target import (
walk_module_targets,
walk_integration_targets,
walk_units_targets,
walk_compile_targets,
walk_sanity_targets,
load_integration_prefixes,
)
from lib.ut... |
"""The Logistic distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
from tensorflow.contrib.distributions.python.ops import distribution
from tensorflow.contrib.framework.python.framework import tensor_util... |
#!/usr/bin/env pyhton
from csv import DictWriter
from gmusicapi import Mobileclient
from operator import itemgetter
def login():
logged_in = api.login('<EMAIL>', 'password')
# IMPORTANT: If you use secondary authentication for gogle music
# you need to generate an app specific password!
return... |
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from openstack_dashboard import api
def availability_zone_list(request):
"""Utility method to retrieve a list of availability zones."""
try:
if api.cinder.extension_supported(request, 'AvailabilityZones'):
... |
from __future__ import absolute_import, division, print_function
import inspect
class TypeVisitor(object):
def visit(self, visitable, *args, **kwargs):
for type in inspect.getmro(visitable):
try:
visit_func = getattr(self, "visit_%s" % type.__name__)
except Attribu... |
from gramps.gen.ggettext import gettext as _
#-------------------------------------------------------------------------
#
# gtk
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
#-------------------------------------------------------------------------
#
# GRAM... |
from django.conf import settings
from django.contrib.gis.gdal import OGRException
from django.contrib.gis.geos import GEOSGeometry, GEOSException
from django.forms.widgets import Textarea
from django.template import loader, Context
from django.utils import translation
# Creating a template context that contains Django... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from collections import namedtuple
from operator import attrgetter
from ..utils import ItemsCount
from .._compat import to_unicode
from ..nlp.stemmers import null_stemmer
SentenceInfo = ... |
from datetime import date
from . import testutils
from .testutils import unittest
import psycopg2
import psycopg2.extras
import psycopg2.extensions as ext
class TestPaginate(unittest.TestCase):
def test_paginate(self):
def pag(seq):
return psycopg2.extras._paginate(seq, 100)
self.as... |
from __future__ import division, print_function
import os, json
from glob import glob
import numpy as np
from scipy import misc, ndimage
from scipy.ndimage.interpolation import zoom
from keras import backend as K
from keras.layers.normalization import BatchNormalization
from keras.utils.data_utils import get_file
fro... |
import logging
import numpy as np
from pele.potentials import BasePotential
from nestedbasinsampling import (
NBS_system, vector_random_uniform_hypersphere, LOG_CONFIG)
class MyPot(BasePotential):
def __init__(self, M):
self.M = M
def getEnergy(self, coords):
return 0.5*np.dot... |
import jinja2
import webapp2
import os
import logging
#logging.info("DOES THIS WORK?!")
from models.Word import Word
from views.ViewHandler import Handler
from views.Index import IndexHandler, CSSFreeIndexHandler
from views.Direct import DirectLinkHandler, CSSFreeDirectLinkHandler
from views.WordNotFound import WordN... |
#! /usr/bin/env python
# David Cournapeau
# Last Change: Wed Nov 05 07:00 PM 2008 J
from __future__ import division, print_function, absolute_import
import os.path
import warnings
import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
TestCase, run_module_suite, assert_raise... |
"""Gneral interface for a corpus reader
"""
__all__ = ["BaseCorpusReader"]
class BaseCorpusReader(object):
"""Basic corpus interface
"""
_loaded_paras = []
_all_para_loaded = False
def raw_para(self):
"""Read a paragraph -- you need to implement this for your
corpus reader.
... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'UserProfile'
db.create_table('supersyncer_userprofile', (... |
from openerp.osv import fields, osv
class hr_timesheet_settings(osv.osv_memory):
_inherit = 'hr.config.settings'
_columns = {
'timesheet_range': fields.selection([('day','Day'),('week','Week'),('month','Month')],
'Validate timesheets every', help="Periodicity on which you validate your tim... |
import re
from tools import (
case,
)
class test(case):
def test_11(self):
# Bug: https://sourceforge.net/p/djvu/bugs/106/
# + fixed in 0.4.11 [25f63fdcee01a93df16fcd56ebd7587165f4ee52]
self.pdf2djvu('--bg-subsample=11', '--dpi=72').assert_()
r = self.djvudump()
r.asse... |
#!/usr/bin/env python
import os
import optparse
import sys
import re
from pip.exceptions import InstallationError, CommandError, PipError
from pip.log import logger
from pip.util import get_installed_distributions, get_prog
from pip.vcs import git, mercurial, subversion, bazaar # noqa
from pip.baseparser import Conf... |
from subprocess import call, check_call, Popen, PIPE
import os, tempfile, sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option("", "--good", help="known good revision (default HEAD~100)", default='HEAD~100')
parser.add_option("", "--bad", help="known bad revision (default HEAD)", default='HE... |
import io
import json
import os
import subprocess
from setuptools import Command
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.sdist import sdist as base_sdist
from wagtail import __semver__
class assets_mixin:
def compile_assets(self):
try:
subprocess.check_cal... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
# ===========================================
# MQTT module support methods.
#
HAS_PAHOMQTT = True
try:
import socket
import paho.mqtt.publish as mqtt
except ImportError:... |
from math import floor
class MinHeap(object):
def __init__(self):
self._values = [None]
def insert(self, value):
self._values.append(value)
self._heapify(len(self._values) - 1)
def pop(self):
self._swap(len(self._values) - 1, 1)
ret = self._values.pop()
#... |
from __future__ import absolute_import
from datetime import datetime, timedelta
from uuid import uuid4
import pytest
from sentry.constants import ObjectStatus
from sentry.exceptions import DeleteAborted
from sentry.models import (
ApiApplication, ApiApplicationStatus, ApiGrant, ApiToken, Commit, CommitAuthor, En... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.