content stringlengths 4 20k |
|---|
from nova import exception
from nova import flags
from nova.openstack.common import excutils
from nova.openstack.common import log as logging
from quantumclient import client
from quantumclient.v2_0 import client as clientv20
FLAGS = flags.FLAGS
LOG = logging.getLogger(__name__)
def _get_auth_token():
try:
... |
import copy
import functools
import imp
import io
import os
from collections import OrderedDict, defaultdict
from datetime import datetime
from mozlog import reader
from mozlog.formatters import JSONFormatter
from mozlog.handlers import BaseHandler, StreamHandler, LogLevelFilter
here = os.path.dirname(__file__)
local... |
"""Visual Studio solution file generation tool for SCons."""
import sys
def Solution(env, solution_name,
environments,
exclude_pattern=None,
extra_build_targets=None):
"""Builds an MSVS solution containing all projects underneath build/win.
Args:
solution_name: Name o... |
# -*- coding: utf-8 -*-
"""
pygments.filter
~~~~~~~~~~~~~~~
Module that implements the default filter.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
def apply_filters(stream, filters, lexer=None):
"""
Use this method to app... |
#-*- coding: utf8
'''
Implementation of some Machine Learning regression models. Basically, we
implement simple wrappers around the scikit-learn library which performs
the transformations and specific training models we need.
'''
from __future__ import division, print_function
from sklearn.base import clone
from skle... |
import gevent
import gevent.pywsgi
from gevent import Greenlet
import signal
import struct
import socket
import binascii
import time
import sys
import re
import random
import cStringIO
import copy
import re
import hashlib
import rpc
import ChainDb
import MemPool
import Log
from bitcoin.core import *
from bitcoin.seri... |
import csv
import pytest
from snakemakelib.sample.input import _parse_sampleinfo, _samples_from_input_files, initialize_input
from snakemakelib.sample.organization import config, illumina_scilife
@pytest.fixture(scope="module")
def illumina_scilife_files():
"""Input file names following naming conventions at SciL... |
from pyvirtualdisplay import Display
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait
from django.core.urlresolvers import reverse
from django.test.utils import override_set... |
"""A setup module for the GAPIC DLP API library.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup, find_packages
import sys
install_requires = [
'google-gax>=0.15.7, <0.16dev',
'oauth2client>=2.0.0, <4.0dev',
'proto-googl... |
from ..simstore.custom_json import JSONCodec
try:
import mdtraj as md
except ImportError:
md = None
HAS_MDTRAJ = False
else:
HAS_MDTRAJ = True
import pandas as pd
def _check_mdtraj():
if not HAS_MDTRAJ:
raise RuntimeError("Unable to import MDTraj.")
def traj_to_dict(obj):
return {'xy... |
# File: C (Python 2.4)
from otp.ai.AIBaseGlobal import *
from direct.distributed.ClockDelta import *
from direct.fsm import StateData
from direct.directnotify import DirectNotifyGlobal
import random
from direct.task import Task
from toontown.toonbase import ToontownGlobals
import CCharChatter
import CCharPaths
class ... |
import datetime
import decimal
import logging
import sys
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import render
from django.template import TemplateDoesNotExist
from django.urls import get_resolver
from dj... |
#!/usr/bin/python3
from __future__ import print_function
__author__ = '<EMAIL>'
import argparse
import os
import os.path as path
import tempfile
import subprocess
# constants
AR_CMD = ["ar", "x"]
XZ_CMD = ["xz", "-d"]
TAR_CMD = ["tar", "xf"]
DATA_FILE_NAME = "data.tar"
DESCRIPTION = "installs bracket manually from ... |
'''
urlresolver XBMC Addon
Copyright (C) 2016 Gujal
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 License, or
(at your option) any later version.
... |
import ConfigParser
import getopt
import json
import os
import requests
import sys
import time
# Returns login response's cookies
def log_in(username, password):
print "Preparing to take a dump by logging in..."
login_data = { "type": "login", "alias": username, "password": password }
login_resp = reques... |
import copy
from openstack_dashboard.test.test_data import utils
from saharaclient.api import cluster_templates
from saharaclient.api import clusters
from saharaclient.api import data_sources
from saharaclient.api import job_binaries
from saharaclient.api import job_executions
from saharaclient.api import job_types
f... |
"""TargetColumn abstract a single head in the model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.contrib.framework import deprecated
from tensorflow.contrib.losses.python.losses import loss_ops
from tensorflow.contrib.metr... |
from flask import Blueprint, request
from ...middlewares import auth_manager
from .middlewares import (s, validate)
from ...container import container
from ...models import Device
from structlog import get_logger
from .view_models import Device as DeviceViewModel
logger = get_logger()
devices = Blueprint('devices', _... |
"""
Required kwargs:
- 'symbolname'
Optional kwargs:
- 'enginestr' - SQLAlchemy engine string, pointing to a trump install.
- 'cache_first' - Bool
- 'croptime' - crop the time.
"""
stype = 'Trump'
renew = True
class Source(object):
def __init__(self, ses, **kwargs):
from trump import SymbolManager
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
las2demPro.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
---------------------
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cPickle as pickle
import csv
import numpy
import os
import wave
import librosa
import yaml
def load_audio(filename, mono=True, fs=44100):
"""Load audio file into numpy array
Supports 24-bit wav-format, and flac audio through librosa.
Parameters
... |
import os
import threading
import time
import traceback
try:
import Queue as queue
except ImportError:
import queue
try:
import win32api
except ImportError:
win32api = None
try:
import multiprocessing
except ImportError:
multiprocessing = None
import lit.Test
###
# Test Execution Implementat... |
data = (
'toels', # 0x00
'toelt', # 0x01
'toelp', # 0x02
'toelh', # 0x03
'toem', # 0x04
'toeb', # 0x05
'toebs', # 0x06
'toes', # 0x07
'toess', # 0x08
'toeng', # 0x09
'toej', # 0x0a
'toec', # 0x0b
'toek', # 0x0c
'toet', # 0x0d
'toep', # 0x0e
'toeh', # 0x0f
'tyo', # 0x10... |
import json
from django.conf import settings
from django.contrib.messages.storage.base import BaseStorage, Message
from django.http import SimpleCookie
from django.utils import six
from django.utils.crypto import constant_time_compare, salted_hmac
from django.utils.safestring import SafeData, mark_safe
class Message... |
"""Utility script to run chromoting test driver tests on the Chromoting bot."""
import argparse
from chromoting_test_utilities import GetJidFromHostLog
from chromoting_test_utilities import InitialiseTestMachineForLinux
from chromoting_test_utilities import MAX_RETRIES
from chromoting_test_utilities import PrintHostL... |
# -*- coding: utf-8 -*-
"""
sphinx.domains.javascript
~~~~~~~~~~~~~~~~~~~~~~~~~
The JavaScript domain.
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinx import addnodes
from sphinx.domains import Domain, ObjType
from sphinx.lo... |
from setuptools import setup, find_packages
__plugin_name__ = "Blocklist"
__author__ = "John Garland"
__author_email__ = "<EMAIL>"
__version__ = "1.2"
__url__ = "http://deluge-torrent.org"
__license__ = "GPLv3"
__description__ = "Download and import IP blocklists"
__long_description__ = __description__
__pkg_data__ = ... |
try:
try:
import ubinascii as binascii
except ImportError:
import binascii
except ImportError:
print("SKIP")
raise SystemExit
print(binascii.a2b_base64(b''))
print(binascii.a2b_base64(b'Zg=='))
print(binascii.a2b_base64(b'Zm8='))
print(binascii.a2b_base64(b'Zm9v'))
print(binascii.a2b_ba... |
#! /usr/bin/env python
import os
import sys
from barf import BARF
if __name__ == "__main__":
#
# Open file
#
try:
filename = os.path.abspath("../../samples/toy/arm/constraint2")
barf = BARF(filename)
except Exception as err:
print err
print "[-] Error opening file... |
#!/usr/bin/env python
'''
CREATED:2014-03-18 by Justin Salamon <<EMAIL>>
Compute melody extraction evaluation measures
Usage:
./melody_eval.py TRUTH.TXT PREDICTION.TXT
(CSV files also accepted)
For a detailed explanation of the measures please refer to:
J. Salamon, E. Gomez, D. P. W. Ellis and G. Richard, "Melody ... |
#! /usr/bin/env python
"""
Progress bar
===========
Written by Maxim Moinat and TR Maarleveld, Amsterdam, The Netherlands
E-mail: <EMAIL>
Last Change: February 18, 2015
"""
from __future__ import division, print_function, absolute_import
import sys,time
class Progress_bar():
"""
A progress bar for slow itera... |
from django.contrib.auth import models
from django.contrib.auth.management.commands import changepassword
from django.core.management import call_command
from django.test import TestCase
from django.utils.six import StringIO
class MultiDBChangepasswordManagementCommandTestCase(TestCase):
multi_db = True
def ... |
from tempest import test # noqa
from tempest_lib import exceptions as lib_exc # noqa
from manila_tempest_tests.tests.api import base
class SharesMetadataNegativeTest(base.BaseSharesTest):
@classmethod
def resource_setup(cls):
super(SharesMetadataNegativeTest, cls).resource_setup()
cls.shar... |
"""Entry point for running stress tests."""
import argparse
import Queue
import threading
from grpc.beta import implementations
from src.proto.grpc.testing import metrics_pb2
from src.proto.grpc.testing import test_pb2
from tests.interop import methods
from tests.qps import histogram
from tests.stress import metrics... |
#!/usr/bin/env python
import os
import shutil
import glob
import time
import sys
import subprocess
import string
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PKG_NAME = os.path.basename(SCRIPT_DIR)
PARAMETERS = None
#XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=... |
import pytest
from mpmath import *
from mpmath.calculus.optimization import Secant, Muller, Bisection, Illinois, \
Pegasus, Anderson, Ridder, ANewton, Newton, MNewton, MDNewton
def test_findroot():
# old tests, assuming secant
mp.dps = 15
assert findroot(lambda x: 4*x-3, mpf(5)).ae(0.75)
assert fin... |
from __future__ import unicode_literals
import logging
from django.conf import settings
from django.contrib.gis import gdal
from django.contrib.gis.geos import GEOSGeometry, GEOSException
from django.forms.widgets import Widget
from django.template import loader
from django.utils import six
from django.utils import t... |
#!/usr/bin/env python
# A linter to warn for ASSERT macros which are separated from their argument
# list by a space, which Clang's CPP barfs on
import sys
import logging
import os
import json
def setup_logging(logger):
"""
``arc lint`` makes it quite tricky to catch debug output from linters.
Log to a f... |
"""
=========================
Bayesian Ridge Regression
=========================
Computes a Bayesian Ridge Regression on a synthetic dataset.
See :ref:`bayesian_ridge_regression` for more information on the regressor.
Compared to the OLS (ordinary least squares) estimator, the coefficient
weights are slightly shift... |
from ..cw_controller import CWController
# Class for /company/configurations
from . import configuration
class ConfigurationsAPI(CWController):
def __init__(self):
self.module_url = 'company'
self.module = 'configurations'
self._class = configuration.Configuration
super()... |
# -*- encoding: utf-8 -*-
from abjad.tools.documentationtools.ReSTDirective import ReSTDirective
class ReSTOnlyDirective(ReSTDirective):
r'''A ReST `only` directive.
::
>>> only = documentationtools.ReSTOnlyDirective(argument='latex')
::
>>> heading = documentationtools.ReSTHeading(
... |
import json
import logging
class ProcessJsonData(object):
def __init__(self, current_result_json_dict, old_failing_results_list, old_full_results_list):
self._current_result_json_dict = current_result_json_dict
self._old_failing_results_list = old_failing_results_list
self._old_full_resul... |
"""
CDS Invenio DB dumper.
Usage: /opt/cds-invenio/bin/dbdump [options]
Command options:
-o, --output=DIR Output directory. [default=/opt/cds-invenio/var/log]
-n, --number=NUM Keep up to NUM previous dump files. [default=5]
Scheduling options:
-u, --user=USER User name to submit the task as, password... |
import unittest
from hamcrest import equal_to, assert_that, is_not, raises
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.command import Command
from selenium.webdriver.remote.webelement import WebElement
from pages.ui_component... |
from oslo_config import cfg
from oslo_log import helpers as log_helpers
from oslo_log import log as logging
from oslo_utils import importutils
import six
from neutron.agent.common import config
from neutron.agent.linux import interface
from neutron.agent.linux import iptables_manager
from neutron.common import constan... |
# -*- coding: utf-8 -*-
import re
import six
import xmlrpclib
from github import Github
from urlparse import urlparse
from fixtures.pytest_store import store
from cfme.utils import classproperty, conf, version
from cfme.utils.bz import Bugzilla
from cfme.utils.log import logger
class Blocker(object):
"""Base cla... |
from openerp import models, fields, api
class StockSelectUL(models.TransientModel):
_name = 'stock.select.ul'
_description = 'Select UL'
_rec_name = 'ul_id'
ul_id = fields.Many2one('product.ul', string='Logistic Unit')
# required=False, because we accept that it can be left empty
@api.multi
... |
from __future__ import unicode_literals
import frappe
def execute():
print "WARNING!!!! Email Settings not migrated. Please setup your email again."
# this will happen if you are migrating very old accounts
# comment out this line below and remember to create new Email Accounts
# for incoming and outgoing mails
... |
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
def main():
argument_spec = openstack_full_argument_spec(
image=dict(required=True),
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(argument_spec, **module_kwargs)
if not HAS_SHADE:
... |
import logging
from ipaserver.install import service
from ipaserver.install import sysupgrade
from ipaplatform.constants import constants
from ipaplatform.paths import paths
logger = logging.getLogger(__name__)
NTPD_OPTS_VAR = constants.NTPD_OPTS_VAR
NTPD_OPTS_QUOTE = constants.NTPD_OPTS_QUOTE
NTP_EXPOSED_IN_LDAP =... |
'''
VGDL example: a simplified variant of the classic space-invaders.
@author: Tom Schaul
'''
# the (initial) level as a block of characters
aliens_level = """
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
w w
w1 w
w000 w
w000 ... |
"""
homeassistant.components.thermostat
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to interact with thermostats.
"""
import logging
from homeassistant.helpers.entity_component import EntityComponent
import homeassistant.util as util
from homeassistant.helpers.entity import Entity
from homeassistant.h... |
# -*- coding: utf-8 -*-
import lib.sparksee as sparksee
import DatabaseNames
from sys import argv, stdout
import json
__author__ = "Matt Cook"
__version__ = "1.0.0"
__contributors__ = ["Matthew Cook", "Caleb Whitman"]
__email__ = "<EMAIL>"
# Tutorial here: http://www.sparsity-technologies.com/UserManual/API.html
# Do... |
'''
This module proxy all REST call to splunklib SDK, it handles proxy, certs etc
in this centralized location. All clients should use SplunkRestProxy to do REST
call instead of calling splunklib SDK directly in business logic code.
'''
import logging
import os
import traceback
import urllib2
from cStringIO import Str... |
# -*- coding: utf-8 -*-
"""Evolutionary models with neighbor-dependent substitutions module.
Defines evolutionary models of evolution. This class inherits most of
its functions from Porportion class of compte module.
Copyright 2007, Leonor Palmeira, <<EMAIL>>.
"""
__author__ = "Leonor Palmeira <<EMAIL>>"
__date__ = ... |
import mock
from oslo_config import cfg
from nova.api.metadata import password
from nova.api.openstack.compute.legacy_v2.contrib import server_password \
as server_password_v2
from nova.api.openstack.compute import server_password \
as server_password_v21
from nova import compute
from nova import exception
fr... |
from contextlib import contextmanager
import logging
import re
import sys
import warnings
from functools import wraps
from xml.dom.minidom import parseString, Node
from django.conf import settings, UserSettingsHolder
from django.core import mail
from django.core.signals import request_started
from django.db import res... |
from __future__ import unicode_literals
from sickbeard.image_cache import ImageCache
from sickrage.media.GenericMedia import GenericMedia
class ShowPoster(GenericMedia):
"""
Get the poster of a show
"""
def get_default_media_name(self):
return 'poster.png'
def get_media_path(self):
... |
#http://www.djangosnippets.org/snippets/955/
#GIF patch by DNN
import os
import Image
from django.template import Library
register = Library()
def thumbnail(file, size='50x50'):
# defining the size
x, y = [int(x) for x in size.split('x')]
# defining the filename and the miniature filename
filehead, f... |
import ROOT
from ROOT import TAttLine
Black = ROOT.kBlack
White = ROOT.kWhite
Red = ROOT.kRed+2
Blue = ROOT.kBlue+2
Green = ROOT.kGreen+2
Gray = ROOT.kGray+2
Brown = ROOT.kOrange+3
Orange = ROOT.kOrange+7
Yellow = ROOT.kYellow
Magenta = ROOT.kMagenta
Cyan = ROOT.kCyan
# Should set up several variations on this -- jus... |
# -----------------
# normal decorators
# -----------------
def decorator(func):
def wrapper(*args):
return func(1, *args)
return wrapper
@decorator
def decorated(a,b):
return a,b
exe = decorated(set, '')
#? set
exe[1]
#? int()
exe[0]
# more complicated with args/kwargs
def dec(func):
def ... |
try:
import jsonresults
from jsonresults import JsonResults
except ImportError:
print "ERROR: Add the TestResultServer, google_appengine and yaml/lib directories to your PYTHONPATH"
import unittest
JSON_RESULTS_TEMPLATE = (
'{"Webkit":{'
'"allFixableCount":[[TESTDATA_COUNT]],'
'"buildNumbers"... |
import fixtures
from oslo_utils.fixture import uuidsentinel as uuids
from nova.api.openstack.compute import server_topology
from nova.compute import vm_states
from nova import objects
from nova.policies import server_topology as policies
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_... |
from __future__ import print_function
# $example on$
from numpy import array
# $example off$
from pyspark import SparkContext
# $example on$
from pyspark.mllib.clustering import BisectingKMeans, BisectingKMeansModel
# $example off$
if __name__ == "__main__":
sc = SparkContext(appName="PythonBisectingKMeansExampl... |
'''
---------------------------------------- Masquerade ----------------------------------------
Allow course staff to see a student or staff view of courseware.
Which kind of view has been selected is stored in the session state.
'''
import logging
from django.conf import settings
from django.contrib.auth.decorators... |
from sympy import Piecewise, lambdify, Equality, Unequality, Sum, Mod
from sympy.abc import x, i, j, a, b, c, d
from sympy.printing.lambdarepr import NumPyPrinter
from sympy.utilities.pytest import skip
from sympy.external import import_module
np = import_module('numpy')
def test_numpy_piecewise_regression():
""... |
""" The Builder Pattern
Notes:
The Builder Pattern is particularly useful for creating complex objects made up of
several smaller objects. This pattern uses classes to represent both objects and their
builders (used to assemble objects). By having all child builders inherit from an
abstract builder, it is possible to... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: aci_tenant_span_dst_group
short_description: Manage SPAN des... |
"""
================
Confusion matrix
================
Example of confusion matrix usage to evaluate the quality
of the output of a classifier on the iris data set. The
diagonal elements represent the number of points for which
the predicted label is equal to the true label, while
off-diagonal elements are those that ... |
#!/usr/bin/env python
#
# test_codecmaps_kr.py
# Codec mapping tests for ROK encodings
#
from test import test_support
from test import test_multibytecodec_support
import unittest
class TestCP949Map(test_multibytecodec_support.TestBase_Mapping,
unittest.TestCase):
encoding = 'cp949'
mapfi... |
"""Test resurrection of mined transactions when the blockchain is re-organized."""
from test_framework.test_framework import PivxTestFramework
from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class MempoolCoinbaseTest(PivxTestFramework):
def set_test_params(self):
self... |
"""
metadata.forms
"""
import json
import copy
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.forms.utils import ErrorList
class UsersAllowedWidget(forms.SelectMultiple):
"""
A sub-widget of the PermissionsWidget. This should ... |
from __future__ import unicode_literals
from guessit import UnicodeMixin, s, u, base_text_type
from guessit.language import Language
from guessit.country import Country
import json
import datetime
import logging
log = logging.getLogger(__name__)
class Guess(UnicodeMixin, dict):
"""A Guess is a dictionary which h... |
{
'name': 'Germany SKR04 - Accounting',
'version': '3.0',
'author': 'openbig.org',
'website': 'http://www.openbig.org',
'category': 'Accounting/Localizations/Account Charts',
'description': """
Dieses Modul beinhaltet einen deutschen Kontenrahmen basierend auf dem SKR04.
=======================... |
"""
@authors: Sergei Garbuzov
@status: Development
@version: 1.1.0
"""
import time
import json
from pybvc.controller.controller import Controller
from pybvc.openflowdev.ofswitch import (OFSwitch,
FlowEntry,
Instruction,
... |
from oscar.core.loading import get_class, get_classes
OrderReportGenerator = get_class('order.reports', 'OrderReportGenerator')
ProductReportGenerator, UserReportGenerator \
= get_classes('analytics.reports', ['ProductReportGenerator',
'UserReportGenerator'])
OpenBasketRepor... |
"""benchmarks for the scipy.sparse.linalg._expm_multiply module"""
import math
import numpy as np
try:
import scipy.linalg
from scipy.sparse.linalg import expm_multiply
except ImportError:
pass
from .common import Benchmark
def random_sparse_csr(m, n, nnz_per_row):
# Copied from the scipy.sparse be... |
import csv
from os.path import dirname, join, exists
from random import shuffle
import resource
import time
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import precision_recall_fscore_support
from sklearn.svm import LinearSVC
from modules.cleaner import clean
##... |
import scrapy
from naver_crawler.items import Review
import re
import math
from urlparse import urlparse, parse_qs
class BlogSpider(scrapy.Spider):
name = "naver-blog"
# allowed_domains = ["cafeblog.search.naver.com", "blog.naver.com"]
# start_urls = [getPageURL(1)]
def __init__(self, results, search)... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import COIN, MAX_BLOCK_SIZE
class PrioritiseTransactionTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nod... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.network.avi.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ... |
#!/usr/bin/env python
"""
=============================================
Joint feature selection with multi-task Lasso
=============================================
The multi-task lasso allows to fit multiple regression problems
jointly enforcing the selected features to be the same across
tasks. This example simulates... |
from unittest.mock import call, Mock, patch
from alexa_client.refreshtoken import http_server, handlers
@patch.object(handlers.AmazonAlexaServiceLoginHandler, '__init__',
return_value=None)
@patch.object(http_server.AmazonLoginHttpServer, 'server_bind', Mock)
def test_http_server_passes_args(mock__init... |
from inspire.ext.formatter_jinja_filters.general import apply_template_on_array
def email_links(record):
"""
returns array of links to record emails
"""
return apply_template_on_array(record.get('email', []),
'format/record/field_templates/email.tpl')
def insti... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import time
import threading
from ansible.plugins.callback import CallbackBase
class Mem... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
from ansible.module_utils.six.moves import reduce
from ansible.module_utils.facts.hardware.base import Hardware, HardwareCollector
from ansible.module_utils.facts.timeout import TimeoutError, timeout
from ans... |
# -*- coding: utf-8 -*-
"""
Manages the credential information (netrc, passwords, etc).
"""
import getpass
import logging
import netrc
import os
import platform
class CredentialsError(BaseException):
"""
Class to be thrown if the credentials are not found.
"""
pass
def _getenv_or_empty(s):
""... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from .. import Rule
#-----------------------------------------------... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_parse_qs,
compat_urllib_parse,
compat_urllib_request,
)
from ..utils import (
determine_ext,
ExtractorError,
int_or_none,
)
class MetacafeIE(InfoExtractor):
_VALID_URL = r'ht... |
from __future__ import unicode_literals
import datetime
import re
from .common import InfoExtractor
from ..utils import (
str_to_int,
unified_strdate,
)
class MotherlessIE(InfoExtractor):
_VALID_URL = r'http://(?:www\.)?motherless\.com/(?:g/[a-z0-9_]+/)?(?P<id>[A-Z0-9]+)'
_TESTS = [
{
... |
"""Converts MNIST data to TFRecords file format with Example protos."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets import mnist
FLAGS = N... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
import re
import time
from requests import RequestException
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from... |
import ast
# y+-----------+
# 4| 1 |
# 3| 2 3 4 |
# 2| 5 6 7 8 9 |
# 1| A B C |
# 0| D |
# +-----------+
# 0 1 2 3 4 x
KEYPAD = {
'[2, 4]': '1',
'[1, 3]': '2',
'[2, 3]': '3',
'[3, 3]': '4',
'[0, 2]': '5',
'[1, 2]': '6',
'[2, 2]': '7',
'[3, 2]': '8',... |
#! /usr/bin/env python
import unittest
from redcap import Project, RedcapError
import semantic_version
skip_pd = False
try:
import pandas as pd
except ImportError:
skip_pd = True
class ProjectTests(unittest.TestCase):
"""docstring for ProjectTests"""
url = 'https://redcap.vanderbilt.edu/api/'
b... |
"""d3d9caps.h"""
from winapi import *
from d3d9types import *
D3DVS20CAPS = Flags(DWORD, [
"D3DVS20CAPS_PREDICATION",
])
D3DVSHADERCAPS2_0 = Struct("D3DVSHADERCAPS2_0", [
(D3DVS20CAPS, "Caps"),
(INT, "DynamicFlowControlDepth"),
(INT, "NumTemps"),
(INT, "StaticFlowControlDepth"),
])
D3DPS20CAPS =... |
"""
Models for course action state
If you make changes to this model, be sure to create an appropriate migration
file and check it in at the same time as your model changes. To do that,
1. Go to the edx-platform dir
2. ./manage.py cms schemamigration course_action_state --auto description_of_your_change
3. It adds th... |
from iwbt import get_db, get_session
from iwbt.models.rivers import (Area, Gauge, GaugeData, River,
Rapid, Section,
associate_user_favorites)
import random
class Busboy(object):
""" The busboy clears tables """
def __init__(self, app):
se... |
from unittest import mock
from neutron.tests.unit.db import test_db_base_plugin_v2
from neutron_lib import context
from neutronclient.common import exceptions
from neutronclient.v2_0 import client
from oslo_config import cfg
from gbpservice.network.neutronv2 import client as neutronclient
CONF = cfg.CONF
# NOTE: N... |
"""UnitTests for DoFn lifecycle and bundle methods"""
# pytype: skip-file
from __future__ import absolute_import
import unittest
from nose.plugins.attrib import attr
import apache_beam as beam
from apache_beam.testing.test_pipeline import TestPipeline
class CallSequenceEnforcingDoFn(beam.DoFn):
def __init__(se... |
import datetime
import decimal
import logging
import os
import shutil
from django.db.utils import DatabaseError
from google.appengine.api.datastore import Delete, Query
from google.appengine.api.datastore_errors import BadArgumentError, \
BadValueError
from google.appengine.api.datastore_types import Blob, Key, T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.