code stringlengths 1 199k |
|---|
"""test pb with exceptions and old/new style classes"""
class ValidException(Exception):
"""Valid Exception."""
class OldStyleClass:
"""Not an exception."""
class NewStyleClass(object):
"""Not an exception."""
def good_case():
"""raise"""
raise ValidException('hop')
def good_case1():
"""zlib.err... |
from dmoj.checkers import (
bridged,
easy,
floats,
floatsabs,
floatsrel,
identical,
linecount,
rstripped,
sorted,
standard,
unordered,
) |
import logging
from base64 import b64decode, b64encode
from werkzeug.datastructures import FileStorage
from odoo import models, fields, _
_logger = logging.getLogger(__name__)
try:
import magic
except ImportError:
_logger.warning("Please install magic in order to use Muskathlon module")
class OrderMaterialForm(... |
from estimatecharm.unnaturalCode import *
from logging import debug, info, warning, error
from estimatecharm import flexibleTokenize
import re
import sys, token
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
COMMENT = 53
ws = re.compile('\s')
class pythonLexeme(ucLexeme):
@class... |
import unittest
import argparse
import logging
import tests
def run():
parser = argparse.ArgumentParser()
parser.add_argument('--print-log', action='store_true',
help='Print the log.')
args = parser.parse_args()
if args.print_log:
logging.basicConfig(level=logging.DEBUG,
... |
from __future__ import print_function
import argparse
import logging
import memcache
import sys
from lxml import etree
import cnxepub
from cnxepub.formatters import exercise_callback_factory
ARCHIVEHTML = 'https://archive.cnx.org/contents/{}.html'
MATHJAX_URL = 'https://cdn.mathjax.org/mathjax/{mathjax_version}/'\
... |
import math
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y + step * math.sin(angle)
return nx, ny
x, y = move(80, 80, 60, math.pi / 6)
x = int(x)
y = int(y)
Loca1 = (x, y)
print(Loca1)
print(type(Loca1)) |
import logging
from twisted.internet.defer import inlineCallbacks
from txzookeeper.client import ZOO_OPEN_ACL_UNSAFE
from juju.machine.constraints import Constraints, ConstraintSet
from .auth import make_ace
from .environment import EnvironmentStateManager, GlobalSettingsStateManager
from .machine import MachineStateMa... |
from odoo import api, models
from odoo.addons.queue_job.job import job
class MatchPartner(models.AbstractModel):
"""
Extend the matching so that all create partner must be checked by a human.
"""
_inherit = 'res.partner.match'
def match_process_create_infos(self, infos, options=None):
create... |
from __future__ import print_function, unicode_literals
import calendar
import itertools
import json
import logging
import mimetypes
import os
import pycountry
import random
import re
import regex
import six
import stripe
import traceback
from collections import defaultdict
from datetime import datetime, timedelta
from... |
from django.test import TestCase
from django.core.urlresolvers import reverse
from docdata.interface import PaymentInterface
class PaymentTestBase(TestCase):
""" Base class for payment tests. """
def setUp(self):
""" Common setup. """
# Setup a payment interface
self.interface = PaymentI... |
from . import res_partner
from . import res_partner_id_category
from . import res_company |
"""
Test flake8 errors.
"""
from __future__ import absolute_import, print_function, division
from nose.plugins.skip import SkipTest
import os
from fnmatch import fnmatch
import theano
try:
import flake8.engine
import flake8.main
flake8_available = True
except ImportError:
flake8_available = False
__auth... |
from odoo import models
class ProjectTask(models.Model):
_inherit = "project.task"
def action_duplicate_subtasks(self):
action = self.env.ref("project.action_view_task")
result = action.read()[0]
task_created = self.env["project.task"]
for task in self:
new_task = tas... |
{'name': 'Magento Connector',
'version': '2.5.0',
'category': 'Connector',
'depends': ['account',
'product',
'delivery',
'sale_stock',
'connector_ecommerce',
'product_m2mcategories',
],
'external_dependencies': {
'python': ['magento'... |
from datetime import datetime
from openerp import api, fields, models
class AddressManagement(models.Model):
_name = 'myo.address.mng'
name = fields.Char('Name', required=True, index=True)
alias = fields.Char('Alias', help='Common name that the Address is referred.')
code = fields.Char(string='Code', he... |
import logging
import telepot
from ..Alarm import Alarm
from Stickers import sticker_list
from ..Utils import parse_boolean
log = logging.getLogger('Telegram')
try_sending = Alarm.try_sending
replace = Alarm.replace
class TelegramAlarm(Alarm):
_defaults = {
'pokemon': {
# 'chat_id': If no defaul... |
import asterisk
import wizard |
from Products.CMFCore.utils import getToolByName
from bika.lims.jsonapi import get_include_fields
from bika.lims import bikaMessageFactory as _
from bika.lims.browser import BrowserView
from bika.lims.utils import t, dicts_to_dict
from bika.lims.utils.analysis import get_method_instrument_constraints
from bika.lims.int... |
import odoo.tests.common as common
class TestSale(common.TransactionCase):
def setUp(self):
super(TestSale, self).setUp()
self.product_9 = self.env.ref("product.product_product_9")
self.product_11 = self.env.ref("product.product_product_11")
def test_import_product(self):
"""Crea... |
from collections import defaultdict
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
import logging
import pytz
from odoo import api, exceptions, fields, models, _
from odoo.osv import expression
from odoo.tools.misc import clean_context
from odoo.addons.base.models.ir_model import M... |
"""PILdriver, an image-processing calculator using PIL.
An instance of class PILDriver is essentially a software stack machine
(Polish-notation interpreter) for sequencing PIL image
transformations. The state of the instance is the interpreter stack.
The only method one will normally invoke after initialization is the... |
from superdesk.publish.formatters import Formatter
from apps.publish.formatters.aap_formatter_common import map_priority
from apps.archive.common import get_utc_schedule
import superdesk
from superdesk.errors import FormatterError
from bs4 import BeautifulSoup
import datetime
from superdesk.metadata.item import ITEM_TY... |
""" Models the characteristic response of the load demand due to to changes in system conditions such as voltage and frequency. This is not related to demand response. If LoadResponseCharacteristic.exponentModel is True, the voltage exponents are specified and used as to calculate: Active power component = Pnominal *... |
from odoo import models, api
import os
import tempfile
import StringIO
import pyPdf
class BVRFromInvoice(models.AbstractModel):
_name = 'report.one_slip_per_page_from_invoice'
class Report(models.Model):
_inherit = 'report'
@api.multi
def _generate_one_slip_per_page_from_invoice_pdf(self, report_name=No... |
def index():
"""
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
if you need a simple wiki simply replace the two lines below with:
return auth.wiki()
"""
response.flash = T('Welcome to gti2py!')
return dict(me... |
import time
from odoo.tests.common import TransactionCase
from ..exceptions import PassError
class TestResUsers(TransactionCase):
def setUp(self):
super(TestResUsers, self).setUp()
self.login = 'foslabs@example.com'
self.partner_vals = {
'name': 'Partner',
'is_company... |
from labonneboite.importer.jobs.performance_compute_data import (lancement_requete,
PayloadDataframe,prepare_google_sheet_data)
from labonneboite.importer.models.computing import PerfImporterCycleInfos, PerfDivisionPerRome, PerfPredictionAndEffectiveHirin... |
from __future__ import unicode_literals
from webnotes.model.doc import addchild
from test.doctype import assign_notify
from test.doctype import create_test_results,create_child_testresult, get_pgcil_limit,verfy_bottle_number,update_test_log
from webnotes.utils import cint, cstr, flt, now, nowdate, get_first_day, get_la... |
import re
import logging
import string
import urllib
import urllib2
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import Context, RequestContext
from utility import *
from appadmin import *
import grammar
logger = logging.getLogger(__name__)... |
"""
Simple Python Script to integrate a strong motion record using
the Newmark-Beta method
"""
import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
from smtk.sm_utils import (_save_image, get_time_vector, convert_accel_units,
get_velocity_displacement)
class ResponseSpectr... |
{'name': 'Picking dispatch',
'version': '1.2.3',
'author': 'Camptocamp',
'maintainer': 'Camptocamp',
'category': 'Products',
'complexity': "normal", # easy, normal, expert
'depends': ['stock',
'base',
'report_webkit',
'base_headers_webkit',
],
'description': "... |
from datetime import datetime
import gzip
from importlib import import_module
from io import BytesIO
import json
from openpyxl import load_workbook, Workbook
from openpyxl.utils import get_column_letter
from openpyxl.cell import WriteOnlyCell
from openpyxl.styles import NamedStyle, PatternFill
from openpyxl.comments im... |
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):
# Changing field 'Place.geo'
db.alter_column(u'scout_place', 'geo', self.gf('django.contrib.gis.db.m... |
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ResPartnerIdCategory(models.Model):
_inherit = "res.partner.id_category"
has_unique_numbers = fields.Boolean(
string="Enforce unicity",
help="When set, duplicate numbers will not be allowed for this categor... |
from . import models |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pyBuchaktion', '0005_auto_20170518_1600'),
]
operations = [
migrations.AlterField(
model_name='student',
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='FileUpload',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=F... |
"""
Monitor for new data collection images to be submitted to a redis instance
"""
__license__ = """
This file is part of RAPD
Copyright (C) 2016-2018 Cornell University
All rights reserved.
RAPD is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as publi... |
from bika.lims import _
from plone.supermodel import model
from plone import api
from plone.indexer import indexer
from zope import schema
from plone.dexterity.content import Item
from zope.interface import implements
from zope.schema.vocabulary import SimpleVocabulary
from Products.CMFCore.utils import getToolByName
f... |
import logging
import re
from odoo import models, fields, tools, _
testing = tools.config.get('test_enable')
_logger = logging.getLogger(__name__)
if not testing:
class PartnerSmsRegistrationForm(models.AbstractModel):
_name = 'cms.form.recurring.contract'
_inherit = 'cms.form'
_form_model =... |
import curses.ascii
import datetime
import json
import logging
import pipes
import re
import subprocess
import tempfile
import uuid
import weakref
import taskw.utils
from taskw import TaskWarriorShellout, utils
from taskw.fields import DependsField
from taskw.task import Task as TaskwTask
from inthe_am.taskmanager.util... |
import colander
from pyramid.view import view_config
from dace.objectofcollaboration.principal.util import get_current
from dace.objectofcollaboration.entity import Entity
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.form import FormView
from pontus.default_behavior import Cancel
from ... |
from setuptools import setup
import setup_utils
options = setup_utils.prepare_setup()
ext_modules = []
ext_modules += setup_utils.create_pcl_extentions()
setup(
name="fluxclient",
version=setup_utils.get_version(),
author="FLUX Inc. Development Team",
author_email="cerberus@flux3dp.com",
description... |
import sys
def main():
from ansible.module_utils.basic import AnsibleModule
module = AnsibleModule({
"egg_path": {"required": True, "type": "path"}
})
sys.path.append(module.params["egg_path"])
import falafel
module.exit_json(nvr=falafel.get_nvr())
if __name__ == "__main__":
main() |
from __future__ import print_function
from Numberjack import *
def get_model(N):
series = VarArray(N, 0, N - 1)
model = Model(
AllDiff(series),
AllDiff([Abs(series[i] - series[i - 1]) for i in range(1, N)]))
return series, model
def solve(param):
N = param['N']
series, model = get_mo... |
"""EPIC (Electoral Photo Identity Card, Indian Voter ID).
The Electoral Photo Identity Card (EPIC) is an identity document issued by
the Election Commission of India (ECI) only to the India citizens who have
reached the age of 18.
Each EPIC contains an unique 10 digit alphanumeric identifier known as EPIC
number or Vot... |
__doc__ = ""
__version__ = "1.0.0"
__versionTime__ = "24/07/2008"
__author__ = "Fabien Marteau <fabien.marteau@armadeus.com>"
from periphondemand.bin.define import *
from periphondemand.bin.code.topgen import TopGen
from periphondemand.bin.utils import wrappersystem as sy
from periphondemand.bin.utils.setti... |
class SinglevalueVariant(Package):
homepage = "http://www.llnl.gov"
url = "http://www.llnl.gov/mpileaks-1.0.tar.gz"
version(1.0, 'foobarbaz')
variant(
'fum',
description='Single-valued variant with type in values',
default='bar',
values=str,
multi=False
) |
"""support to generate SQLObject-based fixtures."""
from fixture.style import camel_to_under
from fixture import SQLObjectFixture
from fixture.command.generate import (
DataHandler, FixtureSet, register_handler, code_str,
UnsupportedHandler, MisconfiguredHandler, NoData )
try:
import sqlobject
except Import... |
from __future__ import absolute_import, unicode_literals
import unittest
if __name__ == '__main__':
import os
import sys
sys.path.insert(0, os.path.dirname(
os.path.dirname(os.path.abspath(__file__))
))
import simpleacl
from simpleacl.exceptions import MissingRole, MissingPrivilege,\
Missing... |
from spack import *
class Giraph(Package):
"""Apache Giraph is an iterative graph processing system built
for high scalability."""
homepage = "https://giraph.apache.org/"
url = "https://downloads.apache.org/giraph/giraph-1.0.0/giraph-dist-1.0.0-src.tar.gz"
list_url = "https://downloads.apache.o... |
"""Spack's installation tracking database.
The database serves two purposes:
1. It implements a cache on top of a potentially very large Spack
directory hierarchy, speeding up many operations that would
otherwise require filesystem access.
2. It will allow us to track external installations as well as los... |
"""
Module that defines Translator objects for converted AST from Reader to Rendered output from
Renderer objects. The Translator objects exist as a place to import extensions and bridge
between the reading and rendering content.
"""
import os
import uuid
import logging
import multiprocessing
import types
import traceb... |
out = open("python34stub.def", "w")
out.write('LIBRARY "python34"\n')
out.write('EXPORTS\n')
inp = open("python3.def")
line = inp.readline()
while line.strip().startswith(';'):
line = inp.readline()
line = inp.readline() # LIBRARY
assert line.strip()=='EXPORTS'
for line in inp:
# SYM1=python34.SYM2[ DATA]
h... |
import cv2
import numpy as np
import os
import time
def extract_frames(fname,prefix,skip=1):
print('Extracting %s'%fname)
t1 = time.time()
cap = cv2.VideoCapture(fname)
cnt = 0
images = []
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if cnt%skip==0:
if prefix is None:
images.app... |
import numpy as np
from mockdtpkg import (define_a_type,
leveltwomod,
use_a_type,
top_level)
a = define_a_type.Atype() # calls initialise()
a.rl = 3.0 # calls set()
assert(a.rl == 3.0)
a.vec[:] = 0. # calls get() then sets array data in place
assert(np.all(a.v... |
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, redirect, reverse
from django import forms
from django.template.loader import render_to_string
from django.template import Context, Template
from django.template import RequestContext
from django.conf import settings
from dj... |
"""IRQ plugin."""
import os
import operator
from glances.globals import LINUX
from glances.timer import getTimeSinceLastUpdate
from glances.plugins.glances_plugin import GlancesPlugin
class Plugin(GlancesPlugin):
"""Glances IRQ plugin.
stats is a list
"""
def __init__(self, args=None, config=None):
... |
"""
This script enables to start IPv8 headless.
"""
import argparse
import signal
import sys
from asyncio import all_tasks, ensure_future, gather, get_event_loop, sleep
try:
import ipv8
del ipv8
except ImportError:
import __scriptpath__ # noqa: F401
from ipv8.REST.rest_manager import RESTManager
from ipv8.... |
from typing import Any, List, Union
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject, RESTObjectList
__all__ = [
"LDAPGroup",
"LDAPGroupManager",
]
class LDAPGroup(RESTObject):
_id_attr = None
class LDAPGroupManager(RESTManager):
_path = "/ldap/groups"
_obj_cls = ... |
from morsel.nodes import Output, Node
from morsel_europa.europac import EuropaCapture as CEuropaCapture
class EuropaCapture(Output):
def __init__(self, client = None, message = "", **kargs):
super(EuropaCapture, self).__init__(**kargs)
self.client = client
self.message = message
self.publisher = CEuro... |
# "pyleptonica" is a Python wrapper to Leptonica Library
# Copyright (C) 2010 João Sebastião de Oliveira Bueno <jsbueno@python.org.br>
#This program is free software: you can redistribute it and/or modify
#it under the terms of the Lesser GNU General Public License as published by
#the Free Software... |
"""quick_tests.py - run all unit tests in the project
This file is part of cMonkey Python. Please see README and LICENSE for
more information and licensing details.
"""
import unittest
import xmlrunner
import orig_membership_test as omembtest
import datamatrix_test as dmtest
import util_test as ut
import organism_test ... |
from msa.core.event_handler import EventHandler
from msa.builtins.command_registry.events import RegisterCommandEvent, HelpCommandEvent
from msa.builtins.tty.events import TextInputEvent
from msa.core import supervisor
from msa.builtins.tty.events import StyledTextOutputEvent
from msa.builtins.tty.style import heading,... |
import lxml.etree as ET
import os
import socket
import stat
import string
import urlparse
from lxml import objectify
from lxml.builder import E
from wok.exception import InvalidParameter, NotFoundError
from wok.plugins.kimchi.utils import check_url_path
BUS_TO_DEV_MAP = {'ide': 'hd', 'virtio': 'vd', 'scsi': 'sd'}
DEV_T... |
"""
Tests of MultivariateRandomMixture
===================================
Test 2: R^3-->R^3 case - Non diagonal matrix test
"""
if __name__ == "__main__":
import openturns as ot
import MultivariateRandomMixture as MV
import numpy as np
blockMin = 3
blockMax = 7
n_blockMax = 2**block... |
from ..periodictable import QueryElement
class QueryAtom:
__slots__ = ('atom', 'charge', 'is_radical', 'neighbors', 'hybridization', 'xy')
def __setstate__(self, state):
atom = state['atom']
if atom['element'] is None or len(atom['element']) > 1:
raise TypeError('Any element in query... |
import os, sys, re, string
std_types = ['bool', 'float', 'double', 'int', 'long'] # , 'std::string']
forbidden = ['param', 'width', 'height', 'type', 'class', 'cached', 'master', 'fps']
def translate_type(decl):
""" Translate types to internal types of Markus """
# if decl[0] == 'string':
# return 'std::string'
if... |
from .plasma import Plasma
from .rainbow import Rainbow
from .ripple import Ripple
from .reaction import Reaction |
from __future__ import print_function, unicode_literals, division, absolute_import
from . import abstract, base, common, error
from .library import lib
from .loop import Loop
__all__ = ['UVRequest']
class RequestType(common.Enumeration):
UNKNOWN = lib.UV_UNKNOWN_REQ
CONNECT = lib.UV_CONNECT
WRITE = lib.UV_W... |
try:
import re2 as re
except ImportError:
import re
from lib.cuckoo.common.abstracts import Signature
class NetworkHTTP(Signature):
name = "network_http"
description = "Performs some HTTP requests"
severity = 2
confidence = 30
categories = ["http"]
authors = ["nex"]
minimum = "0.5"
... |
from guineapig import *
import sys
import math
def loadAsDict(view):
result = {}
for (key,val) in GPig.rowsOf(view):
result[key] = val
return result
class TFIDF(Planner):
data = ReadLines('idcorpus.txt') \
| Map(by=lambda line:line.strip().split("\t")) \
| Map(by=lambda (docid,do... |
{
'name': "Care Center Procedures",
'summary': """
Add Procedures to Tasks / Tickets.
""",
'author': "Dave Burkholder <dave@thinkwelldesigns.com>",
'website': "http://www.thinkwelldesigns.com",
"category": "Project Management",
'version': '0.2',
'depends': [
'care_cen... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('backend', '0018_auto_20170919_1637'),
]
operations = [
migrations.CreateModel(
name='GroupTag',
... |
"""sportloto URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... |
debug_mode = True # in debug mode nothing will be sold!
log_filename = "" # file name for log
username = ""
apikey = ""
secret = ""
ghs = 1.40 # number of ghs to be sold on price drop
limit = 0.0462 # limit for stop loss
gap = 0.0001 # window size
maximum = limit+gap # top price for trailing st... |
from flask import request
from flask_cors import CORS
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
)
from flask_restful import Resource
from flask_restless import APIManager, ProcessingException
from .models import Category, Question, User, QuestionW... |
import webapp2
from handlers import MainPage, Signup, Login, Logout, NewDraft, DraftPage
app = webapp2.WSGIApplication([
('/', MainPage),
('/signup', Signup),
('/login', Login),
('/logout', Logout),
('/newdraft', NewDraft),
('/draft/([0-9]+)(?:\.json)?', DraftPage),
],
debug=True) |
from .elements import Outputs, Parameters, Summary
def new_parameters(parms_dict):
return Parameters(parms=parms_dict)
def parameters(boto3_session, stack_name):
return Parameters(_get_stack(boto3_session, stack_name))
def outputs(boto3_session, stack_name):
return Outputs(_get_stack(boto3_session, stack_na... |
from google.cloud import contact_center_insights_v1
def sample_update_settings():
# Create a client
client = contact_center_insights_v1.ContactCenterInsightsClient()
# Initialize request argument(s)
request = contact_center_insights_v1.UpdateSettingsRequest(
)
# Make the request
response = c... |
"""Unit tests for the API endpoint"""
import datetime
import httplib
import random
import StringIO
import boto
from boto.ec2 import regioninfo
from boto import exception as boto_exc
import webob
from nova import block_device
from nova import context
from nova import exception
from nova import test
from nova.api import ... |
from model.contact_properties import Contact_properties
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def add_contact(self, contact_properties):
wd = self.app.wd
# open "Add new contact" page
wd.find_element_by_link_text("add new").click()
... |
from common_fixtures import * # NOQA
from cattle import ApiError
TEST_SERVICE_OPT_IMAGE = 'ibuildthecloud/helloworld'
TEST_SERVICE_OPT_IMAGE_LATEST = TEST_SERVICE_OPT_IMAGE + ':latest'
TEST_SERVICE_OPT_IMAGE_UUID = 'docker:' + TEST_SERVICE_OPT_IMAGE_LATEST
LB_IMAGE_UUID = "docker:sangeetha/testlbsd:latest"
SSH_IMAGE_U... |
import scrapy
from scrapy.utils.project import get_project_settings
from scrapy.pipelines.images import ImagesPipeline
import os
class ImagesPipeline(ImagesPipeline):
#def process_item(self, item, spider):
# return item
# 获取settings文件里设置的变量值
IMAGES_STORE = get_project_settings().get("IMAGES_STORE")
... |
from setuptools import setup
setup(name='epynet',
version='0.1',
description='Vitens EPANET 2.0 wrapper and utilities',
url='https://github.com/vitenstc/epynet',
author='Abel Heinsbroek',
author_email='abel.heinsbroek@vitens.nl',
license='Apache Licence 2.0',
packages=['epynet'... |
from django.shortcuts import render,redirect
from django.utils import timezone
from .models import Post
from django.http import HttpResponseRedirect, JsonResponse, HttpResponse
from django.shortcuts import render, render_to_response, get_object_or_404
from .forms import PostForm
from django.contrib.auth.forms import Us... |
from google.cloud import dlp_v2
def sample_activate_job_trigger():
# Create a client
client = dlp_v2.DlpServiceClient()
# Initialize request argument(s)
request = dlp_v2.ActivateJobTriggerRequest(
name="name_value",
)
# Make the request
response = client.activate_job_trigger(request=... |
import json
import os
from oslo_utils import encodeutils
from oslo_utils import uuidutils
import prettytable
from osprofiler.cmd import cliutils
from osprofiler.drivers import base
from osprofiler import exc
class BaseCommand(object):
group_name = None
class TraceCommands(BaseCommand):
group_name = "trace"
... |
import numpy as np
from xray import indexing, variable, Dataset, Variable, Coordinate
from . import TestCase, ReturnItem
class TestIndexers(TestCase):
def set_to_zero(self, x, i):
x = x.copy()
x[i] = 0
return x
def test_expanded_indexer(self):
x = np.random.randn(10, 11, 12, 13, ... |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.cloud.aiplatform.v1.schema.predict.params",
manifest={"ImageClassificationPredictionParams",},
)
class ImageClassificationPredictionParams(proto.Message):
r"""Prediction model parameters for Image Classification.
Attributes:
... |
import importlib
from indy_node.__metadata__ import __version__ as node_pgk_version
from plenum.server.validator_info_tool import none_on_fail, \
ValidatorNodeInfoTool as PlenumValidatorNodeInfoTool
class ValidatorNodeInfoTool(PlenumValidatorNodeInfoTool):
@property
def info(self):
info = super().in... |
"""Keras backend config API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
_FLOATX = 'float32'
_EPSILON = 1e-7
_IMAGE_DATA_FORMAT = 'channels_last'
def epsilon():
"""Returns the value of the fuzz factor used in numeric expressions.
Returns:
A f... |
from copy import deepcopy
from re import search, compile
from lxml.etree import fromstring, tostring, Element, _Element
from lxml.etree import _ElementStringResult, _ElementUnicodeResult
from datatype import DateTime, Boolean
from utils import _get_abspath, _get_elements, _get_element
from utils import _get_style_tagna... |
"""
MailMojo API
v1 of the MailMojo API # noqa: E501
OpenAPI spec version: 1.1.0
Contact: hjelp@mailmojo.no
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import mailmojo_sdk
from mailmojo_sdk.models.statistics import Stat... |
"""Driver for EMC CoprHD iSCSI volumes."""
from oslo_log import log as logging
from cinder import interface
from cinder.volume import driver
from cinder.volume.drivers.coprhd import common as coprhd_common
LOG = logging.getLogger(__name__)
@interface.volumedriver
class EMCCoprHDISCSIDriver(driver.ISCSIDriver):
"""C... |
from sqlalchemy import event
from slugify import slugify
from flask import current_app as app
from flask import url_for
from flask_editablesite.database import (
Column,
db,
Model,
SurrogatePK,
Slugged,
TimeStamped,
Confirmable,
update_slug_before_save,
update_timestamps_before_inser... |
"""fake formatter mapper"""
from plasoscaffolder.bll.mappings import base_mapping_helper
from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping
from plasoscaffolder.model import base_data_model
class FakeSQLitePluginMapper(base_sqliteplugin_mapping.BaseSQLitePluginMapper):
"""class representing the fake p... |
import sys
from taskflow.persistence import backends
def get_backend():
try:
backend_uri = sys.argv[1]
except Exception:
backend_uri = 'sqlite://'
backend = backends.fetch({'connection': backend_uri})
backend.get_connection().upgrade()
return backend |
from __future__ import print_function
import asyncio
import opentracing
from opentracing.ext import tags
from opentracing.mocktracer import MockTracer
from opentracing.scope_managers.contextvars import ContextVarsScopeManager
from ..testcase import OpenTracingTestCase
from ..utils import get_logger, get_one_by_tag, sto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.