src stringlengths 721 1.04M |
|---|
"""
homeassistant.components.recorder
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component that records all events and state changes. Allows other components
to query this database.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/recorder/
"""
from contextlib imp... |
"""
Special classes to extend the module; e.g. plugins.
The extension mechanism is provided for projects that benefit
from a tighter integration then the Django URLconf can provide.
The API uses a registration system.
While plugins can be easily detected via ``__subclasses__()``, the register approach is less magic a... |
"""Manages Placeholders for Graph convolution networks.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = "Han Altae-Tran and Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import numpy as np
imp... |
import os
import sys
import copy
import logging
from checker import *
from .ofp import register_ofp_creators
from .ofp import OfpBase
from .ofp_bucket import SCE_BUCKETS
from .ofp_bucket import OfpBucketCreator
# YAML:
# group_mod:
# command: 0
# type: 0
# group_id: 0
# buckets:
# - bucket:
# weig... |
import urllib, urllib2, json, threading, itertools
try:
import websocket
except ImportError:
websocket = None
class ChromeDebuggerControl(object):
''' Control Chrome using the debugging socket.
Chrome must be launched using the --remote-debugging-port=<port> option for this to work! '''
def __ini... |
import time
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
brows... |
# coding=utf-8
__author__ = "AstroPrint Product Team <product@astroprint.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import os
import json
import uuid
from flask import request, jsonify, abort
from flask.ext.login import current_user
from requests import ConnectionErr... |
import datetime
##############################################################################
# Creates main function header for .h files and smaller headers for .c files
# Input: None
# Return: None
##############################################################################
def CreateFunctionHeader():
# Get ... |
# Copyright Vertex.AI.
import functools
import numpy as np
import numpy.testing as npt
import operator
import os
import unittest
import sys
import plaidml
import testing.plaidml_config
#import plaidml #only needed if adjusting vlog
from keras.backend.common import set_floatx, floatx
set_floatx('float32')
from keras... |
import asyncio
import decimal
import random
import discord
from discord.ext import commands
from .common import Cog
EMOJI_POOL = ':thinking: :snail: :shrug: :chestnut: :ok_hand: :eggplant:'.split()
BET_MULTIPLIER_EMOJI = ':thinking:'
X4_EMOJI = [':snail:', ':chestnut:', ':shrug:']
X6_EMOJI = [':eggplant:', ':ok_han... |
"""Some helper functions for working with Tekton resources."""
from kubernetes import client as k8s_client
# TODO(jlewi): Create a common base class to be shared with CnrmClients.
class TektonClientApi(k8s_client.CustomObjectsApi):
"""A wrapper around CustomObjectsApi."""
def __init__(self, client, kind):
"""... |
# Noysim -- Noise simulation tools for Aimsun.
# Copyright (c) 2010-2011 by Bert De Coensel, Ghent University & Griffith University.
#
# Classes for sending and viewing noise levels in real-time
import os
import sys
import socket
import threading
import time
import random
import msvcrt
if not hasattr(sys... |
import torch
from .Module import Module
from .utils import clear
class LookupTable(Module):
def __init__(self, nIndex, nOutput, paddingValue=-1, maxNorm=None, normType=None):
super(LookupTable, self).__init__()
self.weight = torch.Tensor(nIndex, nOutput)
self.gradWeight = torch.Tensor(nIn... |
# tests
# Testing for the ormbad module
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Thu Aug 13 12:34:07 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: __init__.py [] benjamin@bengfort.com $
"""
Testing for the ormbad module
"""
#########... |
import polyphony
from polyphony import module, pure
from polyphony import testbench
from polyphony.io import Port
from polyphony.typing import bit, uint3, uint4, List
from polyphony.timing import clksleep, clkfence, wait_rising, wait_falling
@module
class life:
def __init__(self):
self.i_bit4 = Port(uin... |
__author__ = 'novokonst'
import ply.lex as lex
def check_comment(fn):
def wrapped(self, t):
if self.nested_comment:
t.type = 'COMMENT'
return t
else:
return fn(self, t)
wrapped.__doc__ = fn.__doc__
return wrapped
class DummyLexer:
"""
Need to ... |
#codeing=utf-8
# @Time : 2017-10.04
# @Author : J.sky
# @Mail : bosichong@qq.com
# @Site : www.17python.com
# @Title : Python多线程编程(2)多线程锁 threading.Lock
# @Url : http://www.17python.com/blog/33
# @Details : Python多线程编程(2)多线程锁 threading.Lock
# @Other : OS X 10.11.6
# Python 3.6.1
# ... |
# ----------------------------------------------------------------------------
# pymunk
# Copyright (c) 2007-2012 Victor Blomqvist
#
# 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 with... |
import logging
import json
import re
import asyncio
from pyenvisalink import EnvisalinkClient
from pyenvisalink.honeywell_envisalinkdefs import *
_LOGGER = logging.getLogger(__name__)
class HoneywellClient(EnvisalinkClient):
"""Represents a honeywell alarm client."""
@asyncio.coroutine
def keep_a... |
# ***************************************************************************
# * Copyright (c) 2019 Bernd Hahnebach <bernd@bimstatik.org> *
# * Copyright (c) 2020 Sudhanshu Dubey <sudhanshu.thethunder@gmail.com *
# * *
# * Th... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# try to replace "old_div(a,b)"" by "a/b"
# with a and b being complex expressions involving brackets, etc.
# processes all the python files recursively from the current folder
#
# you must use the script several times
# (it processes 1 "old_div" per line at a time... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/setupform_base.ui'
#
# Created: Thu Sep 20 11:45:16 2007
# by: The PyQt User Interface Compiler (pyuic) 3.17
#
# WARNING! All changes made in this file will be lost!
from qt import *
class SetupForm_base(QWizard):
def __init_... |
#!/usr/bin/env python
##
## $LicenseInfo:firstyear=2011&license=viewerlgpl$
## Second Life Viewer Source Code
## Copyright (C) 2011, Linden Research, Inc.
##
## 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 Fr... |
import csv
from datetime import datetime, timedelta
INPUTFILE = 'geocoded_notdated_allyears.csv'
MATCHOUTPUTFILE = 'daysfound.csv'
NOMATCH_FILE = 'unmatched.csv'
MEETINGDATE_HEADER = 'Item Type Metadata:meeting date'
COLLECTION_NAME_HEADER = 'Collection'
# NB This doesn't do anything? commenting out for now.
#Impor... |
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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 agree... |
# coding: utf-8
import os
# Used for indexing tutorials, we need to parse each manifest to know which content have been published
class GetPublished:
published_part = []
published_chapter = []
published_extract = []
def __init__(self):
pass
@classmethod
def get_published_content(cls... |
# Copyright (C) 2011-2012 Patrick Totzke <patricktotzke@gmail.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
import abc
import glob
import logging
import mailbox
import os
from .helper import call_cmd_async
from .helper import split_commandstr... |
#!/usr/bin/env python3
from tkinter import *
from sys import argv
from PIL import Image
class App:
def __init__(self, master, photo, destA, destB):
frame = Frame(master)
frame.pack()
self.f = frame
self.destA = destA
self.destB = destB
self.button = Button(frame, text="Cancel", command=frame.quit)
se... |
from ilastik.core.baseModuleMgr import BaseModuleDataItemMgr, BaseModuleMgr
import numpy
import traceback, sys
from ilastik.core import jobMachine
from PyQt4 import QtCore
import os
import algorithms
from ilastik.core.volume import DataAccessor
from ilastik.core.overlayMgr import OverlayItem
""" Import all algorithm ... |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI... |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... |
import re
from bs4 import BeautifulSoup
import requests
from django.core.management.base import BaseCommand, CommandError
from districts.models import DistrictDetail
class Command(BaseCommand):
def handle(self, *args, **options):
import ipdb;ipdb.set_trace()
test_run = options['test_run']
... |
# coding: utf-8
from __future__ import unicode_literals
from unittest import TestCase
from httpretty import HTTPretty, PY3, parse_qs
import pytest
from cleanweb import Cleanweb, CleanwebError
class HttprettyCase(TestCase):
def setUp(self):
HTTPretty.reset()
HTTPretty.enable()
def tearDown(... |
# Copyright 2012 IBM Corp.
# Copyright 2013 Red Hat, Inc.
#
# 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 r... |
"""
WSGI config for analytics project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... |
"""modify assignee.
Revision ID: 253e7b76eb8e
Revises: 1ea1e8070ac8
Create Date: 2016-04-11 20:15:52.864916
"""
# revision identifiers, used by Alembic.
revision = '253e7b76eb8e'
down_revision = '1ea1e8070ac8'
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
def upgrade():
op.add_column(... |
# Copyright (c) 2016 MaxPoint Interactive, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditi... |
import requests
import json
from .base import BaseExtractor
from ...models import DocumentEntity, Entity, Utterance, DocumentTaxonomy
import logging
log = logging.getLogger(__name__)
class CalaisExtractor(BaseExtractor):
""" Use the OpenCalais API to extract entities and other
useful goodies from a document... |
from datetime import datetime, timedelta
import six
from .base import Generic, Object
from .exc import ValidationError
from .utils import is_descriptor
class SimpleType(Generic):
"""This descriptor will not attempt to coerce the value on __set__."""
_type_klass = None
_type_label = None
def __set_... |
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import weakref... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ppb.cli import sub_cmd
from ppb.cli import version
import argparse
import sys
class Main(object):
'''
This command line tool ...
'''
def main(self):
# Global command-line arg... |
import wx, os
from functools import partial
from fr0stlib.decorators import *
def LoadIcon(*path):
# Check for an icons dir in app base path first for development
filename = os.path.join(wx.GetApp().AppBaseDir, 'icons', *path) + '.png'
if not os.path.exists(filename):
# Not there, check install p... |
'''
view
====
Defines a view class for maintaining a graphics scene.
'''
import math
from PySide import QtCore, QtGui
class View(QtGui.QGraphicsView):
'''A View supporting smooth panning and zooming. Use Alt+Left Mouse to
pan and Alt+Middle or Right Mouse to zoom. Dragging without Alt drags out
a selecti... |
import logging
import multiprocessing
import sys
import time
from unittest import TestCase
import rexpython as rx
logging.basicConfig(format="%(asctime)-15s %(name)-25s %(levelname)s %(process)d %(message)s")
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
class TestOnError(TestCase):
def test_on... |
#!env python3
# -*- coding: utf-8 -*-
# from https://www.youtube.com/watch?v=Xi52tx6phRU
import csv
from datetime import datetime
def main():
'''Perform the video example'''
path = 'google_stock_data.csv'
f = open(path, newline='')
reader = csv.reader(f)
header = next(reader) # The first line ... |
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... |
from matplotlib.widgets import Slider
class DiscreteSlider(Slider):
"""A matplotlib slider widget with discrete steps."""
def __init__(self, *args, **kwargs):
"""Identical to Slider.__init__, except for the "increment" kwarg.
"increment" specifies the step size that the slider will be discritiz... |
import sys
from rpython.jit.metainterp.history import Const, TargetToken, JitCellToken
from rpython.jit.metainterp.optimizeopt.shortpreamble import ShortBoxes,\
ShortPreambleBuilder, ExtendedShortPreambleBuilder, PreambleOp
from rpython.jit.metainterp.optimizeopt import info, intutils
from rpython.jit.metainterp.... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
ExtractorError,
int_or_none,
float_or_none,
smuggle_url,
)
class NineNowIE(InfoExtractor):
IE_NAME = '9now.com.au'
_VALID_URL = r'https?://(?:www\.)?9now\.com\.au/(?:[... |
# -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion #
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
from openerp.addons.l10n_br_account.models.l10n_br_account import (
L10nBrTaxDefinition
)
class ResComp... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import taiga.base.db.models.fields
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... |
#
"""cmdline - Command line functionality for rdial."""
# Copyright © 2012-2019 James Rowe <jnrowe@gmail.com>
# Nathan McGregor <nathan.mcgregor@astrium.eads.net>
# Rach Holmes <rach.c.holmes@gmail.com>
#
# SPDX-License-Identifier: GPL-3.0+
#
# This file is part of rdial.
... |
"""Create a Kubeflow instance.
The purpose of this script is to automate the creation of Kubeflow Deployments
corresponding to different versions of Kubeflow.
TODO: This script is obsolete; we should get rid of it in favor of
create_unique_kf_instance.py.
"""
import argparse
import logging
import json
import os... |
class CondaEnvException(Exception):
pass
class CondaEnvRuntimeError(RuntimeError, CondaEnvException):
pass
class EnvironmentFileNotFound(CondaEnvException):
def __init__(self, filename, *args, **kwargs):
msg = '{} file not found'.format(filename)
self.filename = filename
super(En... |
from time import sleep, gmtime, mktime
from datetime import datetime
import logging
import scrapy
import redis
import msgpack
import xxhash
import pymongo as pm
import feedparser as fp
from colorama import Back, Fore, Style
from ..settings import MONGODB_URI, REDIS_HOST, REDIS_PORT, REDIS_PWD, REDIS_PENDING_QUEUE
def... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Channel.description'
db.add_column(u'sign_channel', 'desc... |
import unittest
class Solution:
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
result = []
slen = len(s)
# [0,p1) [p1,p2) [p2,p3) [p3,slen)
for p1 in range(1, 4):
for p2 in range(p1 + 1, p1 + 4):
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def niceCubicPolynomial(p):
tmp = ""
if p["a"] == 1:
tmp += " x^3"
elif p["a"] != 0:
tmp += "%.2fx^3" % p["a"]
if p["b"] == 1:
tmp += "\t+ x^2"
elif p["b"] != 0:
tmp += "\t+ %.2fx^2" % p["b"]
else:
tmp += "\t\... |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from loginurl.utils import create_key
@python_2_unicode_compatible
class Key(models.Model):
"""
A si... |
#!/usr/bin/python
import os, re
import numpy as np
import healpy as hp
import astropy.units as u
from astropy.coordinates import SkyCoord, EarthLocation, AltAz, get_sun
from astropy.time import Time
from astropy.io import fits
import ephem
from ephem import *
from params import Observatory_Locations
def Patch(fitsfile... |
#!/usr/bin/env python
#-------------------------------------------------------------------------------
#
# GeoTIFF creation subroutine
#
# Author: Martin Paces <martin.paces@eox.at>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2016 EOX IT Services GmbH
#
# Permissio... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
#
# Copyright 2012 John Gerlock
#
# 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 in wr... |
import unittest
class TestData(object):
def __init__(self, entity=None, **kw):
self.entity = entity
self.__dict__.update(kw)
class TestComponent(dict):
def __init__(self, entities=()):
self.entities = set(entities)
def __getitem__(self, entity):
return self.setdefault(entity, TestData(entity))
clas... |
import numpy as np
from sklearn.utils.validation import check_array
class NotFittedError(ValueError, AttributeError):
pass
def check_feature_array(array, n_features=None):
array = check_array(array, ensure_2d=True, allow_nd=False)
if n_features is not None and array.shape[1] != n_features:
raise... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# TESTING FILE made.by.a.fox. 12.2.15
# Updated by acrule 01.21.16
#FEATURE LIST
# Y connect to db
# Y write to file
# Y Write JSON format
# Accept input date parameter
#KNOWN ISSUES
# 2. no formatting or conversion of datetime stamps
import re
import os
i... |
# Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
# Copyright (c) 2011, 2012 Open Networking Foundation
# Copyright (c) 2012, 2013 Big Switch Networks, Inc.
# See the file LICENSE.pyloxi which should have been included in the source distribution
# Automatically generated by LOXI from ... |
import argparse
import errno
import httplib
import json
import urllib
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import urlparse
TOKEN = "~/.config/github-token"
WHITELIST = "~/.config/github-whitelist"
OS = os.environ.get("TEST_OS", "fedora-22")
ARCH = os.environ.get("TEST_A... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import re
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from odoo.tools.misc import mod10r
from odoo.exceptions import UserError
import werkzeug.urls
ISR_SUBSCRIPTION_CODE = {'CHF... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_survey.ui'
#
# Created: Wed Apr 29 17:42:49 2015
# by: PyQt4 UI code generator 4.11.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8... |
from PyQt4 import QtCore
class Worker(QtCore.QObject):
"""
Implements a queue of tasks to be carried out in order
in a single independent thread.
"""
# avoid multiple tests for debug availability
pydevd_failed = False
task_completed = QtCore.pyqtSignal(str)
def __init__(self, app, n... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from vdw.samples.models import DEFAULT_COHORT_NAME, DEFAULT_PROJECT_NAME
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
Project ... |
_version = '0.0.1'
import sys
import os
import argparse
from lib import logger, config, uri
from lib.provider import ProviderBase, getProvider
# Change default encoding to UTF-8
reload(sys)
sys.setdefaultencoding('UTF-8')
del sys.setdefaultencoding
sys.path = [os.path.abspath('.')] + sys.path
class _Smart_formatt... |
from urllib.parse import urlparse, urljoin
from flask import g, request, session, url_for
from teknologkoren_se import app
def paginate(content, page, page_size):
"""Return a page of content.
Calculates which posts to have on a specific page based on which
page they're on and how many objects there are p... |
# -*- coding: utf-8 -*-
import time
from functools import update_wrapper
from flask import request, g
from flask_redis import FlaskRedis
from .helpers import bad_request
from . import app
#
# REDIS RATE LIMITER
# ==================
redis = False
if app.config['REDIS_URL']:
redis = FlaskRedis(app)
class RateLi... |
"""
Twilio support
"""
from re import sub
from social.p3 import urlencode
from social.backends.base import BaseAuth
class TwilioAuth(BaseAuth):
name = 'twilio'
ID_KEY = 'AccountSid'
def get_user_details(self, response):
"""Return twilio details, Twilio only provides AccountSID as
paramet... |
from core.himesis import Himesis
class HepackageOUTeClassifiersSolveRefEPackageEClassifierEPackageEClassifier(Himesis):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HepackageOUTeClassifiersSolveRefEPackageEClassifierEPackageEClassifier.
"""
# Flag... |
from simplestats import *
def train(Ys, Xs, classes=[], active=[], k=3, dist=euclidean):
assert (Xs != []), "no training data"
assert (len(Xs) == len(Ys)), "Xs and Ys have differing lengths"
if active == []:
active = range(len(Xs[0]))
if classes == []:
classset = {}
map(classs... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
## @package layers
# Module caffe2.python.layers.layers
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema, scope
from caffe2.python.layers.tags import TagContext
from collections i... |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
#!/usr/bin/env python
# by TR
from obspy.core import UTCDateTime as UTC
from sito.data import IPOC
from sito.noisexcorr import (prepare, get_correlations,
plotXcorrs, noisexcorrf, stack)
from sito import util
import matplotlib.pyplot as plt
from sito.stream import read
from multiprocessing ... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
# coding=utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 yutiansut/QUANTAXIS
#
# 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 th... |
from collections import OrderedDict
import numpy as np
from test_base import VerosPyOMUnitTest
from veros.core import eke
class EKETest(VerosPyOMUnitTest):
nx, ny, nz = 70, 60, 50
extra_settings = {
'enable_cyclic_x': True,
'enable_eke_leewave_dissipation': True,
'enable_eke': True,
... |
# -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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... |
#!/usr/bin/env python
import time
import server
import argparse
DEFAULT_NAME = "Server2"
class OutdoorSensor (server.TemperatureSensor):
def __init__ (self):
super (OutdoorSensor, self).__init__ ("OS", "Outdoor Sensor", "20171127")
class OutdoorLight (server.ControlledRelayActuator):
def __init__ (self):
supe... |
from __future__ import annotations
from decimal import Decimal
from typing import (
Any,
Mapping,
)
from unittest.mock import MagicMock, AsyncMock
import snappy
from sqlalchemy.sql.dml import Insert, Update
from ai.backend.manager.registry import AgentRegistry
from ai.backend.manager.models import AgentStatu... |
#!/usr/bin/env python
import os
import unittest
import sys
from test_common import TestCommon
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'library'))
from fastly_service import FastlyConfiguration
class TestFastlyGzip(TestCommon):
GZIP_NAME = 'gzip-config-name'
@TestCommon.vcr.use_cassett... |
__source__ = 'https://leetcode.com/problems/moving-average-from-data-stream/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/moving-average-from-data-stream.py
# Time: O(1)
# Space: O(w)
#
# Description: Leetcode # 346. Moving Average from Data Stream
#
# Given a stream of integers and a window size, calcul... |
import cv2
import numpy
import queue
import string
import enchant
import pytesseract
from PIL import Image
def remove_bg(img, threshold):
"""二值化去除背景"""
img = img.convert("L") # 转灰度
pixels = img.load()
w, h = img.size
for y in range(h):
for x in range(w):
if pixels[x, y] < thre... |
# YouTube Video (Part 1): https://www.youtube.com/watch?v=4o2Eas2WqAQ&t=0s&list=PL5tcWHG-UPH1aSWALagYP2r3RMmuslcrr
# YouTube Video (Part 2): https://www.youtube.com/watch?v=x5o0XFozYnE&t=716s&list=PL5tcWHG-UPH1aSWALagYP2r3RMmuslcrr
# YouTube Video (Part 3): https://www.youtube.com/watch?v=_y43iqSJgnc&t=1s&list=PL5tcWHG... |
from datetime import datetime
from sqlalchemy import (Column,
DateTime,
ForeignKey,
Integer,
String,
Boolean,
Index)
from sqlalchemy.ext.declarative import declarative_base
fr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = []
test_requirements = [
# TODO: put package test requirements h... |
from p2pool.bitcoin import networks
from p2pool.util import math
# CHAIN_LENGTH = number of shares back client keeps
# REAL_CHAIN_LENGTH = maximum number of shares back client uses to compute payout
# REAL_CHAIN_LENGTH must always be <= CHAIN_LENGTH
# REAL_CHAIN_LENGTH must be changed in sync with all other clients
# ... |
#!/usr/bin/env python
"""
Testing a small training procedure to check that the loading and training
architecture is OK.
"""
import logging
import os
import unittest
from safire.data.loaders import MultimodalDatasetLoader
from safire.learning.interfaces.model_handle import ModelHandle
from safire.learning.models impor... |
import asyncio
import contextlib
import gc
import http.cookies
import re
import types
from unittest import mock
import pytest
from multidict import CIMultiDict, MultiDict
import aiohttp
from aiohttp import web
from aiohttp.client import ClientSession
from aiohttp.connector import BaseConnector, TCPConnector
@pytest... |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
"""Module for cycle task group model.
"""
from sqlalchemy import orm
from ggrc i... |
"""
WSGI config for lugflmembers project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... |
# this context.py should be included by all tests
# idea from http://kennethreitz.com/repository-structure-and-python.html
import os
import shutil
import sys
import tempfile
sys.path.insert(0, os.path.abspath('..'))
import gbp # noqa: E402
import gbp.log # noqa: E402
gbp.log.setup(False, False)
# the top ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.