content stringlengths 4 20k |
|---|
{
'name': 'Payment Follow-up Management',
'version': '1.0',
'category': 'Accounting & Finance',
'description': """
Module to automate letters for unpaid invoices, with multi-level recalls.
=========================================================================
You can define your multiple levels of r... |
"""Verifies that all gRPC Python artifacts have been successfully published.
This script is intended to be run from a directory containing the artifacts
that have been uploaded and only the artifacts that have been uploaded. We use
PyPI's JSON API to verify that the proper filenames and checksums are present.
Note th... |
import sigrokdecode as srd
class Decoder(srd.Decoder):
api_version = 2
id = 'tca6408a'
name = 'TI TCA6408A'
longname = 'Texas Instruments TCA6408A'
desc = 'Texas Instruments TCA6408A 8-bit I²C I/O expander.'
license = 'gplv2+'
inputs = ['i2c']
outputs = ['tca6408a']
annotations = (
... |
"""
Django settings for rssweb project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... |
"""
Provides modules containing classes to support
unmarshalling (XML).
"""
from suds.sudsobject import Object
class Content(Object):
"""
@ivar node: The content source node.
@type node: L{sax.element.Element}
@ivar data: The (optional) content data.
@type data: L{Object}
@ivar text: The (op... |
"""Tests for QueueRunner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import time
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, cint, getdate, formatdate, comma_and, time_diff_in_seconds, to_timedelta
from frappe.model.document import Document
from dateutil.parser import parse
class WorkstationHolidayError(frappe.ValidationError): pass
clas... |
apiAttachAvailable = u'API Available'
apiAttachNotAvailable = u'Not Available'
apiAttachPendingAuthorization = u'Pending Authorization'
apiAttachRefused = u'Refused'
apiAttachSuccess = u'Success'
apiAttachUnknown = u'Unknown'
budDeletedFriend = u'Deleted From Friendlist'
budFriend = u'Friend'
budNeverBeenFriend... |
"""Unit tests for the pipeline options validator module."""
import logging
import unittest
from apache_beam.internal import pickler
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options_validator import PipelineOptionsValidator
from hamcrest.core.base_matcher impor... |
"""
This file implements the Middleware support for the Open edX platform.
A microsite enables the following features:
1) Mapping of sub-domain name to a 'brand', e.g. foo-university.edx.org
2) Present a landing page with a listing of courses that are specific to the 'brand'
3) Ability to swap out some branding elemen... |
#! /usr/bin/env python
from __future__ import print_function
import os
import subprocess
import sys
import pytest
PYTEST_ARGS = {
'default': ['tests', '--tb=short', '-s'],
'fast': ['tests', '--tb=short', '-q', '-s'],
}
FLAKE8_ARGS = ['rest_framework', 'tests', '--ignore=E501']
ISORT_ARGS = ['--recursive', ... |
import cPickle as pickle
import mock
import os
import unittest
import random
import itertools
from contextlib import closing
from gzip import GzipFile
from tempfile import mkdtemp
from shutil import rmtree
from time import time
from distutils.dir_util import mkpath
from eventlet import spawn, Timeout, listen
from swi... |
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask import url_for
from google.appengine.ext import ndb
from os import urandom
import base64
app = Flask(__name__)
# Note: We don't need to call run() since our application is embedded within
# the Ap... |
import argparse
import unittest
from coalib.parsing.CliParsing import parse_cli, check_conflicts
class CliParserTest(unittest.TestCase):
def setUp(self):
self.test_arg_parser = argparse.ArgumentParser()
self.test_arg_parser.add_argument('-t', nargs='+', dest='test')
self.test_arg_parser.... |
from twitter.common.lang import Compatibility, Singleton
from .gauge import (
Gauge,
MutatorGauge,
NamedGauge,
namablegauge)
class Observable(object):
"""
A trait providing a metric namespace for an object.
Classes should mix-in Observable and register metrics against self.metrics.
Application... |
# coding: utf-8
from __future__ import division, unicode_literals
"""
This module implements symmetry-related structure forms.
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "<EMAIL>"
__date__ = "Mar 9, 2012... |
"""add ti job_id index
Revision ID: 947454bf1dff
Revises: bdaa763e6c56
Create Date: 2017-08-15 15:12:13.845074
"""
# revision identifiers, used by Alembic.
revision = '947454bf1dff'
down_revision = 'bdaa763e6c56'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
... |
import os.path
import inspect
import sys
from _pydev_tipper_common import DoFind
#completion types.
TYPE_IMPORT = '0'
TYPE_CLASS = '1'
TYPE_FUNCTION = '2'
TYPE_ATTR = '3'
TYPE_BUILTIN = '4'
TYPE_PARAM = '5'
def _imp(name, log=None):
try:
return __import__(name)
except:
if '.' in name:
... |
from helpers import unittest
try:
from unittest import mock
except ImportError:
import mock
import luigi.rpc
from luigi.scheduler import CentralPlannerScheduler
import central_planner_test
import luigi.server
from server_test import ServerTestBase
import time
import socket
class RemoteSchedulerTest(unittest.... |
from django.conf import settings
import requests
class Webhooks:
@staticmethod
def send_discord_message(message):
if(not hasattr(settings, 'DISCORD_WEBHOOK')):
return # No discord webhook set up
post_data = {'content': message}
try:
requests.post(settings.DIS... |
import win32security,win32api,win32con, win32process
## You need SE_RESTORE_NAME to be able to set the owner of a security descriptor to anybody
## other than yourself or your primary group. Most admin logins don't have it by default, so
## enabling it may fail
new_privs = ((win32security.LookupPrivilegeValue('',w... |
import time
from threading import Thread
from muntjac.application import Application
from muntjac.ui.window import Window
from muntjac.ui.panel import Panel
from muntjac.ui.horizontal_layout import HorizontalLayout
from muntjac.addon.refresher.refresher import Refresher
from muntjac.ui.label import Label
from muntjac... |
import logging
import os
import dj_database_url
from lib.settings_base import CACHE_PREFIX, KNOWN_PROXIES, LOGGING, HOSTNAME
from .. import splitstrip
import private_base as private
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = private.EMAIL_HOST
SEND_REAL_EMAIL = True
ENGAGE_ROBOTS =... |
#!/usr/bin/env python
#
# Codec encoding tests for ISO 2022 encodings.
from test import test_support
from test import test_multibytecodec_support
import unittest
COMMON_CODEC_TESTS = (
# invalid bytes
(b'ab\xFFcd', 'replace', u'ab\uFFFDcd'),
(b'ab\x1Bdef', 'replace', u'ab\x1Bdef'),
(b'... |
# this is an optimized version only available in later Django versions
from django.utils.unittest import TestCase
from evennia.scripts.models import ScriptDB, ObjectDoesNotExist
from evennia.utils.create import create_script
from evennia.scripts.scripts import DoNothing
class TestScriptDB(TestCase):
"Check the s... |
from master.factory import chromium_factory
from master.factory import gclient_factory
from master.factory import chromium_commands
import config
class WebRTCFactory(chromium_factory.ChromiumFactory):
CUSTOM_VARS_ROOT_DIR = ('root_dir', 'src')
# Can't use the same Valgrind constant as in chromium_factory.py, s... |
import numpy as np
import pandas as pd
import sklearn
import tensorflow as tf
from sklearn import feature_extraction, ensemble, decomposition, pipeline
from sklearn.model_selection import KFold
# from textblob import TextBlob
from nfold_train import nfold_train, models_eval
import time
from time import gmtime, strftime... |
import unittest, string
from test import test_support, string_tests
from UserList import UserList
class StringTest(
string_tests.CommonTest,
string_tests.MixinStrStringUserStringTest
):
type2test = str
def checkequal(self, result, object, methodname, *args):
realresult = getattr(string, m... |
"""
Handlers dealing with nodes
"""
from datetime import datetime
import web
from nailgun.api.v1.handlers.base import BaseHandler
from nailgun.api.v1.handlers.base import CollectionHandler
from nailgun.api.v1.handlers.base import content
from nailgun.api.v1.handlers.base import SingleHandler
from nailgun.api.v1.vali... |
#!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collector import Collector
from postfix import ... |
from __future__ import absolute_import
#from twisted.trial import unittest
import unittest
from zope.interface import implementer
from autobahn.wamp.interfaces import *
from autobahn.wamp.types import *
from autobahn.wamp.exception import ApplicationError, ProtocolError
from twisted.internet.defer import Deferred,... |
# coding=utf-8
"""
The CPUCollector collects CPU utilization metric using /proc/stat.
#### Dependencies
* /proc/stat
"""
import diamond.collector
import os
import time
from diamond.collector import str_to_bool
try:
import psutil
except ImportError:
psutil = None
class CPUCollector(diamond.collector.Col... |
from functools import partial
from openerp import SUPERUSER_ID
from openerp.osv import osv, fields
class report_paperformat(osv.Model):
_name = "report.paperformat"
_description = "Allows customization of a report."
_columns = {'name': fields.char('Name', required=True),
'default': field... |
from __future__ import absolute_import, print_function
import logging
logger = logging.getLogger(__name__)
from six import string_types
from ..core.properties import Auto, Either, Enum, Float, Int, Seq, Instance, String, Tuple
from ..core.enums import HorizontalLocation, VerticalLocation
from ..models import Plot
fr... |
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.Console import Console
from Components.ActionMap import ActionMap, NumberActionMap
from Components.Pixmap import Pixmap
from Components.Label import Label
from Components.Sources.StaticText import StaticText
from Components.MenuLis... |
"""gypd output module
This module produces gyp input as its output. Output files are given the
.gypd extension to avoid overwriting the .gyp files that they are generated
from. Internal references to .gyp files (such as those found in
"dependencies" sections) are not adjusted to point to .gypd files instead;
unlike ... |
"""Platform-independent TinyInteger type."""
from sqlalchemy.types import Integer, TypeDecorator
from sqlalchemy.dialects.mysql import TINYINT
class LegacyTinyInteger(TypeDecorator):
"""Platform-independent TinyInteger type.
Uses MySQL's :class:`~sqlalchemy.dialects.mysql.TINYINT` type, otherwise
uses ... |
# coding: utf-8
from __future__ import unicode_literals
import sys
PY2 = True
if sys.version < '3':
from future.builtins import str, int
PY2 = False
import datetime
import json
from decimal import Decimal
from .TimeFormatFactory import TimeFormatFactory
try:
from django.db import models
from django... |
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_dns
version_added: '2.8'
short_description: Configure... |
{
"name": "Quality control - Samples in inspections",
"version": "1.0",
"depends": [
"quality_control",
],
"author": "OdooMRP team,"
"AvanzOSC,"
"Serv. Tecnol. Avanzados - Pedro M. Baeza",
"category": "Quality control",
'data': [
'security/ir.model... |
from pydevd_constants import * #@UnusedWildImport
try:
from Queue import Queue
except:
from queue import Queue #@UnresolvedImport
import threading
from pydev_imports import xmlrpclib
import traceback
import time
from pydev_runfiles_coverage import StartCoverageSupportFromParams
#=============================... |
"""
Polish-specific form helpers
"""
import re
from django.forms import ValidationError
from django.forms.fields import Select, RegexField
from django.utils.translation import ugettext_lazy as _
from django.core.validators import EMPTY_VALUES
class PLProvinceSelect(Select):
"""
A select widget with list of P... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import codecs
import datetime
import locale
from decimal import Decimal
from django.utils import six
from django.utils.functional import Promise
from django.utils.six.moves.urllib.parse import quote, unquote
if six.PY3:
from urllib.parse import un... |
from pychron.core.ui.factory import toolkit_factory
# ============= standard library imports ========================
# ============= local library imports ==========================
ImageEditor = toolkit_factory('image_editor', 'ImageEditor')
# ============= EOF ============================================= |
from __future__ import absolute_import, division
import time
import os
import sys
import errno
from . import (LockBase, LockFailed, NotLocked, NotMyLock, LockTimeout,
AlreadyLocked)
class MkdirLockFile(LockBase):
"""Lock file by creating a directory."""
def __init__(self, path, threaded=True):... |
"""Helper for aiohttp webclient stuff."""
import asyncio
import sys
import aiohttp
from aiohttp.hdrs import USER_AGENT, CONTENT_TYPE
from aiohttp import web
from aiohttp.web_exceptions import HTTPGatewayTimeout, HTTPBadGateway
import async_timeout
from homeassistant.core import callback
from homeassistant.const impor... |
import os
from optparse import OptionParser
import random
import errno
from perfmon import *
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-e", "--events", help="Events to use",
action="store", dest="events")
(options, args) = parser.parse_args()
s = PerThreadSessio... |
"""Test various fingerprinting protections.
If a stale block more than a month old or its header are requested by a peer,
the node should pretend that it does not have it to avoid fingerprinting.
"""
import time
from test_framework.blocktools import (create_block, create_coinbase)
from test_framework.messages import... |
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, add_days, date_diff
from frappe import _
from frappe.utils.csvutils import UnicodeWriter
from frappe.model.document import Document
class UploadAttendance(Document):
pass
@frappe.whitelist()
def get_template():
if not frappe.has_pe... |
"""Alternate PIL plugin for dealing with Microsoft .ico files. Handles XOR
transparency masks, XP style 8bit alpha channels and Vista style PNG image
parts.
>>> import PIL.Image
>>> import Win32IconImagePlugin
>>> ico = PIL.Image.open("down.ico")
>>> print ico.info['sizes']
set([(16, 16), (48, 48), (256, 256), (32, 3... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from ... import units as u
from .. import transformations as t
from ..builtin_frames import ICRS, FK5, FK4, FK4NoETerms, Galactic
from .. import representation as r
from ..baseframe import f... |
__version__ = "0.1"
import struct
from io import BytesIO
from PIL import Image, ImageFile, BmpImagePlugin, PngImagePlugin, _binary
from math import log, ceil
#
# --------------------------------------------------------------------
i8 = _binary.i8
i16 = _binary.i16le
i32 = _binary.i32le
_MAGIC = b"\0\0\1\0"
def _... |
#!/usr/bin/env python
try:
import argparse
except ImportError:
from local_libs import argparse_local as argparse
import ConfigParser
from dlib.ansible_helpers import flatten_ansible_struct, fetch_struct, run_custom_command, gut_struct, save_struct
def load_ini(path):
"""
:param path: Absolute path o... |
import numpy as np
from ase.calculators.singlepoint import SinglePointCalculator
from ase.atom import Atom
from ase.atoms import Atoms
def read_dacapo_text(fileobj):
if isinstance(fileobj, str):
fileobj = open(fileobj)
lines = fileobj.readlines()
i = lines.index(' Structure: A1 ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils._text import to_bytes, to_text
from ansible.template import generate_ansible_template_vars
try:
from __... |
from sqlalchemy import inspect
from app.views.pika_ import pika_
from geokrety_api_models import Move
def _has_changes_that_need_recompute(instance):
if inspect(instance).attrs.type.history.has_changes() or \
inspect(instance).attrs.moved_on_datetime.history.has_changes() or \
inspect(ins... |
from __future__ import division, absolute_import, print_function
from subprocess import PIPE, Popen
import sys
import re
from numpy.linalg import lapack_lite
from numpy.testing import TestCase, dec, run_module_suite
from numpy.compat import asbytes_nested
class FindDependenciesLdd(object):
def __init__(self):... |
import numpy as np
from numpy.linalg import eigvalsh, eigh, matrix_power
import matplotlib.pyplot as plt
from scipy.special import gamma
from scipy.optimize import curve_fit
from qca import multipage
from figure3 import select, moving_average
# plotting defaults
import matplotlib as mpl
mpl.rcParams["text.latex.pream... |
from Tkinter import Tk, BOTH, END, IntVar, StringVar, LEFT
from ttk import Button, Checkbutton, Frame, Style, Combobox, Label, Entry
from tkFileDialog import askopenfilename
import tkMessageBox
from helpers import *
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
clas... |
import datetime
from django.forms import ValidationError # noqa
from django.utils.translation import ugettext_lazy as _
from horizon import forms
class UsageReportForm(forms.SelfHandlingForm):
PERIOD_CHOICES = (("1", _("Last day")),
("7", _("Last week")),
(str(dateti... |
"""
Support for Actions on Google Assistant Smart Home Control.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/google_assistant/
"""
import asyncio
import logging
from typing import Dict, Any
import aiohttp
import async_timeout
import voluptuous as vo... |
""" Test_RSS_Policy_DTPolicy
"""
from mock import MagicMock
import unittest
from DIRAC import gLogger
import DIRAC.ResourceStatusSystem.Policy.DowntimePolicy as moduleTested
__RCSID__ = '$Id: $'
################################################################################
class DTPolicy_TestCase( unittest.TestC... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
SVM-Kernels
=========================================================
Three different types of SVM-Kernels are displayed below.
The polynomial and RBF are especially useful when the
data-points are not linearly sep... |
import mock
from rally.plugins.openstack.scenarios.murano import environments
from tests.unit import test
CTX = "rally.task.context"
MURANO_SCENARIO = ("rally.plugins.openstack.scenarios.murano."
"environments.MuranoEnvironments")
class MuranoEnvironmentsTestCase(test.TestCase):
def _get_con... |
"""A cliff walking single agent reinforcement learning environment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from open_spiel.python import rl_environment
# Actions
RIGHT, UP, LEFT, DOWN = range(4)
class Environment(object):
... |
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.models import NOT_PROVIDED
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
sql_rename_table = "RENAME TABLE %(old_table)s TO %(new_table)s"
sql_alter_column_null = "MODIFY %(column)s %(type)s NULL"
sql_alter_column_... |
import logging
try:
set()
except NameError:
from sets import Set as set
from PyQt4.uic.Compiler.indenter import write_code
from PyQt4.uic.Compiler.qtproxies import QtGui, Literal, strict_getattr
logger = logging.getLogger(__name__)
DEBUG = logger.debug
class _QtGuiWrapper(object):
def search(clsname):... |
import decimal
import math
import re
from oslo_utils import units
import six
from django.conf import settings
from django.contrib.auth import logout # noqa
from django import http
from django.utils.encoding import force_text
from django.utils.functional import lazy # noqa
from django.utils import translation
def ... |
declare_host_attribute(ContactGroupsAttribute(),
show_in_table = False,
show_in_folder = True)
declare_host_attribute(NagiosTextAttribute("alias", "alias", _("Alias"),
_("A comment or description of this host"),
"", mandatory=F... |
from __future__ import absolute_import, print_function, division
import numpy
import theano.sandbox.cuda as cuda
import theano.misc.pycuda_init
if not theano.misc.pycuda_init.pycuda_available: # noqa
from nose.plugins.skip import SkipTest
raise SkipTest("Pycuda not installed. Skip test of theano op with pycu... |
"""
Plugin system for Twisted.
@author: Jp Calderone
@author: Glyph Lefkowitz
"""
import os
import sys
from zope.interface import Interface, providedBy
def _determinePickleModule():
"""
Determine which 'pickle' API module to use.
"""
try:
import cPickle
return cPickle
except Impo... |
import sys
import string
import binwalk.core.common as common
from binwalk.core.compat import *
from binwalk.core.module import Module, Option, Kwarg
class HexDiff(Module):
COLORS = {
'red': '31',
'green': '32',
'blue': '34',
}
SEPERATORS = ['\\', '/']
DEFAULT_BLOCK_SIZE = 16... |
"""Miscellaneous stuff for coverage.py."""
import errno
import hashlib
import inspect
import locale
import os
import sys
import types
from coverage import env
from coverage.backward import string_class, to_bytes, unicode_class
ISOLATED_MODULES = {}
def isolate_module(mod):
"""Copy a module so that we are isola... |
import os
import time
import glob
import tempfile
from abc import ABCMeta, abstractmethod
from ansible.module_utils._text import to_native
from ansible.module_utils.six import with_metaclass
yumdnf_argument_spec = dict(
argument_spec=dict(
allow_downgrade=dict(type='bool', default=False),
autoremo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_homepage(apps, schema_editor):
# Get models
ContentType = apps.get_model('contenttypes.ContentType')
Page = apps.get_model('wagtailcore.Page')
Site = apps.get_model('wagtailcore.Site')
Home... |
from openerp import api, fields, models, _
from openerp.tools.float_utils import float_round
from openerp.addons import decimal_precision as dp
UNIT = dp.get_precision('Product Unit of Measure')
class ProductTemplate(models.Model):
_inherit = "product.template"
qty_available_not_res = fields.Float(
... |
import pytest
from parsec.api.data import UserProfile
from parsec.api.protocol import OrganizationID, HumanHandle
from parsec.core.backend_connection import apiv1_backend_anonymous_cmds_factory
from parsec.core.types import BackendOrganizationBootstrapAddr
from parsec.core.invite import bootstrap_organization, InviteN... |
def register(c):
c.handlers = {
"link" : {},
"image" : {}
}
def handler(handlers, path, **kwargs):
if not "text" in kwargs:
kwargs["text"] = False
if not "fetch" in kwargs:
kwargs["fetch"] = False
if not "ext" in kwargs:
kwargs["ex... |
import json
from social.tests.backends.oauth import OAuth2Test
class DisqusOAuth2Test(OAuth2Test):
backend_path = 'social.backends.disqus.DisqusOAuth2'
user_data_url = 'https://disqus.com/api/3.0/users/details.json'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token':... |
"""Test the weedb package.
For this test to work, user 'weewx' must have full access to database 'test':
mysql> grant select, update, create, delete, drop, insert on test.* to weewx@localhost;
"""
from __future__ import with_statement
from __future__ import absolute_import
import unittest
import weedb
import wee... |
from __future__ import unicode_literals
from datetime import datetime, timedelta
import frappe
from frappe import _
from frappe.utils import cstr, cint
from frappe.model.document import Document
class TokenCache(Document):
def get_auth_header(self):
if self.access_token:
headers = {'Authorization': 'Bearer ' +... |
"""
The GeoDjango GEOS module. Please consult the GeoDjango documentation
for more details: https://docs.djangoproject.com/en/dev/ref/contrib/gis/geos/
"""
__all__ = ['HAS_GEOS']
try:
from .libgeos import geos_version, geos_version_info # NOQA: flake8 detects only the last __all__
HAS_GEOS = True
__all__... |
#!/usr/bin/env python
from nose.tools import *
import networkx as nx
from networkx import convert_node_labels_to_integers as cnlti
class TestBoundary:
def setUp(self):
self.null=nx.null_graph()
self.P10=cnlti(nx.path_graph(10),first_label=1)
self.K10=cnlti(nx.complete_graph(10),first_label... |
"""Python part of the warnings subsystem."""
import sys
__all__ = ["warn", "warn_explicit", "showwarning",
"formatwarning", "filterwarnings", "simplefilter",
"resetwarnings", "catch_warnings"]
def showwarning(message, category, filename, lineno, file=None, line=None):
"""Hook to write a wa... |
import warnings
warnings.filterwarnings("ignore", "strop functions are obsolete;",
DeprecationWarning,
r'test.test_strop|unittest')
import strop
import unittest
import sys
from test import test_support
class StropFunctionTestCase(unittest.TestCase):
def test_atoi(s... |
"""Check for an aggregated logging Fluentd deployment"""
import json
from openshift_checks import OpenShiftCheckException, OpenShiftCheckExceptionList
from openshift_checks.logging.logging import LoggingCheck
class Fluentd(LoggingCheck):
"""Check for an aggregated logging Fluentd deployment"""
name = "flu... |
# encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse,
)
class DaumIE(InfoExtractor):
_VALID_URL = r'https?://(?:m\.)?tvpot\.daum\.net/(?:v/|.*?clipid=)(?P<id>[^?#&]+)'
IE_NAME = 'daum.net'
_TESTS = [{
... |
#!/usr/bin/env python
# sizedist.py
# Description : Categorizes files based on their size and prints the number of files in different
# categories.
import os
def get_size(directory):
total_size=0
sizes = []
for dirpath, dirnames,filenames in os.walk(directory): #
for filena... |
{
'name': 'Purchase Management',
'version': '1.1',
'category': 'Purchase Management',
'sequence': 19,
'summary': 'Purchase Orders, Receptions, Supplier Invoices',
'description': """
Manage goods requirement by Purchase Orders easily
==================================================
Purchase ma... |
import xbmc
from common import *
try:
from subprocess import check_output
from subprocess import call
except:
log('subprocess import error')
class ShellHandlerApt:
_pwd = ""
def __init__(self, usesudo=False):
self.sudo = usesudo
installed, candidate = self._check_versions("xbmc"... |
"""The Extended Volumes API extension."""
from nova.api.openstack import api_version_request
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import objects
from nova.policies import extended_volumes as ev_policies
ALIAS = "os-extended-volumes"
class ExtendedVolumesController(w... |
"""
Some utility functions to deal with mapping Amazon DynamoDB types to
Python types and vice-versa.
"""
import base64
from decimal import (Decimal, DecimalException, Context,
Clamped, Overflow, Inexact, Underflow, Rounded)
from collections import Mapping
from boto.dynamodb.exceptions import Dynam... |
# -*- coding: utf-8 -*-
import random
from ..internal.MultiHoster import MultiHoster
def random_with_n_digits(n):
rand = "0."
not_zero = 0
for i in range(1, n + 1):
r = random.randint(0, 9)
if(r > 0):
not_zero += 1
rand += str(r)
if not_zero > 0:
return r... |
import dateutil.parser
from distutils.version import StrictVersion
import docker
import json
import os
import threading
import time
import sys
def _c(c):
"""A helper method for representing a container in messages. If the given
argument is a string, it is assumed to be the container's ID and only the
firs... |
# Django settings for demo_project project.
import os
import sys
PROJECT_DIR = os.getcwd()
PYTHON_BIN = os.path.dirname(sys.executable)
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Shabda Raaj', '<EMAIL>'),
('Bala Subrahmanyam Varanasi', '<EMAIL>')
)
MANAGERS = ADMINS
DATABASES = {
'default': {
... |
from numpy import *
"""
A series of functions to calculate thermodynamic variables
compiled by Brett Basarab
Colorado State University
bbasarab [at] atmos.colostate.edu
last updated April 2015
Unless otherwise indicated, most of these functions were written
by Thomas Chubb and downloaded as part of a free python ske... |
import logging
import os
import subprocess
import warnings
from pyvivado import task, config
logger = logging.getLogger(__name__)
class VivadoTask(task.Task):
'''
A python wrapper to keep track of a spawned Vivado process.
'''
# How to log different kinds of Vivado messages.
MESSAGE_MAPPING = {... |
"""
Synchronization primitives:
- reader-writer lock (preference to writers)
(Contributed to Django by <EMAIL>)
"""
import contextlib
import threading
class RWLock(object):
"""
Classic implementation of reader-writer lock with preference to writers.
Readers can access a resource simultaneously.
... |
# Import data from SIDER
# Current url for latest: ftp://xi.embl.de/SIDER/latest/
from __future__ import print_function
from ftplib import FTP
import gzip
import os
import csv
import json
source_domain = 'xi.embl.de'
source_folder = '/SIDER/latest/'
temp_folder = './temp'
data_folder = './data'
scope_name = 'sider'
... |
"""
Copyright 2015 SYSTRAN Software, Inc. All rights reserved.
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.