content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# -*- coding: utf-8 -*-
"""
celery cli services module.
"""
from pyrin.application.services import get_component
from pyrin.task_queues.celery.cli import CeleryCLIPackage
def register_cli_handler(instance, **options):
"""
registers a new celery cli handler or replaces the existing one.
if `replace=True`... | python |
# -*- coding: utf-8 -*-
#
# This file is part of the pyFDA project hosted at https://github.com/chipmuenk/pyfda
#
# Copyright © pyFDA Project Contributors
# Licensed under the terms of the MIT License
# (see file LICENSE in root directory for details)
"""
Create a tabbed widget for all plot subwidgets in the list ``fb... | python |
'''
* Capítulo 05: Pré-processamento
5.2 Histograma de Cores
> Equalização de histograma
'''
import cv2
from matplotlib import pyplot as grafico
imagemOriginal = cv2.imread("maquina.jpg", 0)
imagemEqualizada = cv2.equalizeHist(imagemOriginal)
cv2.imshow("Imagem Original", imagemOriginal)
cv... | python |
__author__ = 'lucabasa'
__version__ = '1.1.0'
__status__ = 'development'
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipe... | python |
"""
Simulates the initial state discrimination experiment using different
methods, to compare the resulting error rates.
"""
import torch
from perm_hmm.util import num_to_data
from perm_hmm.postprocessing import ExactPostprocessor, EmpiricalPostprocessor
from perm_hmm.classifiers.perm_classifier import PermClassifier... | python |
import json
import pickle
import pandas as pd
from decimal import Decimal
from django.db.models import Avg
from recommender.models import Rating
from scripts.recommenders.base_recommender import BaseRecommender
class SVDRecommender(BaseRecommender):
def __init__(self, save_path='./models/SVD/model/'):
se... | python |
import ast
from PythonVoiceCodingPlugin.library import nearest_node_from_offset,sorted_by_source_region,get_source_region,node_from_range,make_flat
from PythonVoiceCodingPlugin.library.info import *
from PythonVoiceCodingPlugin.library.LCA import LCA
from PythonVoiceCodingPlugin.library.level_info import LevelVisitor
... | python |
def get_current_admin():
def decorator(func):
setattr(func, 'get_current_admin', True)
return func
return decorator | python |
"""D-Bus interface for rauc."""
from enum import Enum
import logging
from typing import Optional
from ..exceptions import DBusError, DBusInterfaceError
from ..utils.gdbus import DBus
from .interface import DBusInterface
from .utils import dbus_connected
_LOGGER: logging.Logger = logging.getLogger(__name__)
DBUS_NAME... | python |
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common import debug
from nfv_vim.rpc._rpc_defs import RPC_MSG_RESULT
from nfv_vim.rpc._rpc_defs import RPC_MSG_TYPE
from nfv_vim.rpc._rpc_defs import RPC_MSG_VERSION
from nfv_vim.rpc._rpc_message import RPCMessage
... | python |
#!/usr/bin/env python
"""Tests for util.py."""
import datetime
import logging
import os
import sys
import unittest
# Fix up paths for running tests.
sys.path.insert(0, "../src/")
from pipeline import util
from google.appengine.api import taskqueue
class JsonSerializationTest(unittest.TestCase):
"""Test custom j... | python |
/home/runner/.cache/pip/pool/88/20/06/e25d76d7065f6488098440d13a701a2dc1acbe52cd8d7322b4405f3996 | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2002-2019 "Neo4j,"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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 L... | python |
import ast
import sys
class EnvVisitor(ast.NodeVisitor):
def __init__(self):
self.optional_environment_variables = set()
self.required_environment_variables = set()
def parse_and_visit(self, body, filename=''):
doc = ast.parse(body, filename=filename)
return self.visit(doc)
... | python |
#!/usr/bin/python
# __*__ coding: utf8 __*__
oneline = "Read, write and operate with models"
#import os
from model_base import model_base
# --------------------------------------------------------------------
class Free_class:
pass
def bound(x, y):
if x > y/2.: return x-y
if x < -y/2. : return x+y
return x
#=... | python |
import configparser
import datetime
import os
import time
#import xml.etree.ElementTree as ET
import lxml.etree as ET
from io import StringIO, BytesIO
from shutil import copyfile
import requests
from requests.auth import HTTPDigestAuth
from subprocess import Popen
print("Hikvision alert started")
# CONFIGS START
conf... | python |
from project import app
if __name__ == "__main__":
app.run(debug = True, host = "0.0.0.0") | python |
"""
An emulation of the Window class, for injecting pane data into tests
"""
from tmux_session_utils.tmux_utils import (
inject_pane_data,
WINDOW_ID_VARIABLE,
WINDOW_LAYOUT_VARIABLE,
)
class FakeWindow:
"""
Represents a window in a tmux session, for test injection
"""
def __init__(self, ... | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | python |
from app import app
import sys, getopt, json
def clear_file(file_name):
with open(file_name, 'w') as filep:
json.dump({}, filep)
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv, "c", ["clear"])
except getopt.GetoptError:
print('python webapp.py [-c or --clear fo... | python |
import os
import sys
import time
import random
import string
import argparse
from collections import namedtuple
import copy
import torch
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import torch.optim as optim
import torch.utils.data
from torch import autograd
import torch.multiprocessing as mp
im... | python |
import logging
from huobi.connection.impl.websocket_watchdog import WebSocketWatchDog
from huobi.connection.impl.websocket_manage import WebsocketManage
from huobi.connection.impl.websocket_request import WebsocketRequest
from huobi.constant.system import WebSocketDefine, ApiVersion
class SubscribeClient(object):
... | python |
import numpy as np
from seisflows.tools import unix
from seisflows.tools.array import loadnpy, savenpy
from seisflows.tools.code import exists
from seisflows.tools.config import SeisflowsParameters, SeisflowsPaths, \
loadclass, ParameterError
PAR = SeisflowsParameters()
PATH = SeisflowsPaths()
import solver
imp... | python |
from jsonobject import JsonObject
from taxjar.data.float_property import TaxJarFloatProperty
class TaxJarBreakdownLineItem(JsonObject):
# NB: can return either string or integer
# `id` is a valid property, but isn't enforced here
# id = StringProperty()
taxable_amount = TaxJarFloatProperty()
tax_c... | python |
import abjad
import consort
from abjad.tools import durationtools
from abjad.tools import rhythmmakertools
from abjad.tools import systemtools
from abjad.tools import templatetools
from abjad.tools import timespantools
layer = 1
score_template = templatetools.StringOrchestraScoreTemplate(
violin_count=2,
viola... | python |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Error module tests."""
from __future__ import absolute_import, print_function
im... | python |
from OwlveyGateway import OwlveyGateway
from datetime import datetime, timedelta
import pandas as pd
import random
import math
if __name__ == "__main__":
client_id = "CF4A9ED44148438A99919FF285D8B48D"
secret_key = "0da45603-282a-4fa6-a20b-2d4c3f2a2127"
owlvey = OwlveyGateway("http://localhost:50001","htt... | python |
# carve.py
# Wed May 9 14:18:46 IST 2018
from __future__ import print_function
import sys
def main(source, start, end, dest):
# type: (str, int, int, str) -> None
with open(source, 'rb') as sf:
sf.seek(start)
byte_str = sf.read(end)
with open(dest, 'wb') as df:
df.write(byte_str... | python |
from direct.showbase import PythonUtil
from toontown.toonbase import ToontownGlobals
from toontown.hood import ZoneUtil
from random import choice
latencyTolerance = 10.0
MaxLoadTime = 40.0
rulesDuration = 21
JellybeanTrolleyHolidayScoreMultiplier = 2
DifficultyOverrideMult = int(1 << 16)
def QuantizeDifficultyOverride... | python |
# -*- coding: utf-8 -*-
"""Forms module."""
from django import forms
class UploadFileForm(forms.Form):
file = forms.FileField()
def __init__(self, *args, **kwargs):
super(UploadFileForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.at... | python |
import logging
import copy
import time
import os
import sys
import numpy as np
import math
import functools
import mxnet as mx
from mxnet import context as ctx
from mxnet.initializer import Uniform
from mxnet.module.base_module import BaseModule
from mxnet.module.module import Module
from mxnet import metric
from mxne... | python |
import functools
import json
from flask import request, session, url_for
from flask_restplus import Namespace, Resource
from CTFd.models import Users, db
from CTFd.plugins import bypass_csrf_protection
from CTFd.utils import validators, config, email, get_app_config, get_config, user as current_user
from CTFd.utils.co... | python |
from typing import Dict
class Song:
def __init__(self, lyrics: str, artist: str, yt_link: str):
self._lyrics = lyrics
self._artist = artist
self._yt_link = yt_link
@staticmethod
def new(data: Dict):
return Song(lyrics=data['lyrics'], artist=data['artist'], yt_link=data['yt... | python |
"""
Generate NSR and NSW compounds for all methods across all cell lines
Generate a list of NSR, NSW, NSR but not NSW and NSW but not NSR targets
hitting all cell lines, and detected using all analysis methods - as given in
Sup. tables 2,4,5, and 6.
HERE FOR COMPLETENESS - NO OUTPUT AS NOTHING MEETS THE CRITERIA.
"""... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Charles Vanwynsberghe
# Pyworld2 is a Python implementation of the World2 model designed by Jay W.
# Forrester, and thouroughly described in the book World Dynamics (1971). It
# is written for educational and research purposes.
# Pyworld2 is forked from the Software... | python |
# coding:utf-8
#!/usr/bin/python
#
# Copyright (c) Contributors to the Open 3D Engine Project.
# For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
#
# ------------------------------------------------------------------------... | python |
#
# Name: CountBookmarks.py
#
# Purpose: To count the bookmarks in each folder and subfolder of a bookmarks file exported by a web browser. The output file that
# this program generates can be imported into a spreadsheet and sorted to show the relative size of all your bookmark folders.
#
# Inputs: This program require... | python |
# -*- coding:utf8 -*-
# File : neural_stype_opr.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 2/27/17
#
# This file is part of TensorArtist.
import numpy as np
from tartist.nn import opr as O
def get_content_loss(p, x):
c = p.shape[3]
n = p.shape[1] * p.shape[2]
loss = (1. / (2... | python |
#Simule u caixa eletrónico com cédulas de 50,20,10 e 1
#Banco CEV
#Pergunte o valor que você quer sacar
#Total de {} cédulas de 50;Total de {} cedulas de 10 e Total de {} cédulas de 1
print('='*20)
print('Banco cev')
print('='*20)
valor = int(input('Quanto você quer sacar ?'))
total = valor
céd = 50
totcéd = 0
while T... | python |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.11.2)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x23\x70\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x83\x... | python |
from .alembic_current import AlembicCurrent
from .alembic_downgrade import AlembicDowngrade
from .alembic_history import AlembicHistory
from .alembic_init import AlembicInit
from .alembic_migrate import AlembicMigrate
from .alembic_show import AlembicShow
from .alembic_stamp import AlembicStamp
from .alembic_upgrade im... | python |
#from django.db import models
class CreditCard():
def __init__ (self,
full_credit_card_number = '',
major_industry_identifier = 0,
issuer_identification_number = 0,
personal_account_number = 0,
check_digit = 0,
issuer = 'Unkown',
... | python |
#!/usr/bin/env python
import io
import os
import re
from setuptools import setup, find_packages
file_dir = os.path.dirname(__file__)
def read(path, encoding='utf-8'):
path = os.path.join(os.path.dirname(__file__), path)
with io.open(path, encoding=encoding) as fp:
return fp.read()
def version(path... | python |
#
# PySNMP MIB module HUAWEI-LswMAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-LswMAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:34:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | python |
import os
import subprocess
import sys
kolibri_dir = os.path.abspath(os.path.join('src', 'kolibri'))
win_dir = os.path.abspath(os.path.join('dist', 'win', 'Kolibri'))
kolibri_dest_dir = os.path.join(win_dir, 'kolibri')
from .version import get_env_with_version_set
def do_build(args):
if 'android' in args and '-... | python |
total = totmil = cont = menor = 0
barato = ''
while True:
produto = str(input('Nome do produto: '))
preco = float(input('Preço: '))
cont += 1
total += preco
if preco > 1000:
totmil += 1
if cont == 1 or preco < menor:
menor = preco
barato = produto
resposta = ' '
... | python |
import uuid
import os
import traceback
import flask
import urllib, json
import logging
import jsonschema
class FlaskHelper():
def __init__(self, port=None):
self.session = {}
self.server = flask.Flask(__name__)
self.port = port if port else os.environ["PORT"]
def route(self, u... | python |
#
# Copyright 2019 Xilinx 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 writing... | python |
#!/usr/bin/env python
# Copyright 2019 Juliane Mai - juliane.mai(at)uwaterloo.ca
#
# License
# This file is part of the EEE code library for "Computationally inexpensive identification
# of noninformative model parameters by sequential screening: Efficient Elementary Effects (EEE)".
#
# The EEE code library is free so... | python |
from django.contrib import admin
from django.utils.html import mark_safe
# Register your models here.
from .models import Product, Collection, ProductImage
from .forms import RequiredInlineFormSet
class ProductImageAdmin(admin.StackedInline):
model = ProductImage
readonly_fields = ['image_tag']
formset =... | python |
import os
import yaml
_dirname = os.path.dirname(os.path.abspath(__file__))
def load_config(filename):
with open(os.path.join(_dirname, filename)) as file:
config = yaml.load(file, Loader=yaml.FullLoader)
return config
| python |
'''keyvault.py - azurerm functions for the Microsoft.Keyvault resource provider'''
import datetime
import json
from .restfns import do_delete, do_get, do_get_next, do_put, do_post
from .subfns import list_tenants
from .settings import get_rm_endpoint, KEYVAULT_API
def create_keyvault(access_token, subscription_id, rg... | python |
"""
I don't know how much you know already, so I'm assuming you know little
to no Python. This is a multi-line comment, denoted by the three quotation
marks above and below this. Single line and inline comments start with #.
Let's start basic - "print" will send words into the console.
"""
print("Hello! Reddit bot ... | python |
class Resource(object):
def __init__(self, sigfox, resource):
self.sigfox = sigfox
self.resource = resource
def retrieve(self, id="", query=""):
""" Retrieve a list of <resources> according to visibility permissions
and request filters or Retrieve information about a given
... | python |
import os
import time
DEBUG = False
DEFINE = '#define RADIXJOIN_COUNT (size_t) {}*1024\n'
HEADINGSTIMER = ["Tuples", "CollLeft","PartLeft", "CollRight", "PartRight", "SettPart", "SettRedPart", "BuildKey", "BuildVal", "ProbeKey", "ProbAndBuildTup", "Append", "BuildHT", "ProbeHT", "PerfBuildProb", "Runtime", "Complete",... | python |
# O(nlog(n)) time | O(log(n)) space
def quickSort(array):
quickSortHelper(array, 0, len(array) - 1)
return array
def quickSortHelper(array, startIdx, endIdx):
if startIdx >= endIdx:
return
pivotIdx = startIdx
leftIdx = startIdx + 1
rightIdx = endIdx
while rightIdx >= leftIdx:
... | python |
from math import factorial
l = []
for i in range(1,100+1):
l.append(1/i)
print('Suma:',sum(l))
print()
print('Wartość minimalna:',min(l))
print()
print('Wartość maksymalna:',max(l))
silnia = factorial(1000)
lz = list(str(silnia))
lz2 = []
for i in range(len(lz)):
lz2.append(int(lz[i]))
print()
print('Sum... | python |
#!/usr/bin/env python
import argparse
import sys
import numpy as np
import tensorflow as tf
import librosa
import config
import model
from IPython.lib.display import Audio
parser = argparse.ArgumentParser(description='Train song embeddings.')
parser.add_argument('--config', '-c', required=True, help='Config file')... | python |
# Generated by Django 3.1.1 on 2021-01-12 16:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Account",
fields=[
(
"id",
... | python |
from systems.commands.index import Command
from systems.manage.task import channel_communication_key
from utility.data import normalize_value, dump_json
from utility.time import Time
class Send(Command('send')):
def exec(self):
if not self.check_channel_permission():
self.error("You do not ha... | python |
import numpy as np
class MeanSquaredError():
def __call__(self, y, y_pred):
self.last_y_pred = y_pred
self.last_y = y
assert y_pred.shape == y.shape
self.last_loss = np.sum(np.square(y-y_pred), axis=0)/y_pred.shape[0]
return self.last_loss
def gradient(self):
... | python |
import unittest
import os
import wikipedia
from programy.services.wikipediaservice import WikipediaService
from programytest.aiml_tests.client import TestClient
class MockWikipediaAPI(object):
DISAMBIGUATIONERROR = 1
PAGEERROR = 2
GENERALEXCEPTION = 3
def __init__(self, response=None, throw_except... | python |
#!/usr/bin/python3
# This file is part of becalm-station
# https://github.com/idatis-org/becalm-station
# Copyright: Copyright (C) 2020 Enrique Melero <enrique.melero@gmail.com>
# License: Apache License Version 2.0, January 2004
# The full text of the Apache License is available here
# http://... | python |
class Car:
def __init__(self,marka,model,god,speed=0):
self.marka=marka
self.model=model
self.god=god
self.speed=speed
def speed_up(self):
self.speed+=5
def speed_down(self):
self.speed-=5
def speed_stop(self):
self.speed=0
def print_speed(... | python |
import unittest
from app.models import User,Comment,Blog,Subscriber
class UserModelTest(unittest.TestCase):
def setUp(self):
self.new_user = User(password='blog')
def test_password_setter(self):
self.assertTrue(self.new_user.pass_secure is not None)
def test_no_access_password(self):
... | python |
#!/usr/bin/env python
"""
Example of a 'dynamic' prompt. On that shows the current time in the prompt.
"""
from prompt_toolkit import CommandLineInterface
from prompt_toolkit.layout import Layout
from prompt_toolkit.layout.prompt import Prompt
from pygments.token import Token
import datetime
import time
class ClockP... | python |
from django.shortcuts import render
def page_not_found(request, exception):
return render(request, 'error_handling/404.html') | python |
'''
Flask app for Juncture site.
Dependencies: bs4 Flask Flask-Cors html5lib requests
'''
import os, logging
from flask import Flask, request, send_from_directory
from flask_cors import CORS
import requests
logging.getLogger('requests').setLevel(logging.WARNING)
app = Flask(__name__)
CORS(app)
from bs4 import Beau... | python |
from zone_api import platform_encapsulator as pe
from zone_api.core.devices.illuminance_sensor import IlluminanceSensor
from zone_api_test.core.device_test import DeviceTest
class IlluminanceSensorTest(DeviceTest):
""" Unit tests for illuminance_sensor.py. """
def setUp(self):
self.item = pe.create_... | python |
import itertools
import demistomock as demisto # noqa: F401
import geopy.distance
from CommonServerPython import * # noqa: F401
requests.packages.urllib3.disable_warnings()
def get_distances_list(src_coords_list: list, events_dict: dict):
distance_list = []
for unique_pair in itertools.combinations(src_c... | python |
# Copyright (c) 2021 PaddlePaddle 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 appl... | python |
from abc import ABC
import numpy
import torch
import torch.distributions as D
import numpy as np
from distributions.BaseDistribution import Plottable2DDistribution
class RotationDistribution(Plottable2DDistribution):
def __init__(self, skewness, n, mean=7):
self.d = 2
self.dimension = 2
... | python |
#!/usr/bin/env python
# coding: utf-8
# # QuakeMigrate - Example - Icequake detection
# ## Overview:
# This notebook shows how to run QuakeMigrate for icequake detection, using a 2 minute window of continuous seismic data from Hudson et al (2019). Please refer to this paper for details and justification of the setti... | python |
class MyClass:
# Class variable
cvar = 'a'
def __init__(self, num=0):
# Instance variable
self.ivar = num
def __repr__(self):
return f'MyClass({self.ivar})'
def method(self):
# Normal class method - requires instance
# Operates within instance namespace
... | python |
# -*- coding: utf-8 -*-
# Description: PHP-FPM netdata python.d module
# Author: Pawel Krupa (paulfantom)
from base import UrlService
import json
# default module values (can be overridden per job in `config`)
# update_every = 2
priority = 60000
retries = 60
# default job configuration (overridden by python.d.plugin... | python |
import os
from typing import List, Sequence, Any
import numpy as np
from restools.flow_stats import Ensemble, BadEnsemble
from papers.jfm2020_probabilistic_protocol.data import RPInfo
class DistributionSummary:
def __init__(self):
self.means = []
self.lower_quartiles = []
self.upper_quar... | python |
import numpy as np
def generate_features(implementation_version, draw_graphs, raw_data, axes, sampling_freq, scale_axes):
# features is a 1D array, reshape so we have a matrix
raw_data = raw_data.reshape(int(len(raw_data) / len(axes)), len(axes))
features = []
graphs = []
# split out the data fro... | python |
import os.path
import subprocess
from .steps import ImagesStep
from common_utils.exceptions import ZCItoolsValueError
from common_utils.data_types.correlation_matrix import CorrelationMatrix
from common_utils.file_utils import ensure_directory, write_str_in_file, get_settings
_circos_conf = """
<colors>
{colors}
</col... | python |
import pyCardDeck
from typing import List
class Gamer:
def __init__(self, name: str):
self.hand = []
self.name = name
def __str__(self):
return self.name
class GamePlace:
def __init__(self, gamers: List[Gamer]):
self.deck = pyCardDeck.Deck(
cards=generate_de... | python |
#coding:utf-8
#created by Philip_Gao
import tensorflow as tf
from mnv3_layers import *
def mobilenetv3_small(inputs, num_classes, is_train=True):
reduction_ratio = 4
with tf.variable_scope('mobilenetv3_small'):
net = conv2d_block(inputs, 16, 3, 2, is_train, name='conv1_1',h_swish=True) # size/2
... | python |
import math
import torch
from torch import nn
from ..wdtypes import *
class Wide(nn.Module):
r"""Wide component
Linear model implemented via an Embedding layer connected to the output
neuron(s).
Parameters
-----------
wide_dim: int
size of the Embedding layer. `wide_dim` is the sum... | python |
from torch import nn
from IAF.layers.utils import accumulate_kl_div
import IAF.layers as layers
import torch
def test_accumulate_kl_div():
class Model(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.Sequential(
layers.LinearVariational(1, 1, 1), ... | python |
from __future__ import generator_stop
from __future__ import annotations
from .collision.Avoidance import CollisionAvoidance
from .pub_sub.AMQP import PubSubAMQP
__all__ = [
'CollisionAvoidance',
'PubSubAMQP'
]
__version__ = '0.9.0'
| python |
from string import printable
from pylexers.RegularExpressions.BaseRegularExpressions import (
_EmptySet,
_Epsilon,
_Symbol,
_Or,
_Concat,
_Star,
)
from pylexers.RegularExpressions.BaseRegularExpressions import _RegularExpression
"""
Basic Regular Expressions
"""
class EmptySet(_EmptySet):
... | python |
from __future__ import division, print_function
import numpy as np
class OnlineStatistics(object):
def __init__(self, axis=0):
self.axis = axis
self.n = None
self.s = None
self.s2 = None
self.reset()
def reset(self):
self.n = 0
self.s = 0.0
sel... | python |
from PyQt4 import QtGui, QtCore
import sys
sys.path.append('../')
import Code.configuration as cf
import Code.Engine as Engine
# So that the code basically starts looking in the parent directory
Engine.engine_constants['home'] = '../'
import Code.GlobalConstants as GC
import Code.SaveLoad as SaveLoad
impor... | python |
"""Build V8 extension with Cython."""
from Cython.Build import cythonize
from distutils.command.build import build
from setuptools import setup
from setuptools.extension import Extension
import buildtools
#
# NOTE: You will need to add these to the build_ext command:
#
# --include-dirs "${V8}/include"
# --libra... | python |
from django import forms
# from django.core.validators import DecimalValidator
from django.db.models.functions import Concat, Substr,Length,Cast
from django.db.models import Func, CharField, F,Value,IntegerField
from .models import Part, PartClass, Manufacturer, Subpart, Seller
from .validators import decimal, alphan... | python |
from fastapi import APIRouter, FastAPI, Request
from ..models import Request as RequestModel
router = APIRouter()
@router.get("/_version")
def get_version(request: Request) -> dict:
return dict(version=request.app.version)
@router.get("/_status")
async def get_status() -> dict:
await RequestModel.query.g... | python |
import os
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
from MailLoader import ImapConnector
import requests
import json
app = Flask(__name__)
api = Api(app)
settings = {
'imap_server': 'imap.gmail.com',
'ProcessorAgent': 'http://procagent.antispam-msu.site/fit-model',
}
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 1 13:57:09 2019
@author: Tom
"""
import sys
import json
import logging
import configparser
import pprint
from datetime import datetime
from typing import Dict
import requests
import send_gmail
INAT_NODE_API_BASE_URL = "https://api.inaturalist.or... | python |
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 The Pybricks Authors
"""Resource files.
These resources are intended to be used with the standard ``importlib.resources``
module.
"""
UDEV_RULES = "99-pybricksdev.rules"
"""Linux udev rules file name."""
DFU_UTIL_EXE = "dfu-util.exe"
"""Windows version of dfu-util... | python |
from django.conf.urls import include, url
from rest_framework import routers
# from django.conf import settings
from . import views
router = routers.DefaultRouter()
# router.register(r'gamesession', views.GameSessionViewSet)
router.register(r"event", views.EventViewSet)
router.register(r"players", views.PlayerViewSet... | python |
from app.core.crud import CrudView
class ProjectView(CrudView):
pass
| python |
#
# Copyright 2011, Kristofer Hallin (kristofer.hallin@gmail.com)
#
# Mermaid, IRC bot written by Kristofer Hallin
# kristofer.hallin@gmail.com
#
import socket
import select
import urlparse
import urllib
import os
import sys
import ConfigParser
import bot
import log
import listener
import notifier
import threading
f... | python |
from tweetsole.authorizer import Authorizer
import pytest
import os
def test_has_password():
auth = Authorizer("test")
file = open(auth.path + "/test.enc", 'w+')
file.write("test, test, test,test")
output = auth.has_password()
os.remove(auth.path + "/test.enc")
assert output == True
def tes... | python |
#!/usr/bin/env python
import sys
import os
from sets import Set
#-----------------------------------------
# UTILS:
#-----------------------------------------
def Execute(command):
print(command)
os.system(command)
def Execute_py(command, thisTask, step):
print(command)
scriptName = str(step... | python |
import json
class Computer:
def __init__(self):
self.content_danmu = []
self.content_admin = []
def get_message_danmu(self, mode):
if self.content_danmu:
# _danmu 为列表中存储的第一个弹幕
_danmu = self.content_danmu[0]
if mode == 'json_danmu':
... | python |
# build_compose.py
# ================
#
# This script builds the Docker Compose file used to launch all containers
# needed by the tool, with proper volume mounts, environment variables, and
# labels for behaviors and network conditions as specified in the configuration.
#
# The script generally assumes that it is bein... | python |
import unittest
from Spheral import *
#-------------------------------------------------------------------------------
# Base class to unit test the ConstantBoundary boundary condition.
#-------------------------------------------------------------------------------
class ConstantBoundaryTest:
def testApplyBounda... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.