text stringlengths 2 999k |
|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# #*** <License> ************************************************************#
# This module is part of the repository CNDB.
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# #*** </License> ***************... |
# UCF Senior Design 2017-18
# Group 38
from PIL import Image
import cv2
import imagehash
import math
import numpy as np
DIFF_THRES = 20
LIMIT = 2
RESIZE = 1000
def calc_hash(img):
"""
Calculate the wavelet hash of the image
img: (ndarray) image file
"""
# resize image if height > 1000
im... |
# Copyright 2018 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 agreed to in writing, ... |
import time
from PyQt5 import QtGui, QtCore
from ui.room_item import Ui_Form
from PyQt5.QtWidgets import QWidget
class Room_Item(QWidget,Ui_Form):
def __init__(self,parent=None,room_data=None):
super(Room_Item,self).__init__(parent)
self.setupUi(self)
self.data = room_data
self.se... |
import asyncio
import re
import sys
import traceback
import toga
from toga import Key
from .keys import toga_to_winforms_key
from .libs import Threading, WinForms, shcore, user32, win_version
from .libs.proactor import WinformsProactorEventLoop
from .window import Window
class MainWindow(Window):
def winforms_F... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
SimplePhotogrammetryRoutePlanner
A QGIS plugin
A imple photogrammetry route planner.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 14:38:20 2018
dimension reduction with VarianceThreshold using sklearn.
Feature selector that removes all low-variance features.
@author: lenovo
"""
from sklearn.feature_selection import VarianceThreshold
import numpy as np
#
np.random.seed(1)
X = np.random.randn(100, 1... |
#!/usr/bin/env python
# coding=utf-8
from my_multi_main3 import main
import numpy as np
import argparse
import time
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (defa... |
"""HDF5 related files.
This file contains a set of functions that related to read and write
HDF5 files.
Author: Yuhuang Hu
Email : duguyue100@gmail.com
"""
from __future__ import print_function, absolute_import
import h5py
from spiker import log
logger = log.get_logger("data-hdf5", log.DEBUG)
def init_hdf5(file_... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: flatbuf
import flatbuffers
class FloatingPoint(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsFloatingPoint(cls, buf, offset):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x ... |
"""[Scynced Lights]
Class attributes are "shared"
Instance attributes are not shared.
"""
def sub(x, y):
f
class Light:
pass
a = Light()
b = Ligth()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<i@binux.me>
# http://binux.me
# Created on 2012-11-14 17:09:50
from __future__ import unicode_literals, division, absolute_import
import time
import logging
from collections import deque
try:
f... |
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. 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 r... |
#!/usr/bin/env python3
UNKNOWN = -1
def read_val():
return int(input())
def read_row():
return list(map(int, input().split()))
def read_grid():
return [read_row() for _ in range(read_val())]
def make_blank_row(i):
return [UNKNOWN] * i
def make_blank_grid(n):
return [make_blank_row(i) for i in ... |
import platform
# print(platform.system())
operating_system = platform.system().lower()
if operating_system == 'darwin':
from .blender_utils_macos import get_installed_blender_versions
operating_system_name = 'macos'
elif operating_system == 'linux':
from .blender_utils_linux import get_installed_blender_... |
import functools
import random
from math import cos, pi
import cv2
import kornia
import numpy as np
import torch
from kornia.augmentation import ColorJitter
from data.util import read_img
from PIL import Image
from io import BytesIO
# Get a rough visualization of the above distribution. (Y-axis is meaningless, just... |
# This test requires CPython3.5
print(b"%%" % ())
print(b"=%d=" % 1)
print(b"=%d=%d=" % (1, 2))
print(b"=%s=" % b"str")
print(b"=%r=" % b"str")
print("PASS") |
#
# test_JpegCompression.py
#
import pytest
import albumentations as A
from .context import TfDataAugmentation as Tfda
from . import test_utils
from .test_utils import TestResult
@pytest.mark.parametrize(
"quality_lower, quality_upper, expected, message", [
# quality_lower
(-1, 100, TestResult.Er... |
import os
from torch.utils.data import DataLoader
from continuum.datasets import CIFAR10, InMemoryDataset
from continuum.datasets import MNIST
import torchvision
from continuum.scenarios import TransformationIncremental
import pytest
import numpy as np
from continuum.transforms.bg_swap import BackgroundSwap
DATA_PAT... |
# =========================================================================================
# Copyright 2015 Community Information Online Consortium (CIOC) and KCL Software Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
import django.http
import unittest.mock
from .. import middleware
def get_response(req):
# dummy get_response, just return an empty response
return django.http.HttpResponse()
def test_leaves_remote_addr_alone_if_no_real_ip():
remote_addr = object()
request = unittest.mock.MagicMock()
request.M... |
#!/usr/bin/env python
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT)
GPIO.output(21, GPIO.LOW)
time.sleep(3.00)
GPIO.output(21, GPIO.HIGH)
GPIO.cleanup()
|
from direct.directnotify.DirectNotifyGlobal import directNotify
class Notifier:
def __init__(self, name):
"""
@param name: The name of the notifier. Be sure to add it to your config/Config.prc!
@type name: str
"""
self.notify = directNotify.newCategory(name)
|
import numpy as np
def train_ml_squarer() -> None:
print("Training!")
def square() -> int:
"""Square a number...maybe"""
return np.random.randint(1, 100)
if __name__ == '__main__':
train_ml_squarer() |
"""
Platformer Game
"""
import arcade
# Constants
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
SCREEN_TITLE = "Platformer"
# Constants used to scale our sprites from their original size
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
COIN_SCALING = 0.5
SPRITE_PIXEL_SIZE = 128
GRID_PIXEL_SIZE = SPRITE_PIXEL_SIZE * TILE_SCALING
#... |
#!/usr/bin/env python3
'''
lib/ycmd/start.py
Server bootstrap logic. Includes a utility class for normalizing parameters and
calculating default ones. Also includes a helper to set up the temporary
options file.
'''
import logging
import os
import tempfile
from ..process import (
FileHandles,
Process,
)
from... |
#!/usr/bin/env python
import serial
import sys
import struct
import pprint
import argparse
import code
pp = pprint.PrettyPrinter()
class ConsoleUI:
def opStart(self, name):
sys.stdout.write(name.ljust(40))
def opProgress(self, progress, total=-1):
if (total >= 0):
prstr = "0x%04x... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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
# rights to use, copy, modify, merge, publish... |
import logging
from django.db.models.query_utils import Q
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django_filters.rest_framework import DjangoFilterBackend
from drf_yasg import openapi
from drf_yasg.openapi import Parameter
from drf_yasg.utils import no_b... |
"""Mypy style test cases for SQLAlchemy stubs and plugin."""
import os
import os.path
import sys
import pytest # type: ignore # no pytest in typeshed
from mypy.test.config import test_temp_dir
from mypy.test.data import DataDrivenTestCase, DataSuite
from mypy.test.helpers import assert_string_arrays_equal
from myp... |
#!/usr/bin/env python
# Copyright (C) 2017 The Android Open Source Project
#
# 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 b... |
# from flask import Flask, Blueprint
# from flask_sqlalchemy import SQLAlchemy
# from flask_login import LoginManager
# import os
from flask import Flask, jsonify, request, make_response, redirect, url_for
import jwt
import datetime
import os
from functools import wraps
from flask_sqlalchemy import SQLAlchemy
import u... |
# coding: utf-8
"""
An API to insert and retrieve metadata on cloud artifacts.
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1alpha1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
import re
import os
import tempfile
import six
from .. import environment
from ..console import log
from .. import util
WIN = (os.name == "nt")... |
"""
Function objects.
In PyPy there is no difference between built-in and user-defined function
objects; the difference lies in the code object found in their func_code
attribute.
"""
from pypy.rlib.unroll import unrolling_iterable
from pypy.interpreter.error import OperationError
from pypy.interpreter.baseobjspace i... |
"""Timer class based on the timeit.Timer class, but torch aware."""
import enum
import timeit
import textwrap
from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union
import numpy as np
import torch
from torch.utils.benchmark.utils import common, cpp_jit
from torch.utils.benchmark.utils._stubs imp... |
from Ranger.src.Range.Cut import Cut
class Range(object):
"""
Class used to represent a range along some 1-D domain. The range
is represented by 2 cutpoints can can be unbounded by specifying an
aboveAll or belowAll Cut.
"""
def __init__(self, lowerCut, upperCut):
""" Instantiates a Ran... |
from pyrelational.data.data_manager import GenericDataManager
|
from selfdrive.car import dbc_dict
from cereal import car
Ecu = car.CarParams.Ecu
class CarControllerParams:
ANGLE_DELTA_BP = [0., 5., 15.]
ANGLE_DELTA_V = [5., .8, .15] # windup limit
ANGLE_DELTA_VU = [5., 3.5, 0.4] # unwind limit
LKAS_MAX_TORQUE = 1 # A value of 1 is easy to overpower
... |
from .core import Core, Settings
class Download(Core):
host = 'https://artifacts.elastic.co/downloads/beats/elastic-agent/{endpoint}'
endpoint = Settings.download_endpoint
kwargs = {
'stream': True
}
def parse_response(self, response):
self.__logger.debug('Saving file to download... |
from .single_stage import SingleStageDetector
from ..registry import DETECTORS
from mmdet.core import bbox2result
import torch.nn as nn
import torch
from .. import builder
import numpy as np
import cv2
from mmdet.core import bbox2roi, bbox2result, build_assigner, build_sampler
@DETECTORS.register_module
class CSP(Sin... |
# Simple demo of sending and recieving data with the RFM95 LoRa radio.
# Author: Tony DiCola
import board
import busio
import digitalio
import adafruit_rfm9x
# Define radio parameters.
RADIO_FREQ_MHZ = 915.0 # Frequency of the radio in Mhz. Must match your
# module! Can be a value like 915.0, 433.0, etc.
# Define ... |
"""
Class to hold clinical outcome model.
Predicts probability of good outcome of patient(s) or group(s) of patients.
Call `calculate_outcome_for_all(args)` from outside of the object
Inputs
======
All inputs take np arrays (for multiple groups of patients).
mimic: proportion of patients with stroke mimic
ich: pro... |
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url
from djangopypi.feeds import ReleaseFeed
urlpatterns = patterns("djangopypi.views",
url(r'^$', "root", name="djangopypi-root"),
url(r'^packages/$','packages.index', name='djangopypi-package-index'),
url(r'^simple/$','packages.simpl... |
import pandas as pd
from pandas.compat import StringIO
import numpy
numpy.set_printoptions(threshold=numpy.nan)
def main():
df = pd.read_csv(StringIO(earnings), sep=",", header=None,
names=['symbol', 'exchange', 'eps_pct_diff_surp', 'asof_date'])
df = df.sort_values(by=['asof_date'])
... |
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# 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 applicabl... |
from PIL import ImageChops, Image as PILImage
from http.client import HTTPConnection
from time import sleep
from traceback import format_stack, print_exc
def Tint(image, color):
return ImageChops.blend(image, PILImage.new('RGB', image.size, color), 0.36)
def GetStatusCode(host, path="/"):
""" This function r... |
# Copyright 2016 Quantopian, 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 required by applicable law or agreed to in writ... |
import requests
API_URL = 'https://secure.techfortesco.com/tescolabsapi/restservice.aspx'
class TescoLabsApi(object):
def __init__(self, url, developerkey, applicationkey):
self.url = url
self.developerkey = developerkey
self.applicationkey = applicationkey
res = requests.get(self... |
# Generated by Django 3.2.12 on 2022-03-21 09:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0002_tag'),
]
operations = [
migrations.AddField(
model_name='item',
name='tags',
field=mode... |
#
# Licensed to the Apache Software Foundation (ASF) 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... |
# =======================================================================================================================================
# VNU-HCM, University of Science
# Department Computer Science, Faculty of Information Technology
# Authors: Nhut-Nam Le (Tich Phan Suy Rong)
# © 2020
import unittest
"""
Given tw... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributi... |
import os
from dotenv import load_dotenv
load_dotenv()
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://fidel:fidel@localhost/blog'
UPLOADED_PHOTOS_DEST = 'app/static/photos'
QUOTES_URL = 'http://quotes.stormconsultancy.co.uk/random.json'
MAIL... |
_TF_INCLUDE_PATH = "TF_INCLUDE_PATH"
_TF_LIB_PATH = "TF_LIB_PATH"
def _get_env_var_with_default(repository_ctx, env_var):
"""Returns evironment variable value."""
if env_var in repository_ctx.os.environ:
value = repository_ctx.os.environ[env_var]
return value
else:
fail("Environment variable '%s' was... |
import yaml
from os import path
from netmiko import ConnectHandler
home_dir = path.expanduser("~")
filename = path.join(home_dir, ".netmiko.yml")
with open(filename) as f:
yaml_out = yaml.safe_load(f)
cisco3 = yaml_out["cisco3"]
net_connect = ConnectHandler(**cisco3)
print()
print(net_connect.find_prompt())
pr... |
# -*- coding: iso-8859-1 -*-
|
# Copyright 1999-2017 Tencent Ltd.
#
# 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 writ... |
"""Support for ICS Calendar."""
import copy
import logging
from datetime import datetime, timedelta
from urllib.error import ContentTooShortError, HTTPError, URLError
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
HTTPBasicAuthHandler,
HTTPDigestAuthHandler,
build_opener,
install_open... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import json
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationE... |
from arm.logicnode.arm_nodes import *
class SetTransformNode(ArmLogicTreeNode):
"""Use to set the transform of an object."""
bl_idname = 'LNSetTransformNode'
bl_label = 'Set Object Transform'
arm_version = 1
def init(self, context):
super(SetTransformNode, self).init(context)
self.... |
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2021 Jose David M. for circuitpython
#
# SPDX-License-Identifier: MIT
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sample... |
from ssmpfwd.helpers import verify_plugin_version, verbose_debug_quiet, time_decorator
from unittest.mock import MagicMock, patch
import unittest
class TestVerifyPluginVersion(unittest.TestCase):
@patch("ssmpfwd.helpers.subprocess")
def test_verify_plugin_version_success(self, mock_subprocess):
... |
import numpy as np
import matplotlib.pyplot as plt
import pint
# Use the same registry
from main import ureg
ureg.setup_matplotlib(True)
from uncertainties import ufloat, umath, unumpy
import pandas as pd
from scipy.signal import find_peaks
from scipy.integrate import simpson
from scipy.optimize import curve_fit
plt.rc... |
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
from get_secrets import *
def main():
resp = MessagingResponse()
resp.message ("You have reached the DogBot. Thanks for contacting us :)")
return str(resp)
if __name__ == "__main__":
main()
|
from __future__ import annotations
from enum import IntEnum
class Algorithm(IntEnum):
"""
https://developers.yubico.com/YubiHSM2/Concepts/Algorithms.html
"""
RSA_PKCS1_SHA1 = 1
RSA_PKCS1_SHA256 = 2
RSA_PKCS1_SHA384 = 3
RSA_PKCS1_SHA512 = 4
RSA_PSS_SHA1 = 5
RSA_PSS_SHA256 = 6
... |
import unittest.mock
from functools import partial
import bokeh.core.properties as bp
import param
import pytest
from bokeh.document import Document
from bokeh.io.doc import patch_curdoc
from bokeh.models import Div
from panel.layout import Tabs, WidgetBox
from panel.reactive import Reactive, ReactiveHTML
from pane... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
import unittest
from hydrus.core import HydrusConstants as HC
from hydrus.core import HydrusData
from hydrus.core import HydrusSerialisable
from hydrus.client import ClientApplicationCommand as CAC
from hydrus.client import ClientConstants as CC
from hydrus.client import ClientData
from hydrus.client import ClientDef... |
import requests
import json
import time
import random
from . import conf, data, lang
from inukit.timestamp import natural_date, natural_time, timestamp_now
def is_same_day(ts1, ts2) -> bool:
def d(ts):
return natural_date(ts, '%Y-%m-%d')
return d(ts1) == d(ts2)
def handle_morning(qq):
last_morning... |
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 2.1.15.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Bu... |
#!/usr/bin/env python3
'''Test config updates '''
# ------------------------------------------------------------------------------
# Imports
# ------------------------------------------------------------------------------
import subprocess
import os
import json
import time
import datetime
import requests
import pytest
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import find_packages, setup
test_requirements = [
"black>=19.10b0",
"flake8>=3.8.3",
"flake8-debugger>=3.2.1",
]
dev_requirements = [
*test_requirements,
"wheel>=0.34.2",
]
requirements = [
"cdp-backend[pi... |
from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.selector import XmlXPathSelector
from openrecipes.spiders.elanaspantry_spider import ElanaspantryMixin
class ElanaspantryfeedSpider(BaseSpider, ElanaspantryMixin):
name = "elanaspantry.feed"
allowed_domains = [
"www.elana... |
#!/usr/bin/env python
#-*- encoding: UTF-8 -*-
###############################################
# Todos los derechos reservados a: #
# CreceLibre Consultores en Tecnologías Ltda. #
# #
# ©Milton Inostroza Aguilera #
# minostro@minostro.com ... |
"""Train (basic) densely-connected oracle."""
import os
import time
import multiprocessing as mp
import pandas as pd
import torch
from torch import optim
from torch.utils.data import DataLoader, Subset, TensorDataset, WeightedRandomSampler
from profit.dataset.splitters import split_method_dict
from profit.models.to... |
# -*- 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... |
import numpy as np
from skimage.morphology import max_tree, area_closing, area_opening
from skimage.morphology import max_tree_local_maxima, diameter_opening
from skimage.morphology import diameter_closing
from skimage.util import invert
from skimage._shared.testing import assert_array_equal, TestCase
eps = 1e-12
d... |
import logging
import os
from pathlib import Path
from typing import Any, Callable, Optional
from torch.utils.data import Dataset
from torchvision import transforms
from PIL import Image
import cv2
import numpy as np
class URISC(Dataset):
def __init__(
self,
dir: str,
mode: str = 'trai... |
# Copyright (C) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, check out LICENSE.md
import torch.nn as nn
class FeatureMatchingLoss(nn.Module):
r"""Compute feature matching loss"""
def __ini... |
# Copyright 2017 Datera
# 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 applic... |
#!/usr/bin/env python
"""
Author: Alexander David Leech
Date: 30/09/2015
Rev: 2
Lang: Python 2.7
Deps: Pyserial, Pymodbus, logging
"""
import time # For sleep functionality
import logging # For detailed error output
from pymodbus... |
import os
import subprocess
from unittest import mock
import pytest
from pre_commit.constants import VERSION as PRE_COMMIT_VERSION
import testing.git
from all_repos import autofix_lib
from all_repos import clone
from all_repos import git
from all_repos.config import load_config
@pytest.mark.parametrize(
('cli_r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Generate random usernames in
"""
import random
from .names import names as default_names
class NameGenerator(object):
def __init__(self, names=None):
self.names = names or default_names
def __call__(self):
return self.names.pop(rando... |
from django.utils import timezone
from rest_framework.authtoken.models import Token
class AuthTokenHandler:
"""
Handles variations in auth token
"""
@staticmethod
def expired_token(auth_token):
"""
Checks expiry of auth token
"""
utc_now = timezone.now()
exp... |
from .useful_functions import get_ngrams, words_to_ngrams_list, remove_hook_words, remove_words
from .transformers import phrases_transform, phrases2lower, phrases_without_excess_symbols
from .tokenizers import text2sentences, split_by_words, sentence_split
from .stemlem_operators import create_stemmer_lemmer, cre... |
# internal imports
import dependency_checker
import dependency_installer
import dependency_updater
import logger
from rendering import VortexWindow
# external imports
import pyglet
import sys
# check if python version is too old. If it is, exit.
if sys.version_info < (3, 6): # if python version is less than 3.6
... |
"""
Intergation of the pytorch_transformers openai and gpt2 modules.
Note that these objects are only to be used to load
pretrained models. The pytorch-transformers library
wasn't designed to train these models from scratch.
"""
import pytorch_transformers as pt
from flambe.nlp.transformers.utils import Transformer... |
#
# Copyright 2018 Analytics Zoo Authors.
#
# 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... |
from src.layers.LayerHelper import *
from settings import LayerSettings as layerSettings
import tensorflow as tf
import os
CUDA_VISIBLE_DEVICES=0
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # set gpu number
def LSTM(name_, inputTensor_, numberOfOutputs_, isTraining_, dropoutProb_=None):
with tf.name_scope(name_):
cell... |
#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describe... |
"""LCM type definitions
This file automatically generated by lcm.
DO NOT MODIFY BY HAND!!!!
"""
import cStringIO as StringIO
import struct
class request_t(object):
__slots__ = ["utime"]
def __init__(self):
self.utime = 0
def encode(self):
buf = StringIO.StringIO()
buf.write(reque... |
from conans import ConanFile, CMake
import os
channel = os.getenv("CONAN_CHANNEL", "testing")
username = os.getenv("CONAN_USERNAME", "memsharded")
class EasyLoggingTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "easyloggingpp/9.94.1@%s/%s" % (username, channel)
generato... |
# Author: Guilherme Aldeia
# Contact: guilherme.aldeia@ufabc.edu.br
# Version: 1.0.1
# Last modified: 06-07-2021 by Guilherme Aldeia
"""Interaction Transformation expression's **Inspector**
Sub-module containing three classes to help inspect and explain the
results obtained with the itea.
- ``ITExpr_exp... |
# write your first unittest!
import unittest
from ovos_plugin_manager.skills import find_skill_plugins
class TestPlugin(unittest.TestCase):
@classmethod
def setUpClass(self):
self.skill_id = "ovos-skill-timer.OpenVoiceOS"
def test_find_plugin(self):
plugins = find_skill_plugins()
... |
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU
from keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from keras.mo... |
import pytest
from brownie import interface
def test_uniswap_add_two_tokens(
admin, alice, chain, bank, werc20, ufactory, urouter, simple_oracle, oracle, celo, cusd, ceur, UniswapV2SpellV1, UniswapV2Oracle, core_oracle
):
spell = UniswapV2SpellV1.deploy(bank, werc20, urouter, celo, {'from': admin})
cusd.m... |
"""
This module patches a few core functions to add compression capabilities,
since gevent-websocket does not appear to be maintained anymore.
"""
from socket import error
from zlib import (
decompressobj,
MAX_WBITS,
Z_FULL_FLUSH,
)
from geventwebsocket.exceptions import (
ProtocolError,
WebSocketE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.