code stringlengths 1 199k |
|---|
from JoeAgent import job, event
import db_interface
import os, os.path
import logging
import log_parser
LINEINCR = 30
log = logging.getLogger("agent.LogReader")
class ReadLogCompleteEvent(event.Event):
"""Event to indicate the file is completely read. This event will
be caught by the FindLogJob that is watch... |
@app.route('/job/<name>')
def results(name):
job = saliweb.frontend.get_completed_job(name,
flask.request.args.get('passwd'))
# Determine whether the job completed successfully
if os.path.exists(job.get_path('output.pdb')):
template = 'results_ok.html'
... |
__doc__ = ""
__version__ = "1.0.0"
__author__ = "Fabien Marteau <fabien.marteau@armadeus.com>"
import re
from periphondemand.bin.utils.wrapperxml import WrapperXml
from periphondemand.bin.utils.error import Error
DESTINATION = ["fpga","driver","both"]
PUBLIC = ["true","false"]
class Generic(WrapperXml):
""" Ma... |
import logging
from ..DataUploader import Plugin as DataUploaderPlugin
from .reader import AndroidReader, AndroidStatsReader
from ...common.interfaces import AbstractPlugin
try:
from volta.core.core import Core as VoltaCore
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-lo... |
"""
Linux installation
"""
import os
import re
import time
import libvirt
import oz.Guest
import oz.OzException
class LinuxCDGuest(oz.Guest.CDGuest):
"""
Class for Linux installation.
"""
def __init__(self, tdl, config, auto, output_disk, nicmodel, diskbus,
iso_allowed, url_allowed, mac... |
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def loadMapFile(path, engine, callback=None, debug=True, extensions={}):
""" load ... |
from __future__ import print_function
from __future__ import absolute_import
from enigma import *
from Screens.MessageBox import MessageBox
from Screens.Standby import TryQuitMainloop
from . crossepglib import *
from . crossepg_downloader import CrossEPG_Downloader
from . crossepg_importer import CrossEPG_Importer
from... |
"""
cNotify package provides three main concepts: I{L{signals <signal>}}, I{L{conditions
<condition>}} and I{L{variables <variable>}}. Signals are basically lists of callables
that can be I{emitted} and then will call all contained callables (I{handler} of a signal)
in turn. Conditions are boolean values complemented... |
import sys
import os
on_rtd = os.environ.get('READTHEDOCS') == 'True'
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.mathjax',
]
templates_path = ['_templates']
source_suffix = ['.rst']
master_doc = 'index'
project = 'Backend.AI API Documentation'
copyright = '2015-2020, Lablup Inc.'
author = 'Lablup Inc.... |
import math
import socket
import tempfile
import unittest
from contextlib import closing
import numpy as np
from shyft.api import (
Calendar, UtcPeriod,
DtsServer, DtsClient,
TimeAxis, TimeSeries, POINT_AVERAGE_VALUE, POINT_INSTANT_VALUE
)
from shyft.pyapi import fixed_tsv, windowed_percentiles_tsv, period_... |
"""
RSS Reader for C-Power 1200
Copyright 2010-2012 Michael Farrell <http://micolous.id.au/>
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option)... |
from distutils.core import setup
import os.path
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Operati... |
{
'name' : 'Signature templates for user emails',
'version' : '1.0.0',
'author' : 'IT-Projects LLC, Ivan Yelizariev',
'license': 'LGPL-3',
'category' : 'Social Network',
'website' : 'https://yelizariev.github.io',
'depends' : ['base'],
'data':[
'res_users_signature_views.xml',
... |
import hashlib
import uuid
def get_hash(data):
"""Returns hashed string"""
return hashlib.sha256(data).hexdigest()
def get_token():
return str(uuid.uuid4()) |
import sys
if sys.argv[1] == 'template':
effectname = 'template'
parameters = [('Vol', (0.0, 1.0, 0.5, 0.25, 0.00001))]
# pName, (min, max, default, skew, increment)
# where skew is a dynamic adjustment of exp/lin/log translation if the GUI widget
# and increment ... |
import unittest
from matching.cpe_sorter import *
unsorted_cpes = [{'wfn': {'version': '4.0', 'target_sw': 'android_marshmallow'},
'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.0:beta:~~~android_marshmallow~~'},
{'wfn': {'version': '1.0.1.2', 'target_sw':... |
"""
# Copyright (c) 05 2015 | surya
# 18/05/15 nanang.ask@kubuskotak.com
# 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 2
# of the License, or (at your option) any later ve... |
import os
import socket
import sys
input_host = '127.0.0.1'
input_port = 65000
batch_enabled = int(os.environ.get('_BACKEND_BATCH_MODE', '0'))
if batch_enabled:
# Since latest Python 2 has `builtins`and `input`,
# we cannot detect Python 2 with the existence of them.
if sys.version_info.major > 2:
i... |
class Range:
"""A class that mimic's the built-in range class."""
def __init__(self, start, stop=None, step=1):
"""Initialize a Range instance.
Semantics is similar to built-in range class.
"""
if step == 0:
raise ValueError('step cannot be 0')
if stop is None... |
"""
This script edits your backends conf file by replacing stuff like:
[bnporc21]
_module = bnporc
website = pp
login = 123456
password = 78910
with:
[bnporc21]
_module = bnporc
website = pp
login = 123456
password = `pass show weboob/bnporc21`
"""
from __future__ import print_function
import os
import re
import shutil... |
import oauth2 # XXX pumazi: factor this out
from webob.multidict import MultiDict, NestedMultiDict
from webob.request import Request as WebObRequest
__all__ = ['Request']
class Request(WebObRequest):
"""The OAuth version of the WebOb Request.
Provides an easier way to obtain OAuth request parameters
(e.g. o... |
import re
import json
from datetime import datetime
from weboob.browser.pages import LoggedPage, HTMLPage, JsonPage
from weboob.browser.elements import DictElement, ItemElement, method
from weboob.browser.filters.standard import Date, CleanDecimal, CleanText, Format, Field, Env, Regexp, Currency
from weboob.browser.fil... |
"""
.15925 Editor
Copyright 2014 TechInvestLab.ru dot15926@gmail.com
.15925 Editor is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
... |
import os
import struct
from binascii import unhexlify
from shutil import copy as copyfile
from twisted.internet.defer import inlineCallbacks
from Tribler.Core.CacheDB.SqliteCacheDBHandler import TorrentDBHandler, MyPreferenceDBHandler, ChannelCastDBHandler
from Tribler.Core.CacheDB.sqlitecachedb import str2bin
from Tr... |
"""
Property reference docs:
- https://docs.microsoft.com/en-us/office/client-developer/outlook/mapi/mapping-canonical-property-names-to-mapi-names#tagged-properties
- https://interoperability.blob.core.windows.net/files/MS-OXPROPS/[MS-OXPROPS].pdf
- https://fossies.org/linux/libpst/xml/MAPI_definitions.pdf
- https... |
import bpy
import blf
import math
import gpu, bgl
from bpy import types
from mathutils import Vector, Matrix
from mathutils import geometry
from bpy_extras import view3d_utils
from blenderbim.bim.module.drawing.shaders import DotsGizmoShader, ExtrusionGuidesShader, BaseLinesShader
from ifcopenshell.util.unit import si_... |
import random
import time
class Treap:
def __init__(self, key):
self.key = key
self.prio = random.randint(0, 1000000000)
self.size = 1
self.left = None
self.right = None
def update(self):
self.size = 1 + size(self.left) + size(self.right)
def size(treap):
retu... |
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_it... |
import fechbase
class Records(fechbase.RecordsBase):
def __init__(self):
fechbase.RecordsBase.__init__(self)
self.fields = [
{'name': 'FORM TYPE', 'number': '1'},
{'name': 'FILER FEC CMTE ID', 'number': '2'},
{'name': 'ENTITY TYPE', 'number': '3'},
{'n... |
"""
Largest product in a grid
Problem 11
Published on 22 February 2002 at 06:00 pm [Server Time]
In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
The product of these numbers is 26 * 63 * 78 * 14 = 1788696.
What is the greatest product of four adjacent numbers in the same direction (... |
"""
Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string.
Examples:
foo -> foo1
foobar23 -> foobar24
foo0042 -> foo004... |
from ..parsers.errors import ErrorResponse
from warnings import warn
def raise_for_error(f):
"""
Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered.
:param f:
:return:
"""
def inner(*args, **kwargs):
warn('`raise_for_error` is depre... |
import random
import socket
import os
import time
import threading
import Queue
import sys
import argparse
from multiprocessing import Process
print """\33[91m
═════════════════════════════════════════════════════════
███████ ██████ ███████
█ █ █ █ ║
... |
"""
Assorted utilities for manipulating latitude and longitude values
"""
from __future__ import unicode_literals
__version__ = "1.4"
import math, struct
def signbit(value):
"""
Test whether the sign bit of the given floating-point value is
set. If it is set, this generally means the given value is
neg... |
from math import log
def num_prime_factors(upper_limit):
"""
Create an array whose entries are the number of not necessarily distinct
prime factors of the index. The upper bound is the first number not
included.
"""
factor_count = [0] * upper_limit
prime = 2 #start with the first prime, whic... |
from __future__ import unicode_literals
import base64
import functools
import json
import re
import itertools
from .common import InfoExtractor
from ..compat import (
compat_kwargs,
compat_HTTPError,
compat_str,
compat_urlparse,
)
from ..utils import (
clean_html,
determine_ext,
dict_get,
... |
__author__ = 'Alex'
from Movement import Movement
class BaseCommand:
def __init__(self, movement):
assert isinstance(movement, Movement)
self.name = 'unknown'
self.m = movement
def execute(selfself):pass
class Forward(BaseCommand):
def __init__(self, movement):
assert isinsta... |
import sys
import os
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'yara'
copyright = u'2014-2019, VirusTotal'
version = '3.9'
release = '3.9.0'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
try:
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"... |
"""Libraries of Keras metrics."""
import tensorflow as tf
def _apply_mask(y_true, sample_weight, masked_tokens, dtype):
if sample_weight is None:
sample_weight = tf.ones_like(y_true, dtype)
else:
sample_weight = tf.cast(sample_weight, dtype)
for token in masked_tokens:
mask = tf.cast(tf.not_equal(y_tr... |
"""Training script."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
from absl import logging
import tensorflow.compat.v1 as tf
from cs_gan import file_utils
from cs_gan import gan
from cs_gan import ima... |
from facette.utils import *
from facette.v1.plotserie import PlotSerie
import json
PLOT_ID = "id"
PLOT_NAME = "name"
PLOT_DESCRIPTION = "description"
PLOT_TYPE = "type"
PLOT_SERIES = "series"
PLOT_STACK_MODE = "stack_mode"
PLOT_START = "start"
PLOT_END = "end"
PLOT_STE... |
"""
Set up the logging
"""
import logging
import tempfile
import os
def initialize_logging():
"""
Set up the screen and file logging.
:return: The log filename
"""
# set up DEBUG logging to file, INFO logging to STDERR
log_file = os.path.join(tempfile.gettempdir(), 'spfy.log')
formatter ... |
import pytest
from selenium import webdriver
@pytest.fixture
def driver(request):
wd = webdriver.Firefox(capabilities={"marionette": True})
#(desired_capabilities={"chromeOptions": {"args": ["--start-fullscreen"]}})
request.addfinalizer(wd.quit)
return wd
def test_example(driver):
driver.get("http:/... |
import numpy as np
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
"""
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
function v... |
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
import datetime
import socket
import time
import sys
import os.path
lib_path = os.path.abspath('../utils')
sys.path.append(lib_path)
from myParser import *
from myCrypto import *
import re
import hashlib
host='localhost'
port=90... |
"""
Tests.
"""
import unittest
from bruges.rockphysics import fluidsub
vp_gas = 2429.0
vs_gas = 1462.4
rho_gas = 2080.
vp_brine = 2850.5
vs_brine = 1416.1
rho_brine = 2210.0
phi = 0.275 # Don't know this... reading from fig
rhohc = 250.0 # gas
rhow = 1040.0 # brine
sw = 0.3 # Don'... |
from __future__ import absolute_import
from rigour.errors import ValidationFailed
from rigour.types import *
from rigour.constraints import length_between
import rigour
import pytest
def test_secrecy_declared_before():
t = String().secret().constrain(length_between(4,6))
with pytest.raises(ValidationFailed) as exci... |
"""
The No Age scheduler is based on the Heapset scheduler, though it does not take age into account.
.. warning:: This scheduler does not take the age into account, making it **unusable** in simulations where the *timeAdvance* function can return (exactly) 0. If unsure, do **not** use this scheduler, but the more gene... |
from datetime import datetime
from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from core.spaces.file_validation import ContentTypeRestrictedFileF... |
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext_lazy
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard import policy
class AddProtocol(policy.PolicyTargetMixin, tables.LinkAction):
name = "crea... |
"""nsx_gw_devices
Revision ID: 19180cf98af6
Revises: 117643811bca
Create Date: 2014-02-26 02:46:26.151741
"""
revision = '19180cf98af6'
down_revision = '117643811bca'
migration_for_plugins = [
'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2',
'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin',
... |
from datetime import datetime
import random
import string
from bson import ObjectId
class DuplicateUserException(Exception):
def __init__(self, message='User name/email already exits'):
Exception.__init__(self, message)
pass
class UserServiceException(Exception):
def __init__(self, message=None):
... |
from abc import ABCMeta, abstractmethod, abstractproperty
from contextlib import contextmanager
from functools import wraps
import gzip
from inspect import getargspec
from itertools import (
combinations,
count,
product,
)
import operator
import os
from os.path import abspath, dirname, join, realpath
import... |
import socket
import re
from xii import error, util
class Validator():
def __init__(self, example=None, description=None):
self._description = description
self._example = example
def structure(self, accessor):
if accessor == "example":
return self._example
return self... |
from email.mime import text
import email.utils
import smtplib
import socket
import mailjet_rest
from scoreboard import main
app = main.get_app()
class MailFailure(Exception):
"""Inability to send mail."""
pass
def send(message, subject, to, to_name=None, sender=None, sender_name=None):
"""Send an email."""
... |
import pytest
from ray.train.callbacks.results_preprocessors import (
ExcludedKeysResultsPreprocessor,
IndexedResultsPreprocessor,
SequentialResultsPreprocessor,
AverageResultsPreprocessor,
MaxResultsPreprocessor,
WeightedAverageResultsPreprocessor,
)
def test_excluded_keys_results_preprocessor(... |
from builtins import map
from builtins import str
from builtins import object
from copy import deepcopy
import logging
from bq_data_access.v2.seqpeek.seqpeek_interpro import InterProDataProvider
logger = logging.getLogger('main_logger')
SAMPLE_ID_FIELD_NAME = 'sample_id'
TRACK_ID_FIELD = "tumor"
COORDINATE_FIELD_NAME =... |
import numpy as np
import xgboost as xgb
import pytest
try:
import shap
except ImportError:
shap = None
pass
pytestmark = pytest.mark.skipif(shap is None, reason="Requires shap package")
def test_with_shap():
from sklearn.datasets import fetch_california_housing
X, y = fetch_california_housing(retur... |
import pathlib
import importlib
import sys
__all__ = ['sample', 'sampleTxt', 'sampleBin']
this = pathlib.Path(__file__)
datadir = this.parent.parent / 'data'
loader = importlib.machinery.SourceFileLoader('sample', str(datadir / 'sample.py'))
sample = loader.load_module()
sampleTxt = datadir / 'sample.txt'
sampleBin = d... |
import datetime
from keystone import exception
from keystone.auth import plugins as auth_plugins
from keystone.common import dependency
from keystone.openstack.common import log
from oauthlib.oauth2 import RequestValidator
try: from oslo.utils import timeutils
except ImportError: from keystone.openstack.common import t... |
from zope.i18nmessageid import MessageFactory
PloneMessageFactory = MessageFactory('plone')
from Products.CMFCore.permissions import setDefaultRoles
setDefaultRoles('signature.portlets.gdsignature: Add GroupDocs Signature portlet',
('Manager', 'Site Administrator', 'Owner',)) |
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.db.models import Q
from pathlib import Path
from webframe.functions import TRUE_VALUES, LogMessage as lm, getTime
from webframe.... |
import hashlib
import base64
import datetime
import urllib2
import json
class TemplateSMS:
account_sid = ''
account_token = ''
app_id = ''
server_ip = ''
server_port = ''
soft_version = ''
timestamp = ''
def set_account(self, account_sid, token):
self.account_sid = account_sid
... |
from __future__ import print_function, division, absolute_import
import os
import argparse
import random
import numpy as np
import datetime
import os.path as osp
import sys
cur_dir = osp.dirname(osp.abspath(__file__))
sys.path.insert(1, osp.join(cur_dir, '.'))
from sklearn.datasets import load_svmlight_file
from scipy.... |
from google.cloud import aiplatform_v1
def sample_delete_study():
# Create a client
client = aiplatform_v1.VizierServiceClient()
# Initialize request argument(s)
request = aiplatform_v1.DeleteStudyRequest(
name="name_value",
)
# Make the request
client.delete_study(request=request) |
import sys
import logging
import hexdump
import vstruct
import vivisect
import envi
import envi.archs.i386 as x86
import envi.archs.amd64 as x64
import sdb
from sdb import SDB_TAGS
from sdb_dump_common import SdbIndex
from sdb_dump_common import item_get_child
from sdb_dump_common import item_get_children
logging.basic... |
"""Keystone's pep8 extensions.
In order to make the review process faster and easier for core devs we are
adding some Keystone specific pep8 checks. This will catch common errors
so that core devs don't have to.
There are two types of pep8 extensions. One is a function that takes either
a physical or logical line. The ... |
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... |
"""
lunaport.dao.line
~~~~~~~~~~~~~~~~~
Storage interaction logic for line resource.
"""
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from sqlalchemy import text, exc
from ..wsgi import app, db
from .. domain.line import LineBuilder, LineAdaptor
from exceptions import StorageError
class Filter(o... |
import os
import uuid
import pkg_resources
from pifpaf import drivers
class CephDriver(drivers.Driver):
DEFAULT_PORT = 6790
def __init__(self, port=DEFAULT_PORT,
**kwargs):
"""Create a new Ceph cluster."""
super(CephDriver, self).__init__(**kwargs)
self.port = port
@... |
import unittest
import tagging
class TestRealizerArbitraryReordering(unittest.TestCase):
"""
Tests for the realizer with arbitrary reordering
enabled.
"""
def test_realize_output_in_order(self):
"""
Test for when source tokens occur
in the same relative order ... |
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self... |
import warnings; warnings.filterwarnings(action='ignore', category=DeprecationWarning, module="sgmllib")
import threading
import time
import os
import socket, urlparse, urllib, urllib2
import base64
import htmlentitydefs
import sgmllib
import re
import xml.dom.minidom
import StringIO
import bisect
import new
import api... |
import os
shoop1=[
("家电类"),
("衣服类"),
("手机类"),
("车类"),
]
jiadianshoop=[
("电冰箱",20000),
("彩电",2000),
("洗衣机",400),
("脸盆",30),
("牙刷",50)
]
flag=True
long=len(jiadianshoop)
def f():
#重复代码
flag=True
long=len(jiadianshoop)
while flag:
for i in enumerate(shoop1):
... |
import os
import numpy as np
import sympy
import cirq
import recirq
@recirq.json_serializable_dataclass(namespace='recirq.readout_scan',
registry=recirq.Registry,
frozen=True)
class ReadoutScanTask:
"""Scan over Ry(theta) angles from -pi/2 to 3... |
from symbol.builder import add_anchor_to_arg
from models.FPN.builder import MSRAResNet50V1FPN as Backbone
from models.FPN.builder import FPNNeck as Neck
from models.FPN.builder import FPNRoiAlign as RoiExtractor
from models.FPN.builder import FPNBbox2fcHead as BboxHead
from mxnext.complicate import normalizer_factory
f... |
import logging
import json
import sys
from dlab.fab import *
from dlab.meta_lib import *
from dlab.actions_lib import *
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--uuid', type=str, default='')
args = parser.parse_args()
if __name__ == "__main__":
local_log_filename = "{}_{}_{... |
"""
Module used after C{%(destdir)s} has been finalized to create the
initial packaging. Also contains error reporting.
"""
import codecs
import imp
import itertools
import os
import re
import site
import sre_constants
import stat
import subprocess
import sys
from conary import files, trove
from conary.build import bu... |
import unittest
import pytest
from libweasyl import ratings
from weasyl.test import db_utils
from weasyl import character
@pytest.mark.usefixtures('db')
class SelectCountTestCase(unittest.TestCase):
def setUp(self):
self.user1 = db_utils.create_user()
self.user2 = db_utils.create_user()
self... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
from mri import MriServer
from mri.dispatch import MriServerDispatch
class TestMriSe... |
from JumpScale import j
descr = """
This jumpscript returns network info
"""
category = "monitoring"
organization = "jumpscale"
author = "kristof@incubaid.com"
license = "bsd"
version = "1.0"
roles = []
def action():
return j.sal.nettools.getNetworkInfo()
if __name__ == "__main__":
print(action()) |
"""Unit tests."""
import mock
import pandas
import pytest
from google.api_core import exceptions
from google.auth.credentials import AnonymousCredentials
from google.cloud import automl_v1beta1
from google.cloud.automl_v1beta1.proto import data_types_pb2
PROJECT = "project"
REGION = "region"
LOCATION_PATH = "projects/{... |
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framew... |
import requests
url = "https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJd8BlQ2BZwokRAFUEcm_qrcA&key=YOUR_API_KEY"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text) |
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from game import app
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start() |
import logging
from keystoneclient import base
from keystoneclient import exceptions
from keystoneclient.i18n import _, _LW
from keystoneclient import utils
LOG = logging.getLogger(__name__)
class User(base.Resource):
"""Represents an Identity user.
Attributes:
* id: a uuid that identifies the user
... |
from .client import SearchServiceClient
from .async_client import SearchServiceAsyncClient
__all__ = (
"SearchServiceClient",
"SearchServiceAsyncClient",
) |
import unittest
from typing import List, Dict
import google.api_core.exceptions
from google.cloud.bigtable.column_family import MaxVersionsGCRule
from google.cloud.bigtable.instance import Instance
from google.cloud.bigtable.table import ClusterState
from parameterized import parameterized
from airflow import AirflowEx... |
"""
Resource Scheduling Offhours
============================
Custodian provides for time based filters, that allow for taking periodic
action on a resource, with resource schedule customization based on tag values.
A common use is offhours scheduling for asgs and instances.
Features
========
- Flexible offhours schedu... |
from flask import Flask, Response, make_response
from video_stream_handler import stream_handler
import logging
import cv2
logging.basicConfig(level=logging.DEBUG)
thetav = None
app = Flask(__name__, static_url_path='/public', static_folder='../')
@app.route('/video_feed')
def video_feed():
cap = cv2.VideoCapture(0... |
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('dash', '0002_remove_post_origin'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='id',
... |
"""Container for Google Cloud Bigtable Cells and Streaming Row Contents."""
import copy
import six
from gcloud._helpers import _datetime_from_microseconds
from gcloud._helpers import _to_bytes
class Cell(object):
"""Representation of a Google Cloud Bigtable Cell.
:type value: bytes
:param value: The value s... |
'''This module provides helper functions for Gnome/GLib related
functionality such as gobject-introspection and gresources.'''
import build
import os, sys
import subprocess
from coredata import MesonException
import mlog
class GnomeModule:
def compile_resources(self, state, args, kwargs):
cmd = ['glib-compi... |
from muntjac.ui.vertical_layout import VerticalLayout
from muntjac.ui.menu_bar import MenuBar, ICommand
from muntjac.terminal.external_resource import ExternalResource
class MenuBarItemStylesExample(VerticalLayout):
def __init__(self):
super(MenuBarItemStylesExample, self).__init__()
self._menubar =... |
import types
from datetime import datetime, timedelta
from django.utils.timezone import now as timezone_now
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.upload import create_attachment
from zerver.models import Message, Realm, Recipient, UserProfile, UserMessage, ArchivedUserMessage, \
Archived... |
""" Base classes for DB backend implementation test
"""
import datetime
from unittest import mock
from oslo_utils import timeutils
from aodh import storage
from aodh.storage import models as alarm_models
from aodh.tests import constants
from aodh.tests.functional import db as tests_db
ALARM_TYPE = 'gnocchi_aggregation_... |
"""Pretty print logging."""
import logging
import pprint
from typing import Any
def log(level: int, x: Any) -> None:
if logging.getLogger(None).isEnabledFor(level):
for line in pprint.pformat(x).split('\n'):
logging.log(level, line)
def info(x: Any) -> None:
log(logging.INFO, x)
def debug(x:... |
import copy
import json
from unittest import mock
import sqlalchemy as sa
from mistral.db.v2 import api as db_api
from mistral.db.v2.sqlalchemy import models
from mistral import exceptions as exc
from mistral.services import security
from mistral.tests.unit.api import base
from mistral.tests.unit import base as unit_ba... |
from __future__ import print_function
import numpy as np
import mxnet as mx
import random
import itertools
from numpy.testing import assert_allclose, assert_array_equal
from mxnet.test_utils import *
from common import with_seed
import unittest
def test_box_nms_op():
def test_box_nms_forward(data, expected, thresh=... |
import sys
import cv2
import helper as hp
class MSP():
name = "MSP"
def __init__(self):
self.__patterns_num = []
self.__patterns_sym = []
self.__labels_num = []
self.__labels_sym = []
msp_num, msp_sym = "msp/num", "msp/sym"
self.__load_num_patterns(msp_num)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.