content stringlengths 4 20k |
|---|
from unittest import TestCase
from wtforms.fields import TextField
from wtforms.ext.csrf import SecureForm
from wtforms.ext.csrf.session import SessionSecureForm
import datetime
import hashlib
import hmac
class DummyPostData(dict):
def getlist(self, key):
v = self[key]
if not isinstance(v, (list,... |
"""Simple plugin."""
import gettext
import glob
import hashlib
import os
from otopi import constants as otopicons
from otopi import filetransaction, plugin, util
import configparser
from ovirt_engine_setup import constants as osetupcons
from ovirt_setup_lib import dialog
def _(m):
return gettext.dgettext(mess... |
# coding: utf-8
import six
from unittest import TestCase
from dsfp.tools import BinDiff
__all__ = ['TestBinDiff', ]
class TestBinDiff(TestCase):
"""Tools tests """
maxDiff = None
diff_a = six.b('\x00\x01\x00\x04\x44\x53\x60\x34\x90\x88\x13\x08')
diff_b = six.b('\x01\x00\x00\x04\x42\x53\x61\x34\x93\x8... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.ipa import IPAClient
class SudoRuleIPAClient(IPACl... |
from gi.repository import Gtk, GdkPixbuf, GObject
from lutris import runners
from lutris import platforms
from lutris import pga
from lutris.gui.runnerinstalldialog import RunnerInstallDialog
from lutris.gui.config_dialogs import RunnerConfigDialog
from lutris.gui.runnersdialog import RunnersDialog
from lutris.gui.wid... |
"""Logging control and utilities.
Control of logging for SA can be performed from the regular python logging
module. The regular dotted module namespace is used, starting at
'sqlalchemy'. For class-level logging, the class name is appended.
The "echo" keyword parameter, available on SQLA :class:`.Engine`
and :class... |
from test import test_support
import unittest
import select
import os
import sys
class SelectTestCase(unittest.TestCase):
class Nope:
pass
class Almost:
def fileno(self):
return 'fileno'
def test_error_conditions(self):
self.assertRaises(TypeError, select.select, 1, 2... |
"""
Auto-generates PXD files from annotated C++ headers.
"""
import re
import os
from pygments.token import Token
from pygments.lexers import get_lexer_for_filename
class ParserError(Exception):
"""
Represents a fatal parsing error in PXDGenerator.
"""
def __init__(self, filename, lineno, message):
... |
from msrest.serialization import Model
class TimeWindow(Model):
"""A specific date-time for the profile.
All required parameters must be populated in order to send to Azure.
:param time_zone: the timezone of the start and end times for the profile.
Some examples of valid timezones are: Dateline Sta... |
# -*- coding: utf-8 -*-
"""
python -m scripts/Online_PassiveAggressive_countmeansketch LMdata 3 1 a ODDST 0.01
Created on Fri Mar 13 13:02:41 2015
Copyright 2015 Nicolo' Navarin
This file is part of scikit-learn-graph.
scikit-learn-graph is free software: you can redistribute it and/or modify
it under the terms... |
from gi.repository import GObject
from gi.repository import Peas
from gi.repository import RB
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import Gio
from gi.repository import PeasGtk
import rb
class RatingFiltersPlugin (GObject.Object, Peas.Activatable):
'''
Main class for ... |
"""Tests for Categorical distribution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_u... |
#!/usr/bin/env python
import sys
import numpy as np
from operator import itemgetter, attrgetter
import Image
from math import *
try:
sys.argv[1]
except NameError:
startingpoint = 'Missing an arg'
else:
startingpoint = sys.argv[1]
i = 0
MegaLine = []
Tableau = []
BaseData = []
print BaseData
print "\n\... |
"""This file implements the chaffing algorithm.
Winnowing and chaffing is a technique for enhancing privacy without requiring
strong encryption. In short, the technique takes a set of authenticated
message blocks (the wheat) and adds a number of chaff blocks which have
randomly chosen data and MAC fields. This means... |
"""Python API for composing notebook elements
The Python representation of a notebook is a nested structure of
dictionary subclasses that support attribute access
(ipython_genutils.ipstruct.Struct). The functions in this module are merely
helpers to build the structs in the right form.
"""
# Copyright (c) IPython Dev... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from mock import call, MagicMock
import pytest
from ansible.errors import AnsibleConnectionFailure
from ansible.plugins.terminal import junos
@pytest.fixture
def junos_terminal():
mock_connection = MagicMock()
return jun... |
"""
SET scalars values
++++++++++++++++++
Send SNMP SET request using the following options:
* with SNMPv1, community 'public'
* over IPv4/UDP
* to an Agent at demo.snmplabs.com:161
* setting three var-bindings to new values
Please note, that in this example MIB lookup is only used
for the second var-bindins. For th... |
"""
Run:
python3 zipsrc.py
This will create a file `source.zip` which you can upload to Coursys (courses.cs.sfu.ca) as your source code submission.
To customize the files used by default, run:
python3 zipsrc.py -h
"""
import sys, os, optparse, shutil, iocollect
if __name__ == '__main__':
optparser = op... |
from osv import fields, osv
import time
from datetime import datetime
import pooler
import netsvc
import sys
import os
from osv import osv,fields
from mx.DateTime import *
from tools.translate import _
import logging
import netsvc
logger = logging.getLogger('server')
class med_question_pack(osv.osv):
_name="med.qu... |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.absp... |
import product
import stock
import purchase
import invoice
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/env python
import logging
import warnings
from twisted.application.service import MultiService
from twisted.internet.endpoints import clientFromString
from zope.interface import implementer
from twistedpusher.connection import Connection
from twistedpusher import channel, websocket
from twistedpusher.event... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'VerificationCheckpoint'
db.create_table('verify_student_v... |
"""Self-test suite for Crypto.Hash.MD4"""
__revision__ = "$Id$"
from Crypto.Util.py3compat import *
# This is a list of (expected_result, input[, description]) tuples.
test_data = [
# Test vectors from RFC 1320
('31d6cfe0d16ae931b73c59d7e0c089c0', '', "'' (empty string)"),
('bde52cb31de33e46245e05fbdbd6f... |
import mock
import unittest
from hpOneView.connection import connection
from hpOneView.resources.resource import ResourceClient
from hpOneView.resources.servers.id_pools import IdPools
class TestIdPools(unittest.TestCase):
resource_info = {'type': 'Range',
'name': 'No name'}
example_uri ... |
# This test module covers support in various parts of the standard library
# for working with modules located inside zipfiles
# The tests are centralised in this fashion to make it easy to drop them
# if a platform doesn't support zipimport
import test.test_support
import os
import os.path
import sys
import textwrap
im... |
{
"name" : "Slovenian - Accounting",
"version" : "1.2",
"author" : "Mentis d.o.o.",
"website" : "http://www.mentis.si",
"category" : "Localization/Account Charts",
"description" : " ",
"depends" : ["account", "base_iban", "base_vat", "account_chart", "account_cancel"],
"description" : "K... |
import datetime
import random
class SimpleScheduler(object):
def __init__(self, setting_dict, right_now=None):
self.frequency = setting_dict.get('check_freq', 1) # how often the action occurs (Never, Daily, Weekly, Monthly)
self.specific_time = setting_dict.get('check_time', 0) # whether the a... |
import os
import sys
import webapp2
import jinja2
import codecs
import re
from google.appengine.ext import vendor
vendor.add('thirdparty')
import markdown
from jinja2 import Environment, meta
from bigrig.usermanager import UserManager
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(
... |
# test_getopt.py
# David Goodger <<EMAIL>> 2000-08-19
from test.test_support import verbose, run_doctest, run_unittest, EnvironmentVarGuard
import unittest
import getopt
sentinel = object()
class GetoptTests(unittest.TestCase):
def setUp(self):
self.env = EnvironmentVarGuard()
if "POSIXLY_CORREC... |
from setuptools import setup
import re
import os
import ConfigParser
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
config = ConfigParser.ConfigParser()
config.readfp(open('tryton.cfg'))
info = dict(config.items('tryton'))
for key in ('depends', 'extras_depend', 'xml'):
i... |
"""\
==========================
Pure Transformer component
==========================
This component applies a function specified at its creation to messages
received (a filter). If the function returns None, no message is sent,
otherwise the result of the function is sent to "outbox".
Example Usage
-------------
To... |
"""Provide toplogical sorting (i.e. dependency sorting) functions.
The topsort function is based on code posted on Usenet by Tim Peters.
Modifications:
- added doctests
- changed some bits to use current Python idioms
(listcomp instead of filter, +=/-=, inherit from Exception)
- added a topsort_levels version that ... |
#!/usr/bin/env python
# encoding: utf-8
"""
tests.py
TODO: These tests need to be updated to support the Python 2.7 runtime
"""
import os
import unittest
from google.appengine.ext import testbed
from application import app
class DemoTestCase(unittest.TestCase):
def setUp(self):
# Flask apps testing. S... |
"""
pgoapi - Pokemon Go API
Copyright (c) 2016 tjado <https://github.com/tejado>
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 rights
to use... |
"""
Support for Parastation MPI as toolchain MPI library.
@author: Kenneth Hoste (Ghent University)
"""
from easybuild.toolchains.mpi.mpich import Mpich
class Psmpi(Mpich):
"""Parastation MPI class"""
MPI_MODULE_NAME = ['psmpi']
def _set_mpi_compiler_variables(self):
"""Set the MPICH_{CC, CXX, ... |
#!/usr/bin/env python
import argparse
import json
import sys
import chainer
import numpy
import nets
import nlp_utils
def setup_model(device, model_setup):
sys.stderr.write(json.dumps(args.__dict__, indent=2) + '\n')
setup = json.load(open(model_setup))
sys.stderr.write(json.dumps(setup, indent=2) + '\n... |
from __future__ import absolute_import
import sys
from collections import Iterable, Mapping
from kombu.five import string_t
__all__ = ['lazy', 'maybe_evaluate', 'is_list', 'maybe_list']
class lazy(object):
"""Holds lazy evaluation.
Evaluated when called or if the :meth:`evaluate` method is called.
Th... |
# -*- coding: utf-8 -*-
from kallithea.model.db import User, UserFollowing, Repository, UserApiKeys
from kallithea.tests import *
from kallithea.tests.fixture import Fixture
from kallithea.lib import helpers as h
from kallithea.model.user import UserModel
from kallithea.model.meta import Session
fixture = Fixture()
... |
"""
Unit test for the template extensions.
"""
from flask import url_for
from invenio.ext.template import render_template_to_string
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
from invenio.testsuite import unittest
class TemplateTest(InvenioTestCase):
"""
jinja2utils TestS... |
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.univention_umc import (
umc_module_for_add,
umc_module_for_edit,
ldap_search,
base_dn,
)
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
def... |
"""
Harmonic Convolutions Lite
A simplified API for harmomin_network_ops
"""
import numpy as np
import tensorflow as tf
from harmonic_network_ops import *
def conv2d(x, n_channels, ksize, strides=(1,1,1,1), padding='VALID', phase=True,
max_order=1, stddev=0.4, n_rings=None, name='conv2d'):
"""Harm... |
from openerp.addons.web.controllers.main import DataSet
from openerp.tools.translate import _
from openerp import http
from openerp.http import request
class DataSetCustom(DataSet):
def _extend_name(self, model, records):
cr, uid, context = request.cr, request.uid, request.context
Model = request.... |
from __future__ import absolute_import, print_function
import random
import socket
import string
import sys
import time
import unittest2 as unittest
import warnings
import weakref
from nose import SkipTest
from kombu import Connection
from kombu import Exchange, Queue
from kombu.five import range
from kombu.tests.ca... |
data = (
'[?]', # 0x00
'e', # 0x01
'aai', # 0x02
'i', # 0x03
'ii', # 0x04
'o', # 0x05
'oo', # 0x06
'oo', # 0x07
'ee', # 0x08
'i', # 0x09
'a', # 0x0a
'aa', # 0x0b
'we', # 0x0c
'we', # 0x0d
'wi', # 0x0e
'wi', # 0x0f
'wii', # 0x10
'wii', # 0x11
'wo', # 0x12
'wo', ... |
from commands import Command, register_command
from HTMLReport import HTMLReport
from Config import Config
import os
import tempfile
class CreateReport(Command):
name = 'create-report'
usage_args = '[ options ... ] tests '
description = 'Create report of test results'
def __init__(self):
Comm... |
import copy
import random
from scipy.optimize import curve_fit
from scipy.special import zetac
def zipf_rank_freq(x, a):
return 1./((x**a)*(1.+zetac(a)))
def fit_zipf(distrib):
distrib_2 = copy.deepcopy(distrib)
distrib_2.sort(reverse=True)
exponent,zipferror = curve_fit(zipf_rank_freq, xdata=range(1,len(distri... |
"""The tests for the mFi switch platform."""
import unittest
import unittest.mock as mock
import homeassistant.components.switch as switch
import homeassistant.components.switch.mfi as mfi
from tests.components.sensor import test_mfi as test_mfi_sensor
from tests.common import get_test_home_assistant
class TestMfiS... |
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_grovevdiv as upmGrovevdiv
def main():
# Instantiate a Grove Voltage Divider sensor on analog pin A0
myVoltageDivider = upmGrovevdiv.GroveVDiv(0)
## Exit handlers ##
# This stops python from printing a stacktra... |
import re
import copy
from pygments.lexer import DelegatingLexer
from pygments.lexers.web import PhpLexer, HtmlLexer
__all__ = ['CodeIgniterLexer']
class CodeIgniterLexer(DelegatingLexer):
"""
Handles HTML, PHP, JavaScript, and CSS is highlighted
PHP is highlighted with the "startline" option
"""
... |
'''
Page is an object used for displaying a standard page
'''
import os
import jinja2
import os
import sys
import nav
from flask.ext.pymongo import PyMongo
# Setup the JINJA envronment
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..... |
"""
Extra HTML Widget classes
"""
from __future__ import unicode_literals
import datetime
import re
from django.conf import settings
from django.forms.widgets import Select, Widget
from django.utils import datetime_safe, six
from django.utils.dates import MONTHS
from django.utils.encoding import force_str
from django... |
{
'name': 'Project Order',
'version': '1.0',
'category': 'Projects & Services',
'sequence': 14,
'summary': '',
'description': """
Project Order
===================
Change default tasks order to the following criteria:
"priority desc, sequence, date_deadline, duration, create_date desc"
"... |
from builtins import object
import logging
import sys
from datetime import datetime, timedelta
from django.core.paginator import Paginator
from desktop.lib.exceptions_renderable import PopupException
from desktop.lib.rest.http_client import RestException
from hadoop.conf import YARN_CLUSTERS
from hadoop.cluster impo... |
import widget
from browser import html, doc
class Dialog(widget.DraggableWidget):
def __init__(self, id=None):
self._div_shell=html.DIV(
Class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable",
style={'position': 'absolute', 'height': 'auto', 'width': '3... |
# compute arctangent table for CORDIC computations in fttrigon.c
import sys, math
#units = 64*65536.0 # don't change !!
units = 256
scale = units/math.pi
shrink = 1.0
comma = ""
def calc_val( x ):
global units, shrink
angle = math.atan(x)
shrink = shrink * math.cos(angle)
return angle/math.pi *... |
#!/usr/bin/env python
'''
Event class and enums for Mission Editor
Michael Day
June 2014
'''
#MissionEditorEvents come FROM the GUI (with a few exceptions where the Mission Editor Module sends a message to itself, e.g., MEE_TIME_TO_QUIT)
#MissionEditorGUIEvents go TO the GUI
#enum for MissionEditorEvent types
MEE_READ_... |
"""## Communicating Between Processes with MPI
TensorFlow natively provides inter-device communication through send and
receive ops and inter-node communication through Distributed TensorFlow, based
on the same send and receive abstractions. On HPC clusters where Infiniband or
other high-speed node interconnects are a... |
from common_fixtures import * # NOQA
TEST_HANDLER_PREFIX = 'test-handler-'
@pytest.fixture(scope='module', autouse=True)
def tear_down(request, admin_user_client):
request.addfinalizer(lambda: _disable_test_handlers(admin_user_client))
def _get_extension(admin_client, extension_point_name, impl_name,
... |
import contextlib
import datetime
import mock
from oslo_config import cfg
from oslo_utils import importutils
from oslo_utils import timeutils
import testscenarios
from neutron.common import constants
from neutron.common import topics
from neutron import context
from neutron.db import agents_db
from neutron.db import ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Export von AggregateSet-Zeitreihen aus NASTY-Tabellen
# erstellt von Gerhard Muenz, August 2008
import MySQLdb, getopt, os, sys, string, calendar, time
def query_metrics(c, starttime, endtime, interval, addr, mask, port, proto, nasty):
def ip2int(adresse):
#... |
"""Abstract base classes related to import."""
from . import _bootstrap
from . import machinery
try:
import _frozen_importlib
except ImportError as exc:
if exc.name != '_frozen_importlib':
raise
_frozen_importlib = None
import abc
import imp
import marshal
import sys
import tokenize
import warnings
... |
from flask import render_template
from invenio_access.control import acc_get_user_email
from invenio_workflows.definitions import WorkflowBase
from invenio_workflows.tasks.logic_tasks import (
workflow_else,
workflow_if,
)
from invenio_workflows.tasks.marcxml_tasks import (
was_approved
)
from invenio_work... |
import os
from prospector.message import Location, Message
from prospector.tools.base import ToolBase
from pyroma import projectdata, ratings
PYROMA_CODES = {
ratings.Name: 'PYR01',
ratings.Version: 'PYR02',
ratings.VersionIsString: 'PYR03',
ratings.PEP386Version: 'PYR04',
ratings.Description: 'PY... |
import io
import os
import setuptools
name = "google-cloud-iam"
description = "IAM Service Account Credentials API client library"
version = "0.2.1"
# Should be one of:
# 'Development Status :: 3 - Alpha'
# 'Development Status :: 4 - Beta'
# 'Development Status :: 5 - Production/Stable'
release_status = "Development ... |
'''OpenGL extension NV.gpu_program4
This module customises the behaviour of the
OpenGL.raw.GL.NV.gpu_program4 to provide a more
Python-friendly API
Overview (from the spec)
This specification documents the common instruction set and basic
functionality provided by NVIDIA's 4th generation of assembly instruction... |
"""Tools for representing MongoDB internal Timestamps.
"""
import calendar
import datetime
from bson.py3compat import integer_types
from bson.tz_util import utc
UPPERBOUND = 4294967296
class Timestamp(object):
"""MongoDB internal timestamps used in the opLog.
"""
_type_marker = 17
def __init__(se... |
import os
import pytest
import simplejson as json
from django.template import Context, Template
from tests import test_utils
from treeherder.client import TreeherderJobCollection
base_dir = os.path.dirname(__file__)
@pytest.fixture
def pending_jobs():
"""returns a list of buildapi pending jobs"""
with open... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_uti... |
import urllib
from authorize import gen_xml as xml, util, base, responses as resp
from authorize.gen_xml import CREDIT_CARD, ECHECK, AuthorizeSystemError
from authorize.gen_xml import AUTH_CAPTURE, AUTH_ONLY, CAPTURE_ONLY
from authorize.gen_xml import CREDIT, PRIOR_AUTH_CAPTURE, VOID
class Api(base.BaseApi):
"""... |
from oslo_versionedobjects import fields
from cinder import db
from cinder import exception
from cinder.i18n import _
from cinder import objects
from cinder.objects import base
from cinder.objects import fields as c_fields
from cinder import utils
@base.CinderObjectRegistry.register
class Cluster(base.CinderPersiste... |
"""distutils.command.bdist
Implements the Distutils 'bdist' command (create a built [binary]
distribution)."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: bdist.py 37828 2004-11-10 22:23:15Z loewis $"
import os, string
from types import *
from distutils.core import Command
from dis... |
#!/usr/bin/env python
theta = {
'left': {'min': 300, 'max': 40},
'right': {'min': 120, 'max': 220},
'shift': 35
}
class Control:
def __init__(self, config_dict):
self.config_dict = config_dict
def fx(self, id, angle, speed, speed_ref):
dth = (speed/speed_ref)*theta['shift']... |
import numpy as np
import scipy.sparse
__all__ = ['save_npz', 'load_npz']
# Make loading safe vs. malicious input
PICKLE_KWARGS = dict(allow_pickle=False)
def save_npz(file, matrix, compressed=True):
""" Save a sparse matrix to a file using ``.npz`` format.
Parameters
----------
file : str or file... |
from stevedore.tests import utils
from stevedore import dispatch
def check_dispatch(ep, *args, **kwds):
return ep.name == 't2'
class TestDispatch(utils.TestCase):
def check_dispatch(ep, *args, **kwds):
return ep.name == 't2'
def test_dispatch(self):
def invoke(ep, *args, **kwds):
... |
from __future__ import division, absolute_import, print_function
import numpy as np
from .numeric import uint8, ndarray, dtype
from numpy.compat import long, basestring
__all__ = ['memmap']
dtypedescr = dtype
valid_filemodes = ["r", "c", "r+", "w+"]
writeable_filemodes = ["r+", "w+"]
mode_equivalents = {
"reado... |
import unittest
import os
import locale
import logging
import pdf
from tempfile import mkdtemp
from pelican import Pelican
from pelican.readers import MarkdownReader
from pelican.settings import read_settings
from shutil import rmtree
CUR_DIR = os.path.dirname(__file__)
class TestPdfGeneration(unittest.TestCase):
... |
""" A code generator (needed by ModToolAdd) """
from templates import Templates
import Cheetah.Template
from util_functions import str_to_fancyc_comment
from util_functions import str_to_python_comment
from util_functions import strip_default_values
from util_functions import strip_arg_types
from util_functions import... |
import pandas as pd
import xgboost as xgb1
from xgboost import XGBClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import OneHotEncoder
from Classification import Utility
import pickle
import time
from sklearn.preprocessing import StandardScaler
# Function to change labels of ... |
"""
The auto installer
"""
import os, sys, pwd, grp, time, stat, ConfigParser, shutil
from subprocess import * # breaking habit of a lifetime !
import core.init_core as init_core
import core.daemon_whip as daemon_whip
class exit_(Exception): pass
DEP_TEXT = """
*****************************************************... |
from __future__ import print_function
import socket
import sys
# windows does not have termios...
try:
import termios
import tty
has_termios = True
except ImportError:
has_termios = False
def interactive_shell(chan):
if has_termios:
posix_shell(chan)
else:
windows_shell(chan)... |
"""Hook scripts handling"""
import os.path
import subprocess
from weblate.trans.util import get_clean_env
def get_script_name(name):
'''
Returns script name from string possibly containing full path and
parameters.
'''
return os.path.basename(name).split()[0]
def run_post_push_script(component)... |
"""Support for the YesssSMS platform."""
import logging
import voluptuous as vol
from homeassistant.const import CONF_PASSWORD, CONF_RECIPIENT, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
from homeassistant.components.notify import (PLATFORM_SCHEMA,
... |
from __future__ import print_function
from itertools import product
import os
import os.path as op
import warnings
from nose.tools import assert_raises, assert_true
import numpy as np
from numpy.testing import (assert_equal, assert_allclose)
from mne.datasets import testing
from mne.io import read_raw_fif, read_raw_... |
"""Matrix factorization with Sparse PCA"""
# License: BSD 3 clause
import numpy as np
from ..utils import check_random_state, check_array
from ..utils.validation import check_is_fitted
from ..linear_model import ridge_regression
from ..base import BaseEstimator, TransformerMixin
from .dict_learning import dict_learni... |
"""
Discussion Application Configuration
Signal handlers are connected here.
"""
from django.apps import AppConfig
from openedx.core.constants import COURSE_ID_PATTERN
from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType, PluginURLs, PluginSettings
class DiscussionConfig(AppConfig):
... |
'''Unit tests for the 'grit transl2tc' tool.'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))
import StringIO
import unittest
from grit.tool import transl2tc
from grit import grd_reader
from grit import util
def MakeOptions():
from grit impor... |
from __future__ import print_function, absolute_import
VCS_URLS = (
'https://',
'http://',
'git://',
'git+git://',
'hg+https://',
'hg+http://',
'git+https://',
'git+http://',
'svn+https://',
'svn+http://',
'svn://',
)
def parse_repo_url(repo_url):
"""
Validate a r... |
# -*- coding: utf-8 -*-
import unittest
import boto
TABLE_NAME1 = 'Table-1'
TABLE_NAME2 = 'Table-2'
class TestListTables(unittest.TestCase):
def setUp(self):
from ddbmock.database.db import dynamodb
from ddbmock.database.table import Table
from ddbmock.database.key import PrimaryKey
... |
""" This module implements the DecompressionMiddleware which tries to recognise
and extract the potentially compressed responses that may arrive.
"""
import bz2
import gzip
import zipfile
import tarfile
import logging
from tempfile import mktemp
import six
try:
from cStringIO import StringIO as BytesIO
except Im... |
from airflow.hooks.base_hook import BaseHook
from azure.datalake.store import core, lib, multithread
class AzureDataLakeHook(BaseHook):
"""
Interacts with Azure Data Lake.
Client ID and client secret should be in user and password parameters.
Tenant and account name should be extra field as
{"ten... |
#!/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 powerdns import... |
import logging
_log = logging.getLogger(__name__)
import sys, os, errno
from .conf import getconf
def which(file):
for path in os.environ["PATH"].split(os.pathsep):
if os.path.exists(os.path.join(path, file)):
return os.path.join(path, file)
return None
def write_service(F, conf, sect, us... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2008, appengine-utilities project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
... |
import os
import os.path
import concurrent.futures
import threading
class AppDaemon:
def __init__(self, logging, loop, **kwargs):
#
# Import various AppDaemon bits and pieces now to avoid circular import
#
import appdaemon.utils as utils
import appdaemon.thread_async as a... |
import sys
import getopt
from socket import *
try:
from xbmc.xbmcclient import *
except:
sys.path.append('../../lib/python')
from xbmcclient import *
def usage():
print "xbmc-send [OPTION] --action=ACTION"
print 'Example'
print '\txbmc-send --host=192.168.0.1 --port=9777 --action="XBMC.Quit"'
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
""" gtk textbuffer with undo functionality """
# Copyright (C) 2009 Florian Heinle
# Some modifications by Peter Andrews, 2012 and 2013
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publi... |
from .base import BaseManager
class SessionListNotRetrieved(Exception):
"""Session list has not been retrieved yet"""
class DirectorySessionManager(BaseManager):
def __init__(self, organization_factory):
self.current_session_list = None
self.previous_session_list = None
super(Directo... |
"""The Multinomial distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops impor... |
from odf import opendocument
from odf.table import Table, TableRow, TableCell
from odf.text import P
class ODSReader(object):
# loads the file
def __init__(self, file=None, content=None, clonespannedcolumns=None):
if not content:
self.clonespannedcolumns = clonespannedcolumns
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.