content stringlengths 4 20k |
|---|
from __future__ import print_function
import sys, time, random, os, json
import six
from six.moves.urllib.parse import urlencode
from subprocess import Popen, PIPE
from twisted.web.server import Site, NOT_DONE_YET
from twisted.web.resource import Resource
from twisted.internet import reactor, defer, ssl
from scrapy imp... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
import json
from django.contrib.admin.sites import site
from django.template import Context
from django.template.base import Template
from django.utils.encoding import force_text
from cms.api import add_plugin
from cms.constants import PLUGIN_MOVE_ACTION, ... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import unittest
from textwrap import dedent
from pants.backend.jvm.register import build_file_aliases as register_jvm
from pants.backend.jvm.targets.exclude import Ex... |
from setuptools import setup, find_packages
exec(open('thunderfish/version.py').read())
long_description = """
# ThunderFish
Algorithms and programs for analysing electric field recordings of
weakly electric fish.
[Documentation](https://bendalab.github.io/thunderfish) |
[API Reference](https://bendalab.github.io/t... |
from ryu.services.protocols.bgp.info_base.vrf import VrfRtImportMap
from ryu.services.protocols.bgp.info_base.vrf4 import Vrf4NlriImportMap
from ryu.services.protocols.bgp.info_base.vrf6 import Vrf6NlriImportMap
class ImportMapManager(object):
def __init__(self):
self._import_maps_by_name = {}
def c... |
"""Pylons specific code to facilitate using AuthKit with Pylons
There is a full Pylons manual in addition to the AuthKit manual which
you should read if you plan to use AuthKit with Pylons
.. Note ::
In addition to the authorize methods described here, you can also use the
default ``authkit.authorize.middle... |
import commands
import os
def get_system_info():
cmd_get_cpu_sockect=r"lscpu|grep Socket|awk '{print $NF}'"
cmd_get_cpu_cores=r"cat /proc/cpuinfo|grep processor|wc -l"
cmd_get_mem_total=r"free -m |head -n 2|tail -n 1|awk '{print $2}'"
cmd_get_mem_used=r"free -m |tail -n 2|head -n 1|awk '{print $3}'"
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
from ... |
__author__ = 'Irwan Fathurrahman <<EMAIL>>'
__date__ = '17/05/17'
import json
from campaign_manager.insights_functions._abstract_overpass_insight_function \
import AbstractOverpassInsightFunction
class FeatureAttributeCompleteness(AbstractOverpassInsightFunction):
function_name = "Feature completeness"
ta... |
#!/usr/bin/env python3
import traceback
import cereal.messaging as messaging
from selfdrive.car.isotp_parallel_query import IsoTpParallelQuery
from selfdrive.swaglog import cloudlog
EXT_DIAG_REQUEST = b'\x10\x03'
EXT_DIAG_RESPONSE = b'\x50\x03'
COM_CONT_REQUEST = b'\x28\x83\x03'
COM_CONT_RESPONSE = b''
def disable_e... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 27 13:26:01 2014
Author: Josef Perktold
License: BSD-3
"""
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from scipy import stats
from statsmodels.regression.linear_model import OLS
from statsmodels.tools.transform_model import StandardizeTr... |
import requests
import urllib
import csv
import os
import sys
from time import time
from py_data_getter import data_getter
from py_db import db
db = db('nba_shots')
def initiate():
print "-------------------------"
print "shots_Relative_Career.py"
start_time = time()
process()
end_time = ti... |
"""FreeBSD platform implementation."""
import errno
import functools
import os
import xml.etree.ElementTree as ET
from collections import namedtuple
from . import _common
from . import _psposix
from . import _psutil_bsd as cext
from . import _psutil_posix as cext_posix
from ._common import conn_tmap, usage_percent, s... |
"""
This module is for inspecting OGR data sources and generating either
models for GeoDjango and/or mapping dictionaries for use with the
`LayerMapping` utility.
Author: Travis Pinney, Dane Springmeyer, & Justin Bronn
"""
from itertools import izip
# Requires GDAL to use.
from django.contrib.gis.gdal import DataSourc... |
# coding: utf-8
__all__ = ()
try:
# Django 1.2 doesn't have this
from django.utils import unittest
except ImportError:
pass
else:
from attest import capture_output, TestFailure, TestResult, get_reporter_by_name
from django.test.simple import DjangoTestSuiteRunner
__all__ += ("Runner", )
... |
from .bases import _StandardStemmer
from whoosh.compat import u
class ItalianStemmer(_StandardStemmer):
"""
The Italian Snowball stemmer.
:cvar __vowels: The Italian vowels.
:type __vowels: unicode
:cvar __step0_suffixes: Suffixes to be deleted in step 0 of the algorithm.
:type __step0_suff... |
import os
import re
import shutil
from oslo.config import cfg
from fuel_agent import errors
from fuel_agent.openstack.common import log as logging
from fuel_agent.utils import utils
LOG = logging.getLogger(__name__)
gu_opts = [
cfg.IntOpt(
'grub_timeout',
default=5,
help='Timeout in secs... |
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from json import dumps
import account
app = Flask(__name__)
api = Api(app)
#Parser that parses incoming messages.
userParser = reqparse.RequestParser()
userParser.add_argument('username', help='The username the user wants to register.'... |
"""
Internet Protocol version 6 (TCP/IP protocol stack)
"""
from construct import *
from ipv4 import ProtocolEnum
from binascii import unhexlify
import six
class Ipv6AddressAdapter(Adapter):
def _encode(self, obj, context):
if bytes is str:
return "".join(part.decode("hex") for part in obj.spl... |
#Python 3+ Script for importing admins.txt and admin_ranks.txt made by Jordie0608
#
#Before starting ensure you have installed the mysqlclient package https://github.com/PyMySQL/mysqlclient-python
#It can be downloaded from command line with pip:
#pip install mysqlclient
#And that you have run the most recent commands ... |
import re
import os
import sys
import glob
import tarfile
import shutil
import subprocess
import distutils.spawn
try:
import hashlib
sha_func = hashlib.sha1
except ImportError:
import sha
sha_func = sha.new
def scrub(b):
if sys.version_info >= (3,) and type(b) == bytes:
return b.decode('a... |
import numpy as np
import pandas as pd
import xarray as xr
from tikon.utils import EJE_TIEMPO, EJE_PARC
class Obs(object):
def __init__(símismo, datos):
símismo.datos = datos
def fechas(símismo):
tiempos = símismo.datos[EJE_TIEMPO].values
if np.issubdtype(tiempos.dtype, np.datetime64... |
PANEL = 'overview'
# The slug of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'project'
# The slug of the panel group the PANEL is associated with.
PANEL_GROUP = 'compute'
# If set, it will update the default panel of the PANEL_DASHBOARD.
DEFAULT_PANEL = 'overview'
# Python panel class of the ... |
import types
import warnings
import Foundation
import AppKit
import objc
import _IOBluetooth
import _LightAquaBlue
import _lightbluecommon
import _macutil
import _bluetoothsockets
# public attributes
__all__ = ("finddevices", "findservices", "finddevicename",
"selectdevice", "selectservice",
... |
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: win_partition
version_added: '2.8'
short_description: Creates, changes and removes partitions on Windows Server
description:
- The M(win_partition) module can create, modi... |
from waflib.Configure import conf
@conf
def get_config_header(self, defines=True, headers=False, define_prefix=''):
"""
Only difference is it outputs `#define VAR 0` or `#define VAR value`
instead of `#undef VAR` or `#define VAR val`.
"""
from waflib.Tools.c_config import DEFKEYS, INCKEYS
lst =... |
"""Hand-crafted tests against specific NOVAS behaviors.
The tests in the neighboring `tests_against_novas.py` are automatically
generated and in general demonstrate close agreement with NOVAS. But
the hand-crafted tests here are aimed at specific edge conditions that
we want to make sure we get correct.
"""
from num... |
import os
import tempfile
import unittest
from testtools import TestCase
from testtools.compat import (
_b,
_u,
StringIO,
)
from testtools.content import (
attach_file,
Content,
content_from_file,
content_from_stream,
TracebackContent,
text_content,
)
from testtools.content_... |
from seamicroclient.tests import utils
from seamicroclient.tests.v2 import fakes
from seamicroclient.v2 import smcards
cs = fakes.FakeClient()
class SMCardstest(utils.TestCase):
def test_list_smcards(self):
pl = cs.smcards.list()
cs.assert_called('GET', '/chassis/smcard')
[self.assertTr... |
import uuid
from eventlet import greenthread
from lxml import etree
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import importutils
from nova.cloudpipe import pipelib
import nova.conf
from nova.i18n import _LI
from nova.i18n import _LW
import nova.virt.firewall as base_firewall
... |
# -*- coding: utf-8 -*-
"""
hyper/common/headers
~~~~~~~~~~~~~~~~~~~~~
Contains hyper's structures for storing and working with HTTP headers.
"""
import collections
from hyper.common.util import to_bytestring, to_bytestring_tuple
class HTTPHeaderMap(collections.MutableMapping):
"""
A structure that contains... |
# encoding: 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 'Document.rendered_html'
db.add_column('wiki_document', 'rendered_html', self.gf('django.db... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.actionscript
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for ActionScript and MXML.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, bygroups, using,... |
# -*- coding: utf-8 -*-
'''
Read meta information from pdb files.
'''
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import re
from calibre.ebooks.metadata import MetaInformation
from calibre.ebooks.pdb.header import PdbHeaderReader
from calibre.ebooks... |
# coding=utf-8
import logging
import random
import string
import sys
import unittest
from time import time, sleep
import apiritif
import os
import re
from appium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.... |
emc_vnx_argument_spec = {
'sp_address': dict(type='str', required=True),
'sp_user': dict(type='str', required=False, default='sysadmin'),
'sp_password': dict(type='str', required=False, default='sysadmin',
no_log=True),
} |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: purefa_hg
version_added: '2.4'
short_description: Manage hos... |
"""
ID3 metadata parser, supported versions: 1.O, 2.2, 2.3 and 2.4
Informations: http://www.id3.org/
Author: Victor Stinner
"""
from hachoir_core.field import (FieldSet, MatchError, ParserError,
Enum, UInt8, UInt24, UInt32,
CString, String, RawBytes,
Bit, Bits, NullBytes, NullBits)
from hachoir_core.text... |
"""
High-level abstraction of an EC2 order for servers
"""
import boto
import boto.ec2
from boto.mashups.server import Server, ServerSet
from boto.mashups.iobject import IObject
from boto.pyami.config import Config
from boto.sdb.persist import get_domain, set_domain
import time
from boto.compat import StringIO
Instan... |
from __future__ import division
import copy
from whoosh import matching
from whoosh.analysis import Token
from whoosh.compat import u
from whoosh.query import qcore, terms, compound
class Sequence(compound.CompoundQuery):
"""Matches documents containing a list of sub-queries in adjacent
positions.
This ... |
import math
import os
import sys
#sys.path.insert(0, 'moman/finenight/python')
sys.path.insert(0, '../../../../../../../../build/core/moman/finenight/python')
try:
from possibleStates import genTransitions
except ImportError:
from finenight.possibleStates import genTransitions
MODE = 'array'
PACKED = True
WORD = 6... |
data = (
'g', # 0x00
'gg', # 0x01
'n', # 0x02
'd', # 0x03
'dd', # 0x04
'r', # 0x05
'm', # 0x06
'b', # 0x07
'bb', # 0x08
's', # 0x09
'ss', # 0x0a
'', # 0x0b
'j', # 0x0c
'jj', # 0x0d
'c', # 0x0e
'k', # 0x0f
't', # 0x10
'p', # 0x11
'h', # 0x12
'ng', # 0x13
'nn', ... |
import deploy
import sys
deploy.program = "rbthemeeditor"
deploy.project = "utils/themeeditor/themeeditor.pro"
deploy.svnserver = "svn://svn.rockbox.org/rockbox/"
deploy.svnpaths = \
[ "utils/themeeditor/",
"lib/skin_parser/",
"docs/COPYING" ]
deploy.useupx = False
deploy.bundlecop... |
# import ocl
import openvoronoi as ovd
import ovdvtk
# import time
import vtk
# import datetime
import math
import random
"""
This script does not use OpenVoronoi, it is used merely for drawing and
verifying solutions etc.
There are functions for:
- voronoi-bisectors and verifying the parametric equations for bisector... |
"""
Fast cryptographic hash of Python objects, with a special case for fast
hashing of numpy arrays.
"""
# Copyright (c) 2009 Gael Varoquaux
# License: BSD Style, 3 clauses.
import warnings
import pickle
import hashlib
import sys
import types
import struct
import io
if sys.version_info[0] < 3:
Pickler = pickle.... |
#!/usr/bin/env python3
"""Generate Mobile Phone Regex
Usage:
generate-mobile-phone-regex.py -d [-i INPUT]
generate-mobile-phone-regex.py [-i INPUT [-o OUTPUT] [-O OUTPUT2]]
Options:
-i --input INPUT Input XML file path with phone information for all regions (from `libphonenumber`)
... |
from spack import *
class Pigz(MakefilePackage):
"""A parallel implementation of gzip for modern multi-processor,
multi-core machines."""
homepage = "http://zlib.net/pigz/"
url = "http://zlib.net/pigz/pigz-2.3.4.tar.gz"
version('2.3.4', '08e6b2e682bbf65ccf12c8966d633fc6')
depends_on... |
"""
This module provides document parsing and transformation utilities for
both SGML and XML.
"""
import os, dom, transforms, parsers, sys
import xml.sax, types
from xml.sax.handler import ErrorHandler
from xml.sax.xmlreader import InputSource
from cStringIO import StringIO
def transform(node, *args):
result = node... |
from sqlalchemy.schema import MetaData
from sqlalchemy.schema import Table
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
metadef_objects = Table('metadef_objects', meta, autoload=True)
metadef_objects.c.schema.alter(name='json_schema')
metadef_properties = Table('metadef_propertie... |
__title__ = "_TaskPanelFemMeshRegion"
__author__ = "Bernd Hahnebach"
__url__ = "http://www.freecadweb.org"
## @package TaskPanelFemMeshRegion
# \ingroup FEM
import FreeCAD
import FreeCADGui
from PySide import QtGui
from PySide import QtCore
class _TaskPanelFemMeshRegion:
'''The TaskPanel for editing References... |
import re
import sys
import os
def validate_injected_script(fileName):
f = open(fileName, "r")
lines = f.readlines()
f.close()
proto_functions = "|".join([
# Array.prototype.*
"concat", "every", "filter", "forEach", "indexOf", "join", "lastIndexOf", "map", "pop",
"push", "redu... |
"""
@author: Andrew Case
@license: GNU General Public License 2.0
@contact: <EMAIL>
@organization:
"""
import struct
from operator import attrgetter
import volatility.obj as obj
import volatility.debug as debug
import volatility.addrspace as addrspace
import volatility.plugins.linux.common as linux_c... |
"""Finds Guids that do not have referents or that point to referents that no longer exist.
E.g. a node was created and given a guid but an error caused the node to
get deleted, leaving behind a guid that points to nothing.
"""
import sys
from modularodm import Q
from framework.guid.model import Guid
from website.app ... |
"""Pretty-prints the contents of a GYP file."""
import sys
import re
# Regex to remove comments when we're counting braces.
COMMENT_RE = re.compile(r'\s*#.*')
# Regex to remove quoted strings when we're counting braces.
# It takes into account quoted quotes, and makes sure that the quotes match.
# NOTE: It does not... |
import ConfigParser
import os
import sys
import install_venv_common as install_venv # flake8: noqa
def print_help(project, venv, root):
help = """
%(project)s development environment setup is complete.
%(project)s development uses virtualenv to track and manage Python
dependencies while in developm... |
#!/usr/bin/env python
from __future__ import unicode_literals
# Allow direct execution
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from youtube_dl import YoutubeDL
from youtube_dl.compat import compat_http_server, compat_urllib_request
import ss... |
"""
Module providing functions for getting the list of timezones, writing timezone
configuration, valid timezones recognition etc.
"""
import os
import pytz
import langtable
from collections import OrderedDict
from pyanaconda import iutil
from pyanaconda.constants import THREAD_STORAGE
from pyanaconda.flags import f... |
"""
Tests for branding page
"""
import datetime
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseRedirect
from django.test.utils import override_settings
from django.test.client import RequestFactory
from pytz import UTC
from mock import patch,... |
import re
import json
from .common import InfoExtractor
from ..utils import unified_strdate, determine_ext
class RoxwelIE(InfoExtractor):
_VALID_URL = r'https?://www\.roxwel\.com/player/(?P<filename>.+?)(\.|\?|$)'
_TEST = {
u'url': u'http://www.roxwel.com/player/passionpittakeawalklive.html',
... |
#!/usr/bin/python
import os
import urllib
import hashlib
doctmpl = """<!doctype html>
<title>WebVTT cue data parser test %s</title>
<style>video { display:none }</style>
<script src=/resources/testharness.js></script>
<script src=/resources/testharnessreport.js></script>
<script src=/html/syntax/parsing/template.js><... |
# -*- coding: utf-8 -*-
"""
Client for connecting to Degreed.
"""
import datetime
import logging
import time
import requests
from six.moves.urllib.parse import urljoin # pylint: disable=import-error
from django.apps import apps
from integrated_channels.exceptions import ClientError
from integrated_channels.integra... |
"""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 numpy as np
import pandas
import nsfg
import thinkstats2
impor... |
from __future__ import absolute_import
import errno
import warnings
import hmac
from binascii import hexlify, unhexlify
from hashlib import md5, sha1, sha256
from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning
SSLContext = None
HAS_SNI = False
IS_PYOPENSSL = False
IS_SECURETRANSPORT = Fals... |
"""
Module for the categorical distribution node.
"""
import numpy as np
#from .expfamily import ExponentialFamily
#from .expfamily import ExponentialFamilyDistribution
from .expfamily import useconstructor
from .multinomial import (MultinomialMoments,
MultinomialDistribution,
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.eos import eos_system
from units.modules.utils import set_module_args
from .eos_module import TestEosModule, load_fixture
class TestEosSystemModule(TestEosModule):
... |
from multiprocessing import Process, Lock, Event
from threading import Thread
import re
from telegram import InlineQueryResultArticle, InputTextMessageContent, \
InlineQueryResultCachedPhoto, TelegramError, ParseMode
from src.LoggingServer import LoggingServer
class InlineQueryResponseDispatcher():
logger =... |
import ColaInterface
import PColaInterface
import random
from time import time
def benchmark(module):
'''returns a tuple with the cost of add and search in ms in given module'''
parser = module.initparser('LastFM_big.dat')
users = module.emptyType()
start = time()
for i in xrange(10):
... |
from .main import TorrentBytes
def start():
return TorrentBytes()
config = [{
'name': 'torrentbytes',
'groups': [
{
'tab': 'searcher',
'list': 'torrent_providers',
'name': 'TorrentBytes',
'description': 'See <a href="http://torrentbytes.net">Torrent... |
__author__ = 'Simons'
from main import*
from nltk.corpus import stopwords
from collections import Counter
from nltk import*
import types
import tfidf
def preProcessReviews(list):
porter = nltk.PorterStemmer()
stop = stopwords.words("english")
temp = []
i = 0;
G = []
for row in lis... |
import testscenarios
from nova.api import openstack as openstack_api
from nova.api.openstack import auth
from nova.api.openstack import compute
from nova.api.openstack import urlmap
from nova import test
from nova.tests.unit.api.openstack import fakes
class TestNoAuthMiddleware(testscenarios.WithScenarios, test.NoDB... |
"""Identity Tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ops.distributions import bijector_test_util
from tensorflow.python.ops.distributions import identity_bijector
from tensorflow.python.platform import test
class Id... |
import datetime
import uuid
import webob
from cinder import db
from cinder import exception
from cinder.openstack.common import jsonutils
from cinder.openstack.common.rpc import common as rpc_common
from cinder import test
from cinder.tests.api import fakes
from cinder.tests.api.v2 import stubs
from cinder import volu... |
"""
Manages the history of the open documents of a MainWindow.
Contains smart logic to switch documents if the active document is closed.
If no documents remain, listen to other HistoryManager instances and
make the document set-current there also current here.
"""
import weakref
import app
import signals
# This si... |
"""
Base class for Instructor celery tasks.
"""
import logging
from celery import Task
from celery.states import FAILURE, SUCCESS
from lms.djangoapps.instructor_task.models import InstructorTask
# define different loggers for use within tasks and on client side
TASK_LOG = logging.getLogger('edx.celery.task')
class... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
=========================================================================
Program: Visualization Toolkit
Module: TestNamedColorsIntegration.py
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from ansible.modules.network.nxos import nxos_bgp
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosBgpModule(TestNxosModule):
module = nxos_bgp
... |
import config
import re
import unittest
class ConfigTest(unittest.TestCase):
@classmethod
def add_validate_categories_test(cls, cfg):
def test(self):
# Categories must have underscores instead of spaces.
self.assertNotIn(' ', cfg.hidden_category)
self.assertNotIn(' ... |
import os
import pytest
import xlrd
import tempfile
from pyfas import Ppl
TEST_FLD = os.getcwd() + os.sep + "test_files" + os.sep
oscheck = pytest.mark.skipif(os.name == 'posix',
reason='this module works only on win')
def test_not_a_ppl():
with pytest.raises(ValueError) ... |
########################################################################
#
# File Name: Printer.py
#
# Documentation: http://docs.4suite.com/4DOM/Printer.py.html
#
"""
The printing sub-system.
WWW: http://4suite.com/4DOM e-mail: <EMAIL>
Copyright (c) 2000 Fourthought Inc, USA. All Rights Re... |
# !/usr/bin/env python
import tempfile
import sys
import subprocess
import shutil
import os
import hashlib
import contextlib
import gzip
import fnmatch
import tarfile
import zipfile
def generate_file_list(directory):
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
... |
"""Tests for initializers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib import layers
from tensorflow.contrib.layers.python.layers import initializers
from tensorflow.contrib.layers.python.layers import regu... |
from __future__ import unicode_literals
import frappe
from frappe.utils import add_days, cint, cstr, flt, getdate, nowdate, rounded, date_diff, money_in_words
from frappe.model.naming import make_autoname
from frappe import msgprint, _
from erpnext.accounts.utils import get_fiscal_year
from erpnext.setup.utils import... |
# The Game is where it all starts. A Game is an abstract and thin package in
# which all of the elements of the game are stored. It is responsible for
# creating the world, parsing and writing to save files, and turning on/off
# graphics.
from core import gfx
from core import world
import sys
import traceback
# A G... |
import pytest
import os
from _pytest.pytester import HookRecorder
from _pytest.config import PytestPluginManager
from _pytest.main import EXIT_OK, EXIT_TESTSFAILED
def test_make_hook_recorder(testdir):
item = testdir.getitem("def test_func(): pass")
recorder = testdir.make_hook_recorder(item.config.pluginmana... |
"""Support for the EZcontrol XS1 gateway."""
import asyncio
import logging
import voluptuous as vol
import xs1_api_client
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_SSL,
CONF_USERNAME,
)
from homeassistant.helpers import discovery
import homeassistant.helpers.confi... |
import numpy as np
from .ode_solver import OdeSolver
class RungeKutta4(OdeSolver):
"""
Runge-Kutta (4th order) method of integration:
https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
"""
def __init__(self, dt, single_dim):
"""
Default constructor.
:param dt: di... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from mothergeo.logging import loggable_class as loggable
class TestLoggable(unittest.TestCase):
"""
These test cases test the :py:func:`loggable_class` decorator method.
"""
def test_loggable_class_without_logger_name(self):
"""
... |
# -*- coding: utf-8 -*-
"""
==========================
Bipartite Graph Algorithms
==========================
"""
# Copyright (C) 2013-2015 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
import networkx as nx
__author__ = """\n""".join(... |
# -*- coding: utf-8 -*-
"""
sentry.search.solr.client
~~~~~~~~~~~~~~~~~~~~~~~~~
A majority of the Solr client is heavily inspired by Pysolr:
https://github.com/toastdriven/pysolr
The main differences are we focus on Python 2, and we must remove the
dependency on the ``requests`` library.
:copyright: (c) 2010-2014 by... |
"""A tool to collect crash signatures for Chrome builds on Linux."""
import fnmatch
import optparse
import os
import shutil
import subprocess
import struct
import sys
import tempfile
def VerifySymbolAndCopyToTempDir(symbol_file, temp_dir, sym_module_name):
"""Verify the symbol file looks correct and copy it to the... |
"""
Utility functions used in the neural network.
@copyright: The Broad Institute of MIT and Harvard 2015
"""
import numpy as np
"""Formats the vector theta containing the neural net coefficients into matrix form
"""
def linear_index(mat_idx, N, L, S, K):
l = mat_idx[0] # layer
n = mat_idx[1] # node
i = ... |
from django.db import models
from apps.seller.models.product import Product
from settings import CLOUDINARY
class Photo(models.Model): #exclusively product photos.
from settings import MEDIA_URL
product = models.ForeignKey(Product, related_name="photos")
rank = models.SmallIntegerField(null=Tr... |
#!/usr/bin/python
# coding=utf-8
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import patch
from mock import Mock
from diamond.collector import Collector
from flume import FlumeCollector
class TestFlumeCollector(CollectorTestCase):
def setUp(self):
... |
'''
Copyright 2016, EMC, Inc.
Author(s):
This script load SKU packs from sources specified in install_default.json
'''
import fit_path # NOQA: unused import
import os
import sys
import subprocess
import fit_common
from nose.plugins.attrib import attr
@attr(all=True)
class fit_template(fit_common.unittest.TestCas... |
{
'name': 'Margins in Sales Orders',
'version':'1.0',
'category' : 'Sales Management',
'description': """
This module adds the 'Margin' on sales order.
=============================================
This gives the profitability by calculating the difference between the Unit
Price and Cost Price.
"""... |
from __future__ import absolute_import
import socket
from .wait import wait_for_read
from .selectors import HAS_SELECT, SelectorError
def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnecti... |
import functools
import random
import go
import numpy as np
import tensorflow as tf
"""
Allowable symmetries:
identity [12][34]
rot90 [24][13]
rot180 [43][21]
rot270 [31][42]
flip [13][24]
fliprot90 [34][12]
fliprot180 [42][31]
fliprot270 [21][43]
"""
INVERSES = {
'identity': 'identity',
'rot90': 'rot270',
... |
# Configuration file for jointcal
from lsst.meas.algorithms import LoadIndexedReferenceObjectsTask
# Select external catalogs for Astrometry
config.astrometryRefObjLoader.retarget(LoadIndexedReferenceObjectsTask)
config.astrometryRefObjLoader.ref_dataset_name='pan-starrs'
config.astrometryRefObjLoader.filterMap = {
... |
"""Fixer that cleans up a tuple argument to isinstance after the tokens
in it were fixed. This is mainly used to remove double occurrences of
tokens as a leftover of the long -> int / unicode -> str conversion.
eg. isinstance(x, (int, long)) -> isinstance(x, (int, int))
-> isinstance(x, int)
"""
from .. impo... |
r"""Fixer for unicode.
* Changes unicode to str and unichr to chr.
* If "...\u..." is not unicode literal change it into "...\\u...".
* Change u"..." into "...".
"""
from ..pgen2 import token
from .. import fixer_base
_mapping = {"unichr" : "chr", "unicode" : "str"}
class FixUnicode(fixer_base.BaseFix):
BM_c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.