content string |
|---|
import unittest
import pandas as pd
class testCompletenessOfSummarisedData(unittest.TestCase):
def test_animal_data(self):
"""
Make sure each sample's fraction of abundance values sums very close
to 1. On toy data set only.
"""
animal_df = pd.read_csv("./summarised_animals... |
def deconstructible(*args, **kwargs):
"""
Class decorator that allow the decorated class to be serialized
by the migrations subsystem.
Accepts an optional kwarg `path` to specify the import path.
"""
path = kwargs.pop('path', None)
def decorator(klass):
def __new__(cls, *args, **kw... |
# -*- coding: utf-8 -*-
""" Tests for transcripts_utils. """
import unittest
from uuid import uuid4
import copy
import textwrap
from mock import patch, Mock
from django.test.utils import override_settings
from django.conf import settings
from django.utils import translation
from nose.plugins.skip import SkipTest
fro... |
"""
## @file
This file defines the base class for NuPIC 2 Python regions.
"""
import numpy
RealNumpyDType = numpy.float32
from abc import ABCMeta, abstractmethod
from nupic.support import getCallerInfo
def not_implemented(f):
"""A decorator that raises NotImplementedError exception when called
Keeps the docstrin... |
'''Unit tests for the admin template gatherer.'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
import StringIO
import tempfile
import unittest
from grit.gather import admin_template
from grit import util
from grit import grd_reader
from grit impo... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j. E Y'
TIME_FORMAT = 'G.i'
DATETIME_FORMAT = r'j. E Y \k\e\l\l\o G.i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_... |
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def find_instance(name):
cdb = pyrax.cloud_databases
instances = cdb.list()
if instances:
for instance in instances:
if instance.name == name:
return instance
return False
def sa... |
from . import parser |
"""
Support for Qwikswitch devices.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/qwikswitch/
"""
import logging
import voluptuous as vol
from homeassistant.const import (EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_... |
from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import SomeClass, SomeOtherException, UTF8Class, setup
class FilterSyntaxTests(SimpleTestCase):
@setup({'filter-syntax01': '{{ var|upper }}'})
def test_filter_syntax01(self):
"""
Basic filter ... |
from gnuradio import gr, gr_unittest, vocoder, blocks
class test_g721_vocoder (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block()
def tearDown (self):
self.tb = None
def test001_module_load (self):
data = (8,24,36,52,56,64,76,88,104,124,132,148,172,
... |
# -*- coding: utf-8
import requests
import tarfile
import yaml
import json
import subprocess
import re
from retrying import retry
from time import gmtime, strftime
import docker
from docker.types import IPAMConfig, IPAMPool
from cStringIO import StringIO
from commons.miscs import NoAvailableImages
import commons.utils... |
#!/usr/bin/env python
import sys
import logging
import iu.i524.S17IRP013.hadoop.hbase_to_hdfs as h2h
DEFAULT_STATION_ID = 'DST:IND000DEF'
logging.basicConfig(format = '%(asctime)s %(message)s',\
datefmt = '%m/%d/%Y %I:%M:%S %p',\
filename = 'wda_app.log',\
... |
from __future__ import unicode_literals
import errno
import io
import hashlib
import json
import os.path
import re
import types
import sys
import youtube_dl.extractor
from youtube_dl import YoutubeDL
from youtube_dl.utils import (
compat_str,
preferredencoding,
write_string,
)
def get_params(override=No... |
from sqlalchemy import orm
from neutron_lib import constants
from neutron_lib.exceptions import l3 as l3_exc
from neutron.db.models import l3 as l3_models
from neutron.db import models_v2
from neutron.services.l3_router import l3_router_plugin
class TricircleL3Plugin(l3_router_plugin.L3RouterPlugin):
# Override... |
from __future__ import absolute_import
import ujson
NORMAL_TWEET = """{
"coordinates": null,
"created_at": "Sat Sep 10 22:23:38 +0000 2011",
"truncated": false,
"favorited": false,
"id_str": "112652479837110273",
"in_reply_to_user_id_str": "783214",
"text": "@twitter meets @seepicturely at #tcdisrupt c... |
import os
import cgi
import sickbeard
from sickbeard import logger, common
def diagnose():
'''
Check the environment for reasons libnotify isn't working. Return a
user-readable message indicating possible issues.
'''
try:
import pynotify #@UnusedImport
except ImportError:
ret... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
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 the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
''' os_lbaas_deletion '''
import keystoneauth1
from oslo_serialization import jsonutils
from ansible.module_utils.basic import AnsibleModule
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
def main():
''' Main module function '''
module = AnsibleModule(
argument_... |
import hashlib
import socket
import struct
import jsonrpclib
from oslo.config import cfg
from neutron import context as nctx
from neutron.db import db_base_plugin_v2
from neutron.openstack.common import log as logging
from neutron.plugins.ml2.drivers.arista import exceptions as arista_exc
LOG = logging.getLogger(__n... |
#-*- coding: utf-8 -*-
import json
import sys
import re
import codecs
out8=codecs.getwriter("utf-8")(sys.stdout)
focus_h_tags=set((u"pakolaiset",u"refugeecrisis",u"syrianrefugees",u"syria",u"syyria",u"pakolaiskriisi",u"migrantcrisis",u"refugeeswelcome",u"migrants",u"réfugiés",u"syrie"))
def keep(tweet):
"""in go... |
"""
Tests for `bx.seq.seq`.
"""
import unittest
import os.path
import sys
import bx.seq, fasta_tests, nib_tests, qdna_tests
test_fa = "test_data/seq_tests/test.fa"
test2_fa = "test_data/seq_tests/test2.fa"
test_nib = "test_data/seq_tests/test.nib"
test_qdna = "test_data/seq_tests/test.qdna"
valid_fasta ... |
'''
Check the performance counters from SQL Server
See http://blogs.msdn.com/b/psssql/archive/2013/09/23/interpreting-the-counter-values-from-sys-dm-os-performance-counters.aspx
for information on how to report the metrics available in the sys.dm_os_performance_counters table
'''
# stdlib
import traceback
# 3rd party... |
from flask import Blueprint, request, jsonify, make_response
from app.users.models import Users, UsersSchema
from flask_restful import Api
from app.baseviews import Resource
from app.basemodels import db
from sqlalchemy.exc import SQLAlchemyError
from marshmallow import ValidationError
from werkzeug.security import gen... |
# -*- coding: utf-8 -*-
import unittest2
from openerp.tests import common
class test_single_transaction_case(common.SingleTransactionCase):
"""
Check the whole-class transaction behavior of SingleTransactionCase.
"""
def test_00(self):
"""Create a partner."""
cr, uid = self.cr, self.u... |
"""
Serialization
``django.core.serializers`` provides interfaces to converting Django
``QuerySet`` objects to and from "flat" data (i.e. strings).
"""
from __future__ import unicode_literals
from decimal import Decimal
from django.db import models
from django.utils import six
from django.utils.encoding import pytho... |
from spack import *
class RXlsx(RPackage):
"""Provide R functions to read/write/format Excel 2007 and Excel
97/2000/XP/2003 file formats."""
homepage = "http://code.google.com/p/rexcel/"
url = "https://cran.rstudio.com/src/contrib/xlsx_0.5.7.tar.gz"
version('0.5.7', '36b1b16f29c54b6089b1dae... |
from ndlib.ndtype import *
class Params:
"""Arguments Class"""
def __init__ (self):
self.token = 'unittest'
self.project = 'unittest'
self.time = [0, 100]
self.window = [0, 500]
self.voxel = [4.0, 4.0, 3.0]
self.channel_type = TIMESERIES
self.datatype = UINT8
self.resolution = 0
... |
from __future__ import absolute_import
import datetime
import logging
import os
import sys
import socket
from socket import error as SocketError, timeout as SocketTimeout
import warnings
from .packages import six
try: # Python 3
from http.client import HTTPConnection as _HTTPConnection
from http.client import... |
from distutils import log, dir_util
import os
from setuptools import Command
from setuptools import namespaces
from setuptools.archive_util import unpack_archive
import pkg_resources
class install_egg_info(namespaces.Installer, Command):
"""Install an .egg-info directory for the package"""
description = "In... |
from __future__ import unicode_literals
import re
import sickrage
from sickrage.core.caches.tv_cache import TVCache
from sickrage.core.helpers import bs4_parser, convert_size
from sickrage.providers import TorrentProvider
class TORRENTZProvider(TorrentProvider):
def __init__(self):
super(TORRENTZProvid... |
from hachoir_metadata.metadata import (registerExtractor,
Metadata, RootMetadata, MultipleMetadata)
from hachoir_parser.image import (
BmpFile, IcoFile, PcxFile, GifFile, PngFile, TiffFile,
XcfFile, TargaFile, WMF_File, PsdFile)
from hachoir_parser.image.png import getBitsPerPixel as pngBitsPerPixel
from ha... |
"""A device that can have interfaces"""
from Device import *
from Attachable import *
class Interfaceable(Attachable):
def __init__(self):
"""
Create a device that can have interfaces.
"""
Attachable.__init__(self)
self.adjacentRouterList = []
self.adj... |
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
class RegistrationModel(models.Model):
user = models.OneToOneField(User)
activation_key = models.CharField(max_length=40)
created_timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
... |
import json
import re
from oslo_config import cfg
from oslo_log import log as logging
import pecan
from pecan import rest
import wsmeext.pecan as wsme_pecan
from solum.api.controllers.v1.datamodel import app
from solum.api.controllers.v1 import workflow
from solum.api.handlers import app_handler
from solum.common imp... |
"""
Test grade calculation.
"""
from django.http import Http404
from django.test.utils import override_settings
from mock import patch
from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE
from student.tests.factories import UserFactory
from xmodule.modulestore.tests.factories import CourseFactor... |
"""Build and install the colormaps package."""
# Copyright (c) 2012 Andrew Dawson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the right... |
#!/usr/bin/env python
# make new dump file by combining snapshots from multiple NEB replica dumps
# Syntax: neb_combine.py -switch arg(s) -switch arg(s) ...
# -o outfile = new dump file
# each snapshot has NEB atoms from all replicas
# -r dump1 dump2 ... = replica dump files of NEB atoms
# ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''Unit tests for display module'''
import warnings
# Disable cache
import os
try:
os.environ.pop('LIBROSA_CACHE_DIR')
except KeyError:
pass
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams.update(matplotlib.rcParamsDefault)
import matplotlib.style
... |
#!/usr/bin/env python
### -- [2012-03-04 14:56:03] FlowRate and FlowSize anomaly parameter has be changed as
### -- ratio instead of absolute value
##-- [2012-04-08 22:31:20] Add GenAnomalyDot
##-- [2012-04-09 18:31:22] refactoring the whole file
## -- [2012-04-10 01:14:07] FLOW_RATE can work
##-- [2012-04-10 17:16:27... |
import arrow, logging, time
from pmuploader import PmDataUploader
from sdserror import SdsError, SdsNoPacketError
from sdssensor import SdsSensor
LOGLEVEL = logging.INFO
PORT = '/dev/serial0'
# Time delta between measurements, in seconds:
SAMPLING_PERIOD = 15
URL = "http://dusty.pythonanywhere.com/pm/sav... |
# test basic complex number functionality
# constructor
print(complex(1))
print(complex(1.2))
print(complex(1.2j))
print(complex("1"))
print(complex("1.2"))
print(complex("1.2j"))
print(complex(1, 2))
print(complex(1j, 2j))
# unary ops
print(bool(1j))
print(+(1j))
print(-(1 + 2j))
# binary ops
print(1j + False)
prin... |
"""
Inception V3, suitable for images with around 299 x 299
Reference:
Szegedy, Christian, et al. "Rethinking the Inception Architecture for Computer Vision." arXiv preprint arXiv:1512.00567 (2015).
Adopted from https://github.com/apache/incubator-mxnet/blob/
master/example/image-classification/symbols/i... |
from oslo_config import cfg
from oslo_log import log as logging
from nova.scheduler import filters
from nova.scheduler.filters import utils
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
CONF.import_opt('default_availability_zone', 'nova.availability_zones')
class AvailabilityZoneFilter(filters.BaseHostFilter):... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os, sys, unittest
import ctypes
from ctypes import wintypes
from ctypes import c_int, c_ulong, c_char_p, c_wchar_p, c_ushort
user32=ctypes.windll.user32
gdi32=ctypes.windll.gdi32
kernel32=ctypes.windll.kernel32
from MessageNumbers import msgs, sgsm... |
import distutils, os
from setuptools import Command
from distutils.util import convert_path
from distutils import log
from distutils.errors import *
from setuptools.command.setopt import edit_config, option_base, config_file
def shquote(arg):
"""Quote an argument for later parsing by shlex.split()"""
for c in ... |
from yowsup.structs import ProtocolTreeNode
from yowsup.layers.protocol_iq.protocolentities import ResultIqProtocolEntity
class SuccessLeaveGroupsIqProtocolEntity(ResultIqProtocolEntity):
'''
<iq type="result" from="g.us" id="{{ID}}">
<leave>
<group id="{{GROUP_JID}}"></group>
</le... |
from portality.dao import DomainObject
from portality.models import Account
class EditorGroup(DomainObject):
__type__ = "editor_group"
@classmethod
def group_exists_by_name(cls, name):
q = EditorGroupQuery(name)
res = cls.query(q=q.query())
ids = [hit.get("_source", {}).get("id") ... |
from subprocess import PIPE
from selenium.webdriver.common import service
class Service(service.Service):
"""Object that manages the starting and stopping of the
GeckoDriver."""
def __init__(
self, executable_path, firefox_binary=None, port=0, service_args=None,
log_path="geckod... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
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 the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
#-*- coding: utf-8-*-
import mysql.connector
config = {
'user': 'root',
'password': 'root',
'host': '127.0.0.1',
'database': 'test',
'raise_on_warnings': True,
}
class save_keys_to_mysql:
def __init__(self,path):
self.path=path
print(self.path)
def __conn(self,**conf):
try:
conn=mysql.connector.... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLayoutUnitsComboBox
.. 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 version.... |
"""Internal support module for sre"""
import _sre, sys
import sre_parse
from sre_constants import *
assert _sre.MAGIC == MAGIC, "SRE module mismatch"
if _sre.CODESIZE == 2:
MAXCODE = 65535
else:
MAXCODE = 0xFFFFFFFFL
def _identityfunction(x):
return x
_LITERAL_CODES = set([LITERAL, NOT_LITERAL])
_REPEA... |
from __future__ import absolute_import
from ..packages.six.moves import http_client as httplib
from ..exceptions import HeaderParsingError
def is_fp_closed(obj):
"""
Checks whether a given file-like object is closed.
:param obj:
The file-like object to check.
"""
try:
# Check vi... |
"""Sparse block 1-norm estimator.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.sparse.linalg import aslinearoperator
__all__ = ['onenormest']
def onenormest(A, t=2, itmax=5, compute_v=False, compute_w=False):
"""
Compute a lower bound of the 1-norm of ... |
from Tkinter import *
from Dialog import Dialog
# this shows how to create a new window with a button in it
# that can create new windows
class Test(Frame):
def printit(self):
print "hi"
def makeWindow(self):
"""Create a top-level dialog with some buttons.
This uses the Dialog class,... |
from operand import O_NONE, P_none
import syn_intel as intel
#hack MK
from syn_intel import intel_operand_syntax
#from syn_att import *
operator_list_invalid = [ 'invalid']
operator_list_call = ['syscall',
'call',
'vmcall',
'vmmcall']
operator_list... |
# coding: utf-8
from __future__ import unicode_literals
import re
import random
from .common import InfoExtractor
from ..utils import (
int_or_none,
float_or_none,
unified_strdate,
)
class PornoVoisinesIE(InfoExtractor):
_VALID_URL = r'http://(?:www\.)?pornovoisines\.com/showvideo/(?P<id>\d+)/(?P<di... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
author: Ansible Core Team (@ansible)
module: import_role
short_description: Import a role into a play
description:
- Much like the C(roles:) keyword, this task loads a role, but it allows you to control wh... |
"""Queues"""
__all__ = ['Queue', 'PriorityQueue', 'LifoQueue', 'JoinableQueue',
'QueueFull', 'QueueEmpty']
import collections
import heapq
from . import events
from . import futures
from . import locks
from .tasks import coroutine
class QueueEmpty(Exception):
'Exception raised by Queue.get(block=0)/... |
import os
def post_register_types(root_module):
enabled_features = os.environ['NS3_ENABLED_FEATURES'].split(',')
if 'EmuFdNetDevice' not in enabled_features:
if 'ns3::EmuFdNetDeviceHelper'in root_module:
root_module.classes.remove(root_module['ns3::EmuFdNetDeviceHelper'])
if 'TapFdNet... |
from datetime import datetime
from django.forms import SplitHiddenDateTimeWidget
from django.test import override_settings
from django.utils import translation
from .base import WidgetTest
class SplitHiddenDateTimeWidgetTest(WidgetTest):
widget = SplitHiddenDateTimeWidget()
def test_render_empty(self):
... |
"""Support for deCONZ covers."""
from homeassistant.components.cover import (
ATTR_POSITION,
DEVICE_CLASS_WINDOW,
DOMAIN,
SUPPORT_CLOSE,
SUPPORT_OPEN,
SUPPORT_SET_POSITION,
SUPPORT_STOP,
CoverEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import a... |
# Lispy: Scheme Interpreter in Python
# (c) Peter Norvig, 2010-16; See http://norvig.com/lispy.html
from __future__ import division
import math
import operator as op
# Types
Symbol = str # A Lisp Symbol is implemented as a Python str
List = list # A Lisp List is implemented as a Python list
Numb... |
"""
Common utilities for tests in block_structure module
"""
from contextlib import contextmanager
from uuid import uuid4
from unittest.mock import patch
from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
from xmodule.modulestore.exceptions import ItemNotFoundError
from ..api import get_cache
fro... |
from __future__ import division
from __future__ import print_function
import platform
import copy
import os
import signal
import socket
import subprocess
import sys
import time
from optparse import OptionParser
from util import local_libpath
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
SCRIPTS = [
'Fa... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
NewPreconfiguredAlgorithmAction.py
---------------------
Date : April 2016
Copyright : (C) 2016 by Victor Olaya
Email : volayaf at gmail dot com
********... |
"""
Access the TOC cache for reading/writing. It supports both user
cache and dist cache.
"""
__author__ = 'Bitcraze AB'
__all__ = ['TocCache']
import os
import json
from glob import glob
import logging
logger = logging.getLogger(__name__)
from .log import LogTocElement # pylint: disable=W0611
from .param import P... |
"""
This module provides methods for postprocessing probabilities and data.
"""
import logging
import numpy as np
import bet.sample as sample
class dim_not_matching(Exception):
"""
Exception for when the dimension is inconsistent.
"""
class bad_object(Exception):
"""
Exception for when the wrong ... |
import copy
import re
import sys
import logging
from oslo_config import cfg
from oslo_policy import policy
from monasca_api.common.policy.i18n import _LW
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
POLICIES = None
USER_BASED_RESOURCES = ['os-keypairs']
KEY_EXPR = re.compile(r'%\((\w+)\)s')
_ENFORCER = None
#... |
import os, sys, base64
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import subresource
def generate_payload(request, server_data):
data = ('{"headers": %(headers)s}') % server_data
if "id" in request.GET:
request.server.stash.put(request.GET["id"], data)
# Simple base64 encoded .t... |
from datetime import date, datetime, time
from django.forms import SplitDateTimeWidget
from .base import WidgetTest
class SplitDateTimeWidgetTest(WidgetTest):
widget = SplitDateTimeWidget()
def test_render_empty(self):
self.check_html(self.widget, 'date', '', html=(
'<input type="text" ... |
# -*- coding: utf-8 -*-
# 第 0006 题:你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
import re
import os
# Get all files in designated path
def get_files(path):
filepath = os.listdir(path)
files = []
for fp in filepath:
fppath = path + '/' + fp
if(os.path.isfile(fppath)):
... |
"""functools.py - Tools for working with functions and callable objects
"""
# Python module wrapper for _functools C module
# to allow utilities written in Python to be added
# to the functools module.
# Written by Nick Coghlan <ncoghlan at gmail.com>
# and Raymond Hettinger <python at rcn.com>
# Copyright (C) 2006-2... |
"""
I/O classes provide a uniform API for low-level input and output. Subclasses
exist for a variety of input/output mechanisms.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import re
import codecs
from docutils import TransformSpec
from docutils._compat import b
from docutils.utils.error_reporting im... |
from __future__ import unicode_literals
import json
import os
import sys
import environment as env
import products
import testloader
import wptcommandline
import wptlogging
import wpttest
from testrunner import ManagerGroup
here = os.path.split(__file__)[0]
logger = None
"""Runner for web-platform-tests
The runne... |
"""
MagPy
Auxiliary input filter - Write AUTODIF read-in data for F (also read)
Written by Rachel Bailey
- contains test and read function, toDo: write function
"""
from magpy.stream import *
def isAUTODIF_FREAD(filename):
"""
Checks whether a file is text POS-1 file format.
"""
try:
line = op... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
DeleteDuplicateGeometries.py
---------------------
Date : May 2010
Copyright : (C) 2010 by Michael Minn
Email : pyqgis at michaelminn dot com
***********... |
import decimal
import unittest
import pytest
from babel import plural
def test_plural_rule():
rule = plural.PluralRule({'one': 'n is 1'})
assert rule(1) == 'one'
assert rule(2) == 'other'
rule = plural.PluralRule({'one': 'n is 1'})
assert rule.rules == {'one': 'n is 1'}
def test_plural_rule_ope... |
"""
:Author: M. Simionato
:Date: April 2004
:Title: A much simplified interface to optparse.
You should use optionparse in your scripts as follows.
First, write a module level docstring containing something like this
(this is just an example)::
'''usage: %prog files [options]
-d, --delete: delete all files... |
# Standard library
import unittest
def decompose_number_on_base(number, base):
"""
Returns a number's decomposition on a defined base
:param number: The number to decompose
:param base: list representing the base. It must be sorted and
each element must be a multiple of its predecessor. First element
must be 1.... |
from collections import namedtuple
import glob
from optparse import OptionParser
import os
import re
import shutil
import subprocess
import sys
import threading
import Queue
version = 'build-all.py, version 1.99'
build_dir = '../all-kernels'
make_command = ["vmlinux", "modules", "dtbs"]
all_options = {}
compile64 = o... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
from contextlib import closing
from time import time
from uuid import uu... |
from django.contrib import messages
from django.contrib.auth.models import Permission
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import get_object_or_404, redirect
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
from djang... |
"""
Support for inheritance of fields down an XBlock hierarchy.
"""
from __future__ import absolute_import
from datetime import datetime
from pytz import UTC
from xmodule.partitions.partitions import UserPartition
from xblock.fields import Scope, Boolean, String, Float, XBlockMixin, Dict, Integer, List
from xblock.run... |
# -*- coding: utf-8 -*-
import unittest
import boto
TABLE_NAME = 'Table-HR'
TABLE_NAME_404 = 'Waldo'
TABLE_RT = 45
TABLE_WT = 123
TABLE_RT2 = 10
TABLE_WT2 = 10
TABLE_HK_NAME = u'hash_key'
TABLE_HK_TYPE = u'N'
TABLE_RK_NAME = u'range_key'
TABLE_RK_TYPE = u'S'
HK_VALUE = u'123'
HK_VALUE_404 = u'404'
RK_VALUE1 = u'Wald... |
"""
SciDB query generation and execution. The query building themselves are
fairly low-level, since their only concern is whether to generate temporary
arrays or not.
"""
from __future__ import absolute_import, division, print_function
import uuid
from itertools import chain
#----------------------------------------... |
"""Utilities and helper functions."""
import collections
import datetime
import decimal
import errno
import functools
import hashlib
import multiprocessing
import netaddr
import os
import random
import signal
import socket
import sys
import tempfile
import uuid
import debtcollector
from eventlet.green import subproce... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.lookup import LookupBase
from ansible.inventory import Inventory
class LookupModule(LookupBase):
def get_hosts(self, variables, pattern):
hosts = []
if pattern[0] in ('!','&'):
... |
# -*- coding: utf-8 -*-
import openerp
from openerp import http, SUPERUSER_ID
from openerp.http import request
import time
GENGO_DEFAULT_LIMIT = 20
class website_gengo(http.Controller):
@http.route('/website/get_translated_length', type='json', auth='user', website=True)
def get_translated_length(self, tran... |
'''Copyright 2015 Chris Young
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 the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... |
#
# big5hkscs.py: Python Unicode Codec for BIG5HKSCS
#
# Written by Hye-Shik Chang <<EMAIL>>
#
import _codecs_hk, codecs
import _multibytecodec as mbc
codec = _codecs_hk.getcodec('big5hkscs')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.MultibyteIncreme... |
from __future__ import absolute_import
from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.lib.actions import create_stream_if_needed, do_add_subscription
from zerver.models import Realm, UserProfile, get_user_profile_by_email
class Command(BaseCommand):
help = """Ad... |
import string
from tkinter import *
from idlelib.Delegator import Delegator
#$ event <<redo>>
#$ win <Control-y>
#$ unix <Alt-z>
#$ event <<undo>>
#$ win <Control-z>
#$ unix <Control-z>
#$ event <<dump-undo-state>>
#$ win <Control-backslash>
#$ unix <Control-backslash>
class UndoDelegator(Delegator):
max_und... |
# -*- coding: utf-8 -*-
#from compat import unicode, bytes
# TODO: round-tripping tests
import pytest
from hematite.url import URL, _URL_RE, parse_authority
TEST_URLS = [
'*', # e.g., OPTIONS *
'http://googlewebsite.com/e-shops.aspx',
'http://example.com:8080/search?q=123&business=Nothing%20Special',... |
# This is a variant of the very old (early 90's) file
# Demo/threads/bug.py. It simply provokes a number of threads into
# trying to import the same module "at the same time".
# There are no pleasant failure modes -- most likely is that Python
# complains several times about module random having no attribute
# randran... |
import tweepy
from zope import interface
from twisted.application import service
from twisted.internet import defer, threads, reactor
from piped import exceptions, log, resource, util
class MyTwitterProvider(object):
# state that we are a resource provider, so that the piped plugin system finds us
interface.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Functions to format apertium style analyses from omorfi data."""
# 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 3 of the... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from cms.models import Page
from cms.test_utils.fixtures.navextenders import NavextendersFixture
from cms.test_utils.testcases import SettingsOverrideTestCase
from cms.test_utils.util.menu_extender import TestMenu
from django.conf import settings
from django... |
#!/usr/bin/env python
# This will create golden files in a directory passed to it.
# A Test calls this internally to create the golden files
# So it can process them (so we don't have to checkin the files).
# Ensure msgpack-python and cbor are installed first, using:
# sudo apt-get install python-dev
# sudo apt-g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.