code stringlengths 1 199k |
|---|
import os
import shutil
import biicode.common.test
from biicode.common.utils import file_utils as common_file_utils
def load(filepath):
"""Return binary load of given test resource."""
abspath = file_path(filepath)
with open(abspath, "rb") as f:
return f.read()
def read(filepath):
"""Return syst... |
from azure.cli.core import AzCommandsLoader
import azure.cli.command_modules.sql._help # pylint: disable=unused-import
class SqlCommandsLoader(AzCommandsLoader):
def __init__(self, cli_ctx=None):
from azure.cli.core.commands import CliCommandType
from azure.cli.core.profiles import ResourceType
... |
import os.path
from pipeline.conf import settings
from pipeline.compilers import SubProcessCompiler
class LessCompiler(SubProcessCompiler):
output_extension = 'css'
def match_file(self, filename):
return filename.endswith('.less')
def compile_file(self, content, path):
command = '%s %s %s' %... |
"""
pipe2py.modules.pipeurlinput
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
http://pipes.yahoo.com/pipes/docs?doc=user_inputs#URL
"""
from pipe2py.lib import utils
def pipe_urlinput(context=None, _INPUT=None, conf=None, **kwargs):
"""An input that prompts the user for a url and yields it forever.
Not loopable.
... |
"""buildpkg.py -- Build OS X packages for Apple's Installer.app.
This is an experimental command-line tool for building packages to be
installed with the Mac OS X Installer.app application.
It is much inspired by Apple's GUI tool called PackageMaker.app, that
seems to be part of the OS X developer tools installed in th... |
from rsf.proj import *
from math import *
import fdmod,pcsutil,wefd
def data(par):
# ------------------------------------------------------------
Fetch('vp_marmousi-ii.segy',"marm2")
Fetch('vs_marmousi-ii.segy',"marm2")
Fetch('density_marmousi-ii.segy',"marm2")
# ------------------------------------... |
'''
:mod: Utils
Module that collects utility functions.
'''
import fnmatch
from DIRAC import gConfig, S_OK
from DIRAC.Core.Utilities import List
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
__RCSID__ = '$Id: $'
d... |
"""
URLResolver Addon for Kodi
Copyright (C) 2016 t0mm0, tknorris
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... |
from UserDict import DictMixin
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clear()
self.upd... |
from .base import Capability, BaseObject, StringField, FloatField
__all__ = ['IpLocation', 'CapGeolocIp']
class IpLocation(BaseObject):
"""
Represents the location of an IP address.
"""
city = StringField('City')
region = StringField('Region')
zipcode = StringField('Zip code')
coun... |
from __future__ import unicode_literals
from copy import deepcopy
from django import forms
from django.conf import settings
from django.core.urlresolvers import reverse
from django.forms.models import modelform_factory
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
... |
from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BlockStruct... |
"""fix description field in connection to be text
Revision ID: 64a7d6477aae
Revises: f5b5ec089444
Create Date: 2020-11-25 08:56:11.866607
"""
import sqlalchemy as sa # noqa
from alembic import op # noqa
revision = '64a7d6477aae'
down_revision = '61ec73d9401f'
branch_labels = None
depends_on = None
def upgrade():
... |
from tempest.lib.services.identity.v3 import endpoint_groups_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services import base
class TestEndPointGroupsClient(base.BaseServiceTest):
FAKE_CREATE_ENDPOINT_GROUP = {
"endpoint_group": {
"id": 1,
"name": "... |
from oslo_config import cfg
from neutron._i18n import _
allowed_address_pair_opts = [
#TODO(limao): use quota framework when it support quota for attributes
cfg.IntOpt('max_allowed_address_pair', default=10,
help=_("Maximum number of allowed address pairs")),
]
def register_allowed_address_pair_o... |
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from distutils import sysconfig
import os
import sys
import platform
flags = ''
inc = sysconfig.get_python_inc()
lib = sysconfig.get_config_var("LIBDIR")
if sys.platform == "darwin":
lib = os.path.di... |
"""
Example Airflow DAG that uses Google AutoML services.
"""
import os
from datetime import datetime
from airflow import models
from airflow.providers.google.cloud.hooks.automl import CloudAutoMLHook
from airflow.providers.google.cloud.operators.automl import (
AutoMLCreateDatasetOperator,
AutoMLDeleteDatasetO... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class InitializeOAuth(Choreography):
def __init__(self, temboo_session):
"""
Create a ... |
"""Tests for tensorflow.ops.gradients."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import warnings
import tensorflow.python.platform
import numpy as np
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from t... |
"""Test for the smhi weather entity."""
import asyncio
from datetime import datetime
import logging
from unittest.mock import AsyncMock, Mock, patch
from smhi.smhi_lib import APIURL_TEMPLATE, SmhiForecastException
from homeassistant.components.smhi import weather as weather_smhi
from homeassistant.components.smhi.const... |
import os
from requestbuilder import Arg
from euca2ools.commands.iam import IAMRequest, AS_ACCOUNT, arg_user
class CreateSigningCertificate(IAMRequest):
DESCRIPTION = '[Eucalyptus only] Create a new signing certificate'
ARGS = [arg_user(nargs='?', help='''user to create the signing
certific... |
from requestbuilder import Arg
from euca2ools.commands.ec2 import EC2Request
class DeleteNetworkAclEntry(EC2Request):
DESCRIPTION = 'Delete a network acl rule'
ARGS = [Arg('NetworkAclId', metavar='NACL', help='''ID of the
network ACL to delete an entry from (required)'''),
Arg('-n', ... |
from __future__ import unicode_literals
import json
from django.test import TestCase, override_settings
from django.utils.http import urlquote
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django.core.files.uploadedfile import SimpleUploadedFile
from django.template... |
from __future__ import absolute_import
input_name = '../examples/multi_physics/thermo_elasticity_ess.py'
output_name = 'test_thermo_elasticity_ess.vtk'
from tests_basic import TestInput
class Test(TestInput):
pass |
def get_attributes_display_map(variant, attributes):
display = {}
for attribute in attributes:
value = variant.get_attribute(attribute.pk)
if value:
choices = {a.pk: a for a in attribute.values.all()}
attr = choices.get(value)
if attr:
display[... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
os.environ['DJANGO_SETTINGS_MODULE'] = 'oauth_provider.runtests.settings'
from django.conf import settings
from django.test.utils import get_runner
from south.management.commands import patch_for_test_db_setup
def usage():
return... |
import taxcalc |
import cherrypy
from cherrypy.test import helper
class ETagTest(helper.CPWebCase):
def setup_server():
class Root:
def resource(self):
return "Oh wah ta goo Siam."
resource.exposed = True
def fail(self, code):
code = int(code)
... |
import re
import urlparse
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class SpeedyshareCom(SimpleHoster):
__name__ = "SpeedyshareCom"
__type__ = "hoster"
__version__ = "0.06"
__status__ = "testing"
__pattern__ = r'https?://(?:www\.)?(speedyshare\.com|speedy\.... |
{
'name': 'Online Members Directory',
'category': 'Website',
'summary': 'Publish your members directory',
'version': '1.0',
'description': """
Publish your members/association directory publicly.
""",
'depends': ['website_partner', 'website_google_map', 'association', 'website_sale'],
'd... |
from osv import fields, osv, orm
from tools.translate import _
from datetime import datetime
from datetime import timedelta
from tools.safe_eval import safe_eval
from tools import ustr
import pooler
import re
import time
import tools
def get_datetime(date_field):
'''Return a datetime from a date string or a datetim... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instructor_task', '0002_gradereportsetting'),
]
operations = [
migrations.AlterField(
model_name='instructortask',
name='task_input',
field=models.TextField(... |
from spack import *
class DhpmmF(MakefilePackage):
"""DHPMM_P:High-precision Matrix Multiplication with Faithful Rounding"""
homepage = "http://www.math.twcu.ac.jp/ogita/post-k/"
url = "http://www.math.twcu.ac.jp/ogita/post-k/software/DHPMM_F/DHPMM_F_alpha.tar.gz"
version('alpha', sha256='35321ecbc... |
from spack import *
class Minigan(Package):
"""miniGAN is a generative adversarial network code developed as part of the
Exascale Computing Project's (ECP) ExaLearn project at
Sandia National Laboratories."""
homepage = "https://github.com/SandiaMLMiniApps/miniGAN"
url = "https://github.com/San... |
import unittest
import sys
from PySide.QtCore import QObject, SIGNAL, QUrl
from PySide.QtWebKit import *
from PySide.QtNetwork import QNetworkRequest
from helper import adjust_filename, UsesQApplication
class TestWebFrame(UsesQApplication):
def load_finished(self, ok):
self.assert_(ok)
page = self.v... |
"""0.3.0 to 0.4.0
Revision ID: 0.3.0
Revises:
"""
revision = '0.4.0'
down_revision = '0.3.0'
branch_labels = None
depends_on = None
from alembic import op
from db_meta import *
from sqlalchemy.dialects import mysql
def upgrade():
"""
update schema&data
"""
bind = op.get_bind()
#alter column user.use... |
from __future__ import absolute_import, unicode_literals, division
import random
import string
import timeit
import os
import zipfile
import datrie
def words100k():
zip_name = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'words100k.txt.zip'
)
zf = zipfile.ZipFile(zip_name)
t... |
"""Tests for `tf.data.Dataset.from_sparse_tensor_slices()`."""
from absl.testing import parameterized
import numpy as np
from tensorflow.python.data.kernel_tests import checkpoint_test_base
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.pytho... |
"""Tests for workflow object exports."""
from os.path import abspath, dirname, join
from flask.json import dumps
from ggrc.app import app
from ggrc_workflows.models import Workflow
from integration.ggrc import TestCase
from integration.ggrc_workflows.generator import WorkflowsGenerator
THIS_ABS_PATH = abspath(dirname(_... |
"""Tests for training.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import json
import os
import random
import shutil
import tempfile
import time
import numpy as np
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python... |
"""Support for ISY994 lights."""
from typing import Callable, Dict
from pyisy.constants import ISY_VALUE_UNKNOWN
from homeassistant.components.light import (
DOMAIN as LIGHT,
SUPPORT_BRIGHTNESS,
LightEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.restore_state impo... |
import sys
from eventlet import event
from eventlet import greenthread
from keystone.openstack.common.gettextutils import _ # noqa
from keystone.openstack.common import log as logging
from keystone.openstack.common import timeutils
LOG = logging.getLogger(__name__)
class LoopingCallDone(Exception):
"""Exception to... |
import mock
from nose.tools import eq_, ok_, assert_raises
from funfactory.urlresolvers import reverse
from .base import ManageTestCase
class TestErrorTrigger(ManageTestCase):
def test_trigger_error(self):
url = reverse('manage:error_trigger')
response = self.client.get(url)
assert self.user... |
from django.http import HttpResponseNotAllowed, HttpResponseServerError
from django.utils import simplejson as json
from util import to_json_response
from util import to_dojo_data
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
def expe... |
from __future__ import print_function
import inspect
import numpy as np
import theano
from ..layers.advanced_activations import LeakyReLU, PReLU
from ..layers.core import Dense, Merge, Dropout, Activation, Reshape, Flatten, RepeatVector, Layer
from ..layers.core import ActivityRegularization, TimeDistributedDense, Auto... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2014 Alex Forencich
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 ri... |
import base64
from selenium.webdriver.remote.command import Command
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
from selenium.common.exceptions import WebDriverException
from .service import Service
from .options import Options
class WebDriver(RemoteWebDriver):
"""
Controls the ... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from past.builtins import basestring
import logging
from flexget import plugin
from flexget.event import event
from flexget.utils.log import log_once
try:
from flexget.p... |
"""
Test of the omero import control.
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import pytest
from path import path
import omero.clients
import uuid
from omero.cli import CLI, NonZeroReturnCode
plugin = __import__('omero.plugins.impor... |
import os,sys
import traceback
def enumToString(constants, enum, elem):
all = constants.all_values(enum)
for e in all.keys():
if str(elem) == str(all[e]):
return e
return "<unknown>"
def main(argv):
from vboxapi import VirtualBoxManager
# This is a VirtualBox COM/XPCOM API client... |
'''
Created on 18/2/2015
@author: PC06
'''
from flaskext.mysql import MySQL
from flask import Flask
class DBcon():
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
pass
def conexion(self):
mysql = MySQL()
app = Flask(__name__)
app.conf... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import pwd
import random
import re
import string
import sys
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six import iteritems
from ansible.module_utils.six.moves impo... |
from odoo import api, fields, models, _
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
task_id = fields.Many2one('project.task', 'Task', copy=False)
def _is_procurement_task(self):
return self.product_id.type == 'service' and self.product_id.track_service == 'task'
@api.mul... |
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\f")
buf.write("f\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.write("\4\b\t\b\4\t\t\t... |
def load_test_data(load_onto=None):
from openstack_dashboard.test.test_data import ceilometer_data
from openstack_dashboard.test.test_data import cinder_data
from openstack_dashboard.test.test_data import exceptions
from openstack_dashboard.test.test_data import glance_data
from openstack_dashboard.... |
from nose.tools import * # noqa: F403
from tests.base import AdminTestCase
from osf_tests.factories import NodeFactory, UserFactory
from osf.utils.permissions import ADMIN
from admin.nodes.serializers import serialize_simple_user_and_node_permissions, serialize_node
class TestNodeSerializers(AdminTestCase):
def te... |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("zerver", "0301_fix_unread_messages_in_deactivated_streams"),
]
operations = [
# We do Stream lookups case-insensitively with respect to the name, but we were missing
# the appropriate (realm_id... |
"""
SQLAlchemy models.
"""
import six
from sqlalchemy import Column, Integer
from sqlalchemy import DateTime
from sqlalchemy.orm import object_mapper
from solum.openstack.common.db.sqlalchemy import session as sa
from solum.openstack.common import timeutils
class ModelBase(object):
"""Base class for models."""
... |
""" msgfmt tool """
__revision__ = "src/engine/SCons/Tool/msgfmt.py 2014/03/02 14:18:15 garyo"
from SCons.Builder import BuilderBase
class _MOFileBuilder(BuilderBase):
""" The builder class for `MO` files.
The reason for this builder to exists and its purpose is quite simillar
as for `_POFileBuilder`. This time,... |
import sys
import inspect
from pylons import config
import logging
import zkpylons.lib.helpers as h
from pylons import request, response, session, tmpl_context as c
from zkpylons.lib.helpers import redirect_to
from pylons.util import class_name_from_module_name
from zkpylons.model import meta
from pylons.controllers.ut... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat import unittest
from units.mock.loader import DictDataLoader
from mock import MagicMock
from ansible.template import Templar
from ansible import errors
from ansible.playbook import conditional
class TestConditional... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: template
version_added: historical
options:
follow:
d... |
from __future__ import unicode_literals
from django import template
from temba.channels.views import get_channel_icon
register = template.Library()
@register.filter
def channel_icon(channel):
return get_channel_icon(channel.channel_type) |
from Acspy.Nc.CommonNC import CommonNC
from Acspy.Nc.Supplier import Supplier
import datacapEx
from datacapEx import ExecBlockProcessedEvent, DataCapturerId, ExecBlockStartedEvent, ScanStartedEvent
import asdmEX
s = Supplier('pyTest-NC')
name = 'DATACAP1'
s.publishEvent(name)
sessionId = asdmEX.IDLEntityR... |
from mock import *
from .gp_unittest import *
from gppylib.programs.gppkg import GpPkgProgram
import sys
class GpPkgProgramTestCase(GpTestCase):
def setUp(self):
self.mock_cmd = Mock()
self.mock_gppkg = Mock()
self.mock_uninstall_package = Mock()
self.apply_patches([
patc... |
from datetime import date
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'ch... |
""" DIRECT Nine DoF Manipulation Panel """
from direct.showbase.DirectObject import DirectObject
from direct.directtools.DirectGlobals import *
from direct.tkwidgets.AppShell import AppShell
from direct.tkwidgets.Dial import AngleDial
from direct.tkwidgets.Floater import Floater
from Tkinter import Button, Menubutton, ... |
'''tzinfo timezone information for America/Inuvik.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Inuvik(DstTzInfo):
'''America/Inuvik timezone definition. See datetime.tzinfo for details'''
zone = 'America/Inuvik'
_ut... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.cloudengine import ce_is_is_instance
from units.modules.network.cloudengine.ce_module import TestCloudEngineModule, load_fixture
from units.modules.utils import set_mo... |
from . import ir_model
from . import trgm_index |
#-*- coding: utf-8 -*-
from openerp.osv import fields, osv
class project_issue(osv.osv):
_inherit = 'project.issue'
_columns = {
'project_issue_solution_id': fields.many2one('project.issue.solution', 'Linked Solution'),
'issue_description': fields.html('Issue Description'),
'solution_de... |
"""Unique element dataset transformations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.data.python.ops import contrib_op_loader # pylint: disable=unused-import
from tensorflow.contrib.data.python.ops import gen_dataset_ops
from... |
from sqlalchemy import Float
from sqlalchemy import MetaData
from sqlalchemy import Table
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
meter = Table('meter', meta, autoload=True)
meter.c.counter_volume.alter(type=Float(53)) |
from ..broker import Broker
class DiscoverySettingBroker(Broker):
controller = "discovery_settings"
def index(self, **kwargs):
"""Lists the available discovery settings. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists, using th... |
import os
from optparse import OptionParser
from jinja2 import Template
HEADER = '!!AUTO-GENERATED!! Edit bin/crontab/crontab.tpl instead.'
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option('-w', '--webapp',
... |
from __future__ import division, unicode_literals
"""
Script to visualize the model coordination environments
"""
__author__ = "David Waroquiers"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "2.0"
__maintainer__ = "David Waroquiers"
__email__ = "david.waroquiers@gmail.com"
__date__ = "Feb 20, 2... |
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
try:
import sqlite3
except ImportError:
pass
import logging
from lib.core.convert import utf8encode
from lib.core.data import conf
from lib.core.data import logger
from lib.core.exception imp... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = u'''
---
module: bzr
author: "André Paramés (@andreparames)"
version_added: "1.1"
short_description: Deploy software (or files) from bzr branches
description:
- Manage I(... |
import Quartz
from AppKit import NSEvent, NSScreen
from .base import PyMouseMeta, PyMouseEventMeta
pressID = [None, Quartz.kCGEventLeftMouseDown,
Quartz.kCGEventRightMouseDown, Quartz.kCGEventOtherMouseDown]
releaseID = [None, Quartz.kCGEventLeftMouseUp,
Quartz.kCGEventRightMouseUp, Quartz.kCGEv... |
"""Gradients for operators defined in linalg_ops.py.
Useful reference for derivative formulas is
An extended collection of matrix derivative results for forward and reverse
mode algorithmic differentiation by Mike Giles:
http://eprints.maths.ox.ac.uk/1079/1/NA-08-01.pdf
A detailed derivation of formulas for backpropaga... |
"""Constants for the Aftership integration."""
from __future__ import annotations
from datetime import timedelta
from typing import Final
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
DOMAIN: Final = "aftership"
ATTRIBUTION: Final = "Information provided by AfterShip"
ATTR_TRACKINGS: Fin... |
"""Describe group states."""
from homeassistant.components.group import GroupIntegrationRegistry
from homeassistant.const import STATE_OK, STATE_PROBLEM
from homeassistant.core import HomeAssistant, callback
@callback
def async_describe_on_off_states(
hass: HomeAssistant, registry: GroupIntegrationRegistry
) -> Non... |
import operator
import unittest
import numpy
import six
from cupy import testing
@testing.gpu
class TestArrayElementwiseOp(unittest.TestCase):
_multiprocess_can_split_ = True
@testing.for_all_dtypes()
@testing.numpy_cupy_allclose()
def check_array_scalar_op(self, op, xp, dtype, swap=False):
a = ... |
from itertools import chain
from django.contrib.sites.models import Site
from django.core.urlresolvers import NoReverseMatch, reverse_lazy
from django.forms.widgets import Select, MultiWidget, TextInput
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translat... |
"""
Serializer for user API
"""
from rest_framework import serializers
from rest_framework.reverse import reverse
from django.template import defaultfilters
from courseware.access import has_access
from student.models import CourseEnrollment, User
from certificates.models import certificate_status_for_student, Certific... |
"""Downloads the necessary NLTK corpora for TextBlob.
Usage: ::
$ python -m textblob.download_corpora
If you only intend to use TextBlob's default models, you can use the "lite"
option: ::
$ python -m textblob.download_corpora lite
"""
import sys
import nltk
MIN_CORPORA = [
'brown', # Required for FastNPEx... |
from django.db import transaction
from denorm.db import base
class RandomBigInt(base.RandomBigInt):
def sql(self):
return '(9223372036854775806::INT8 * ((RANDOM()-0.5)*2.0) )::INT8'
class TriggerNestedSelect(base.TriggerNestedSelect):
def sql(self):
columns = self.columns
table = self.ta... |
"""BibFormat element - Prints brief HTML picture and links to resources
"""
__revision__ = "$Id$"
def format_element(bfo):
"""
Prints html image and link to photo resources.
"""
from invenio.config import CFG_SITE_URL, CFG_SITE_RECORD
resources = bfo.fields("8564_")
out = ""
for resource in ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.modules.cloud.amazon.aws_acm import pem_chain_split, chain_compare
from ansible.module_utils._text import to_bytes, to_text
from pprint import pprint
def test_chain_compare():
# The functions we're testing take modu... |
'''
Simple monitoring script to collect per process cpu percentage
and mem usage in bytes (vms or virt and rss)
usage:
cron-send-cpu-mem-stats process_name openshift.whatever.zabbix.key
or
cron-send-cpu-mem-stats 'something parameter more params' openshift.something.parameter.more.params
The script... |
def f(s):
s = s[::-1]
return s.swapcase()
result = f(f(f(f(f('abcdef'))))) # breakpoint |
"""
Secrets framework provides means of getting connection objects from various sources, e.g. the following:
* Environment variables
* Metastore database
* AWS SSM Parameter store
"""
__all__ = ['BaseSecretsBackend', 'DEFAULT_SECRETS_SEARCH_PATH']
from airflow.secrets.base_secrets import BaseSecretsBackend
... |
from buck import format_watchman_query_params, glob_internal, LazyBuildEnvPartial
from buck import subdir_glob, BuildFileContext
from pathlib import Path, PurePosixPath, PureWindowsPath
import os
import shutil
import tempfile
import unittest
class FakePathMixin(object):
def glob(self, pattern):
return self.... |
import sys
from contextlib import contextmanager
from StringIO import StringIO
import mock
from nose.tools import raises
from . import prompt as _
class TestValueToStr():
def test_none(self):
# pass none to value_to_str
assert _.value_to_str(None) == '', 'passing None should return an empty string'
... |
class ExceptionFinishBreakpoint(gdb.FinishBreakpoint):
def __init__(self, frame):
gdb.FinishBreakpoint.__init__ (self, frame, internal=1)
self.silent = True
print ("init ExceptionFinishBreakpoint")
def stop(self):
print ("stopped at ExceptionFinishBreakpoint")
return True... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: ovirt_disks
short_description: "Module to manage Virtual Machine and floating disks in oVirt"
version_added: "2.2"
author: "Ondra Machacek (@machacekondra)"
d... |
import json
import re
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
import tmp.benchmarks_pb2 as benchmarks_pb2
__file_size_map = {}
def __get_data_size(filename):
if filename[0] != '/':
filename = os.path.dirname(os.path.abspath(__file__)) + "/../... |
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from argparse import ArgumentParser
import django
from django.apps import apps
from django.conf import settings
from django.db import connection
from django.test import TestCase, TransactionTestCase
from django.test.util... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: apk
short_description: Manages apk packages
description... |
"""The tests for the Rfxtrx component."""
import unittest
import pytest
from homeassistant.core import callback
from homeassistant.bootstrap import setup_component
from homeassistant.components import rfxtrx as rfxtrx
from tests.common import get_test_home_assistant
@pytest.mark.skipif("os.environ.get('RFXTRX') != 'RUN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.