content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
@date: 2020/8/22 下午9:02
@file: adam.py
@author: zj
@description:
"""
import torch.nn as nn
import torch.optim as optim
from .. import registry
@registry.OPTIMIZERS.register('ADAM')
def build_adam(cfg, groups):
lr = cfg.OPTIMIZER.LR
weight_decay = cfg.OPTIMIZER.WEIGHT_DECAY.DECA... |
import pytest
from ethereum.tools.tester import TransactionFailed
from plasma_core.constants import NULL_ADDRESS
from plasma_core.utils.transactions import decode_utxo_id
from plasma_core.transaction import Transaction
from plasma_core.utils.merkle.fixed_merkle import FixedMerkle
def test_deposit_valid_values_should_... |
# Copyright (c) 2017 Intel Corporation. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from django.contrib.auth.models import Group
from chroma_api.authentication import AnonymousAuthentication
from tastypie.authorization import ReadOnlyAuth... |
#!/usr/bin/python2.7
# Puny Domain Check v1.0
# Author: Anil YUKSEL, Mustafa Mert KARATAS
# E-mail: anil [ . ] yksel [ @ ] gmail [ . ] com, mmkaratas92 [ @ ] gmail [ . ] com
# URL: https://github.com/anilyuk/punydomaincheck
from argparse import ArgumentParser, RawTextHelpFormatter
from sys import exit
from core.creat... |
from datetime import datetime
from typing import Optional, List, Union
from pydantic import Field
from utils.pydantic import BaseModel
# models
class UserMixin(BaseModel):
id: int
name: Optional[str] = Field(None, max_length=50)
account: Optional[str] = Field(None, max_length=50)
profile: Optional[str... |
import logging
from .__version__ import __version__
logging.getLogger(__name__).addHandler(logging.NullHandler())
__all__ = ["__version__"]
|
# -*- coding: utf-8 -*-
import unittest
import time
from ._mouse_event import MoveEvent, ButtonEvent, WheelEvent, LEFT, RIGHT, MIDDLE, X, X2, UP, DOWN, DOUBLE
from keyboard import mouse
class FakeOsMouse(object):
def __init__(self):
self.append = None
self.position = (0, 0)
self.queue = No... |
import tornado.ioloop
from tornado.ioloop import IOLoop
import tornado.web
import tornado.websocket
import sys
import time
from networktables import NetworkTable
from tornado.websocket import WebSocketHandler
from tornado.options import define, options, parse_command_line
import logging
import json
logging.basicConfig(... |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from .views import(
CategoryListView,
CategoryDetailView
)
urlpatterns = [
url(r'^$', CategoryListView.as_view(),name='categories'),
url(r'^(?P<slug>[\w-... |
import numpy as np
import matplotlib.pyplot as plt
import MatchData as MD
"""
Changes data to standard form,
takes input as a vector
"""
def standardize_var(data):
mean = np.mean(data, dtype=np.float64)
std = np.std(data, dtype=np.float64)
stan = (data - mean)/std
return stan
"""
Tests two collections... |
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# importing the Kratos Library
import KratosMultiphysics
import KratosMultiphysics.DelaunayMeshingApplication as KratosDelaunay
import KratosMultiphysics.ContactMechanicsApplication as ... |
#!/usr/bin/env python3
from datetime import datetime
if __name__ == '__main__':
data = datetime(2021, 12, 12)
print(f'data = {data:%d/%m/%Y}')
print(datetime.strptime('01/01/2021', '%d/%m/%Y'))
data2 = datetime.strptime('01/01/2021', '%d/%m/%Y')
print(f'data = {data2:%y-%m-%d}')
|
from __future__ import unicode_literals, print_function
import random
import spacy
from spacy.util import minibatch, compounding
from ast import literal_eval
import os.path
import logging
log = logging.getLogger('file')
class ScNerAnnotation(object):
# model paths for judgment order and mix of both
... |
import enum
from typing import NamedTuple
from .fuels import Fuel, CARBOB_E10
from .plug import DCPlug
__all__ = [
'PType',
'Powertrain'
]
class PType(enum.IntEnum):
"""Constants that refer to the type of drive.
Valid values are:
* `ICEV`: Conventional combustion and hybrids
(i.e. Ho... |
from .class_names import (cityscapes_classes, coco_classes, dataset_aliases,
get_classes, imagenet_det_classes,
imagenet_vid_classes, voc_classes)
from .eval_hooks import DistEvalHook, EvalHook
from .mean_ap import average_precision, eval_map, print_map_summary, eval_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
import copy
import time
import argparse
import cv2 as cv
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--device", default="sample_movie/bird.mp4")
parser.add_argument("--width", help='cap width', type=int, defau... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 Jinsong Liu <jinsongliu@utexas.edu>
#
# Distributed under terms of the GNU-License license.
"""
"""
import numpy as np
import itertools, math
import scipy.stats as stats
from ._polybase import PolyBase
from . import polyutils as pu
... |
"""
Regression tests for mmtbx.scaling.absences
"""
from __future__ import division
from mmtbx.scaling.absences import *
from cctbx.development import random_structure
from cctbx import sgtbx
from scitbx.array_family import flex
import libtbx.load_env
import os.path as op
import random
def exercise_abs_list():
tmp... |
import pandas as pd
df_list = []
for year in range(2007, 2020):
for month in range(1, 13):
file_path_stub = ('/work/akilby/npi/raw/ptaxcode%s%s' % (year, month))
try:
file_path = '%s.csv' % file_path_stub
df = pd.read_csv(file_path)
df['month'] = pd.to_datetime('... |
import statistics
def get_min_avg_max(sequence):
return min(sequence),round(sum(sequence)/len(sequence), 2),max(sequence),
res = get_min_avg_max([0,10,1,9])
print(res)
print(type(res))
def get_min_med_max(sequence):
try:
med = statistics.median(sequence)
except:
print("statistics will not... |
VERBOSE_NVVM_ERRORS = True
class NvvmSupportError(ImportError):
pass
class NvvmError(Exception):
def __str__(self):
return '\n'.join(map(str, self.args))
def check_nvvm_error(error, msg = '', exit = False):
if error:
exc = NvvmError(msg, nvvmResultCodes[error])
if exit:
print(exc)
sys.exit... |
import socket as socket
import time as t
import random as r
# creates socket object
def receve_MSG(IP="",port=1337,MSG_Size=1024,TEXT_Decode='ascii',ExpectedFileType="TXT"):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
if(IP==""):
IP = socket.gethostname()
s.connect((IP, port))
... |
# Ignoring some linting rules in tests
# pylint: disable=redefined-outer-name
# pylint: disable=missing-docstring
import pytest
from bingo.Base.TournamentSelection import Tournament
@pytest.fixture()
def population_all_ones(single_value_population_of_4):
pop = single_value_population_of_4
for indv in pop:
... |
#! /usr/bin/env python3
import bz2
import os.path
import pickle
import shutil
import subprocess
import sys
import tempfile
from collections import OrderedDict
from xml.dom import minidom
import sprite
from domhelpers import *
ofBaseDir = sys.path[0]
ofPOVRayLibDir = os.path.join(ofBaseDir, 'povray')
def runPOVRay... |
from typing import List
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
maxCandy = 0;
for candy in candies:
maxCandy = max(maxCandy, candy)
res = []
for candy in candies:
res.append(extraCandies >= maxCandy - ... |
# 输入文件数据
# 减去基线,反转波形
# 寻找峰位及确定权重
# 转化为起始位
# 输出数据
import sys
import pandas as pd
import numpy as np
import h5py
import scipy
from scipy import signal
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot as plt
import tables
import multiprocessing as mp
with h5py.File(sys.argv[1],'r') as ipt:
wf =... |
import numpy as np
import pandas as pd
import sklearn
import sklearn.model_selection
import os
import pickle
def grid_search(args):
"""
Wrapper around sklearn's parameter grid. Mends
dict values that are not wrapped in list
"""
args = args if isinstance(args, (list, tuple)) else [args]
return ... |
import os #for OS related activities fetching directory, searching ,marking existence of directory
from string import punctuation #importing build in punctuation's
from nltk.tokenize import word_tokenize #importing build in tokenizer
import contractions #for removing contractions for I'll -> I will
from n... |
class Edge:
def __init__(self, i, j):
self.i = i
self.j = j
self.s = 0
def __eq__(self, other):
return self.i == other.i and self.j == other.j
def __hash__(self):
return hash(self.i) + hash(self.j)
def __str__(self):
return "(src={0},dst={1},s={2})".fo... |
from logging import getLogger
import reversion
from datahub.dbmaintenance.management.base import CSVBaseCommand
from datahub.dbmaintenance.utils import parse_uuid, parse_uuid_list
from datahub.investment.project.models import InvestmentProject
logger = getLogger(__name__)
class Command(CSVBaseCommand):
"""Com... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
ENV = os.getenv('OH_QUEUE_ENV', 'dev')
if ENV in ('dev', 'staging'):
DEBUG = True
elif ENV == 'prod':
DEBUG = False
if ENV == 'dev':
SECRET_KEY = 'dev'
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'sqlite:///' + os.path.join(basedi... |
from time import sleep
def test__i__1():
sleep(0.25)
def test__i__2():
sleep(0.25)
def test__i__3():
sleep(0.25)
|
import tensorflow as tf
import numpy as np
import tensorflow_probability as tfp
from keras.models import model_from_json, model_from_yaml
from rl_botics.common.approximators import *
import random
import matplotlib.pyplot as plt
import time
from keras.models import Model
from keras import backend as K
class MlpSoftm... |
#!/usr/bin/env python3
import logging
import os
import xml.etree.ElementTree as ET
from sonLib.bioio import absSymPath
from .seqFile import SeqFile
from cactus.shared.experimentWrapper import ExperimentWrapper
from cactus.shared.configWrapper import ConfigWrapper
from cactus.shared.common import cactusRootPath
from ... |
#!/usr/bin/env python
# $Id: remap_names.py 1340 2010-09-15 11:54:11Z mcolosimo $
"""
This adds back the names to the tree generated by panjo after it is turned into a phyloxml format from a nwk
@author: Marc E. Colosimo
@copyright: The MITRE Corporation, ALL RIGHTS RESERVED, 2010
@version: $Rev: 1340 $
"""
import sys... |
#!/usr/bin/env python
"""
Create NAPALM a script that connects to srx1 and retrieves its LLDP information
(get_lldp_neighbors() method).
From this returned data structure retrieve the local interface name, the remote switch name that
this srx1 is connected to, and the remote port name.
Email this local interface, rem... |
from past.builtins import basestring
import sys
import os
from flask_testing import TestCase
from flask import url_for, Flask
import unittest
import requests
import time
from metrics_service import app
class TestWebservices(TestCase):
'''Tests that each route is an http response'''
def create_app(self):
... |
import os
# the name of the game
GAME_NAME = "Gadakeco"
screenSize = screenWidth, screenHeight = 1080, 720
# the desired framerate
FPS = 30
MAX_DELTA = 1.5 / FPS
# constant frametime for physic updates (Updates Per Second)
UPS = 0.035
# maximum number of physics updates per game loop iteration
MAX_UPDATES =... |
from .best import Best
best = Best()
|
# -*- coding: utf-8 -*-
import ctypes
from msl.loadlib import Server32
class Cpp32(Server32):
def __init__(self, host, port, **kwargs):
super(Cpp32, self).__init__(u'cpp_lib32-uñicödé', 'cdll', host, port)
def add(self, a, b):
return self.lib.add(ctypes.c_int32(a), ctypes.c_int32(b))
|
from .exceptions import a_width_positive,a_width_match
__all__ = ['expr_match_width','expr_calc_width','expr_width_fix_funcs','expr_width_calc_funcs']
def get_width(src):return src if src is None or isinstance(src,int) else src.width
def expr_match_width(source,expect=None):
source_width = get_width(source)
... |
# By importing this module, all handlers defined there will get registered to
# be used in the HandlerRegistry
from aoc_solver.terminal import handlers # pylint: disable=unused-import
|
import docx
import re
from itertools import zip_longest
from config import cursor, db
def initDocx(name, path):
path = '/root/exam_system/docx/' + path +'.docx'
sql = 'insert into docx (paper_name, path) values (%s, %s)'
cursor.execute(sql,(name, path))
db.commit()
makepaper()
def getDocxPath():... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilitie... |
Solution to [HTML Parser - Part 1](https://www.hackerrank.com/challenges/html-parser-part-1) |
# Generated by Django 3.2.6 on 2021-09-16 08:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("students", "0004_auto_20210916_0708"),
("documents", "0002_alter_document_id"),
]
operations = [
mi... |
#!/usr/bin/env python
"""
get_password function that displays asterisks instead of the actual characters.
With the addition of a ControlT shortcut to hide/show the input.
"""
from quo import Elicit, echo
from quo.filters import Condition
from quo.keys import KeyBinder
def main():
hidden = [True] # Nonlocal
k... |
# lldbrepl.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.tx... |
#!/usr/bin/python3
"""
This module contains a function that determines if two classes are the same
"""
def is_kind_of_class(obj, a_class):
"""
Return True if the object is an instance of the specified class
Args:
obj: the object to be tested
a_class: the class to be tested against
Re... |
import obspython as obs
ID = "htk_id"
JSON_DATA = '{"%s":[{"key":"OBS_KEY_1"}]}' % ID
def on_obs_key_1(pressed):
if pressed:
raise Exception("hotkey 1 pressed")
def script_load(settings):
s = obs.obs_data_create_from_json(JSON_DATA)
a = obs.obs_data_get_array(s, ID)
h = obs.... |
from django.core.validators import validate_email
from rest_framework import serializers, validators
from vecihi.posts.models import Post
from .models import User, ViewedProfileTracking
from actstream.models import Action, followers, following
from actstream.actions import is_following
from vecihi.marmara_majors imp... |
def getResNet50Init():
string = '\
layer {\n\
bottom: "image"\n\
top: "conv1"\n\
name: "conv1"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 7\n\
pad: 3\n\
stride: 2\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "conv1"\n\
top: ... |
"""
Get set of normal and attack Bro logs and create a balanced dataset.
"""
#TODO fix doc strings
import os
from sklearn.utils import resample
from sklearn.model_selection import train_test_split
from . import log_munger, metrics
CONN_LOG_DROP_COLS = cols_to_drop = ['conn_state', 'history', 'id.orig_h',
... |
from flask import current_app, request
from flask_restful import marshal
from bank_api.errors import make_error
from bank_api.models import Customer
from . import intent_api_bp
from .common import customer_info_fields
@intent_api_bp.route('/getCustomerInfo', methods=['GET'])
def get_customer_info():
current_app... |
import base64
from copy import deepcopy
import csv
from datetime import datetime, timedelta
import logging
import re
from io import StringIO
from unittest.mock import patch
from django.conf import settings
from django.test import TestCase
from django.urls import reverse
from pytz import timezone
from civil_registry.t... |
# Copyright (c) PagerDuty.
# See LICENSE for details.
import json
import unittest
import os.path
import requests_mock
from pypd import Integration, Service
from pypd.errors import (InvalidEndpointOperation, InvalidEndpoint,
InvalidArguments)
def chunks(l, n):
"""Yield successive n-sized... |
from marshmallow import Schema, fields
class BaseSchema(Schema):
id = fields.Int()
created_at = fields.DateTime()
updated_at = fields.DateTime()
deleted_at = fields.DateTime()
class SysUserSchema(BaseSchema):
uuid = fields.UUID()
username = fields.Str()
password = fields.Str()
nick_n... |
#
# Copyright (c) 2017 Palo Alto Networks, Inc. <techbizdev@paloaltonetworks.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PRO... |
__version__ = '2.0.0a6'
__short_version__ = '2.0a6'
|
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_im... |
import argparse
from enum import Enum
from ai4good.models.model_registry import get_models, create_params
from ai4good.runner.facade import Facade
from ai4good.models.model import ModelResult
from ai4good.utils.logger_util import get_logger
logger = get_logger(__name__)
facade = Facade.simple()
def cache_info():
... |
begin_unit
comment|'# Copyright 2011 Eldar Nugaev'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'#... |
from rest_framework import serializers
from invoice.models import Invoice
class InvoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Invoice
fields = (
"id",
"date",
"sum",
# "order",
)
class InvoiceCreateSerializer(serializ... |
from django.db import models
class Accel(models.Model) :
x = models.DecimalField(max_digits=30, decimal_places=20)
y = models.DecimalField(max_digits=30, decimal_places=20)
z = models.DecimalField(max_digits=30, decimal_places=20)
def toJson(self) :
return {
'x' : self.x,
'y' : self.y,
'z' : self.z
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from django.conf import settings
from django.db import models
from school.models import School
class Classes(models.Model):
YEAR_CHOICES =[]
for r in range(datetime.now().year, 1999, -1):
YEAR_CHOICES.append... |
#!/usr/bin/env vpython3
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Usage: %prog [options] [<commitref>]*
If no <commitref>'s are supplied, it defaults to HEAD.
Calculates the generation number fo... |
import unittest
from train import *
from modules.transformer import Transformer
import torch
class TestTrain(unittest.TestCase):
def test_optimizer(self):
model = Transformer(6)
optimizer = scheduled_adam_optimizer(model)
def test_label_smoothing(self):
pred = torch.rand([7, 6])
... |
import imageio
import os
fileList = []
for file in os.listdir('output/'):
complete_path = 'output/' + file
fileList.append(complete_path)
kargs = {'macro_block_size': 1}
writer = imageio.get_writer('test.mp4', fps=10, **kargs)
for im in fileList:
writer.append_data(imageio.imread(im))
writer.clos... |
import types
from contextlib import suppress
with suppress(ImportError):
import matplotlib.text as mtext
import matplotlib.patches as mpatch
class strips(list):
"""
List of all strips for a plot
"""
@staticmethod
def initialise(facet):
new = strips()
new.facet = facet
... |
from .basic import BasicAPIv2Connector
from .standard import APIv2Connector
from .model import ModelAPIv2Connector
|
# 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, software
# distributed under t... |
from django.urls import path
from . import views
urlpatterns = [
path('gdp/', views.get_gdp),
path('cpi/', views.get_cpi),
path('cpi_yearly/', views.get_cpi_yearly),
path('unemployment/', views.get_unemployment),
path('immigration/', views.get_immigration),
path('deportation/', views... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 7 14:24:20 2021
@author: bmoseley
"""
# This module defines various active schedulers, which are iterables which allow us
# to define which FBPINN subdomains are active/fixed/inactive at each training step
# This module is used by constants.py w... |
# (c) 2016 Continuum Analytics, Inc. / http://continuum.io
# All Rights Reserved
#
# constructor is distributed under the terms of the BSD 3-clause license.
# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.
from __future__ import print_function, division, absolute_import
import os
import sys
from ... |
from typing import Tuple
import numpy as np
from sklearn.metrics import precision_recall_curve, auc
from xgboost import DMatrix
def xgb_mape(preds: np.ndarray, dtrain: DMatrix) -> Tuple[str, float]:
"""
Mean average precision error metric for evaluation in xgboost.
Args:
preds: Array of predicti... |
'''
Ejercicio 14.7.6. Modelar una clase Mate que describa el funcionamiento de la conocida bebida
tradicional local. La clase debe contener como miembros:
a) Un atributo para la cantidad de cebadas restantes hasta que se lava el mate (representada
por un número).
b) Un atributo para el estado (lleno o vacío).
c) ... |
'''
Description: Provides the implementation for creating the core directories
required for the processing of a product request.
License: NASA Open Source Agreement 1.3
'''
import os
import utilities
from environment import Environment, DISTRIBUTION_METHOD_LOCAL
def __create_local_directory(base_pa... |
import librosa
import torch
from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer
class STT_model(object):
def __init__(self):
#load model and tokenizer
self.tokenizer = Wav2Vec2Tokenizer.from_pretrained(
"facebook/wav2vec2-base-960h")
self.model = Wav2Vec2ForCTC.from_pret... |
from __future__ import absolute_import
import tensorflow as tf
import os
from collections import OrderedDict
import anchors
slim = tf.contrib.slim
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}
def define_first_dim(tensor_dict,dim_size):
"""
Define the first dim keeping the remaining dims ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 22 15:58:31 2019
@author: DaniJ
"""
import numpy as np
import scipy as sp
from bvp import solve_bvp
from scipy import linalg
#from four_layer_model_2try_withFixSpeciesOption_Scaling import four_layer_model_2try_withFixSpeciesOption_Scaling as flm
from matplotlib import p... |
import os
import math
def getRow(rowAssignment):
low = 0
high = 127
for c in rowAssignment[:-1]:
mid = low + (high - low) / 2
if c == 'F':
high = math.floor(mid)
elif c == 'B':
low = math.ceil(mid)
lastC = rowAssignment[-1]
if lastC == "F":
return low
elif lastC == 'B':
re... |
# Spin up DNS servers (either authoritative or recursive)
from jinja2 import Environment, PackageLoader, FileSystemLoader
from enum import Enum
from pkg_resources import resource_filename
from dnstest.dir import Dir
import subprocess
import os
import shutil
RESOLVER_HINT = """
zone "." {
type hint;
file "ro... |
# Func14.py - anonymous fcn
nocall = ['바보', '멍청이', '오영택']
def Hi(name='손'):
if name in nocall : return
print('{}님, 안녕하세요'.format(name))
Hi() # 손님, 안녕하세요
Hi('홍길동') # 홍길동님, 안녕하세요
Hi('바보') #
|
import mxnet as mx
import torch
import numpy as np
torch.backends.cudnn.benchmark = True
import networks as mnn
import networks_th as tnn
import functools
import operator
import time
PARAMS = {}
'''
[x] ResnetGenerator
gradient may be wrong
[x] ResnetBlock
gradient match after replacing instance norm
[x] Re... |
import autofit as af
class MockFitness:
def figure_of_merit_from(self, parameter_list):
return 1.0
class TestInitializePrior:
def test__prior__samples_sample_priors(self):
model = af.PriorModel(af.m.MockClassx4)
model.one = af.UniformPrior(lower_limit=0.099, upper_limit=... |
"""
The auralisation module provides generic tools for auralisation and calculating back from the receiver to the source.
"""
#import numpy as np
#np.seterr(all='raise')
import auraliser.auralisation
import auraliser.generator
import auraliser.propagation
import auraliser.realtime
import auraliser.reverter
#import a... |
from Numeric import zeros,array,ArrayType
from Numeric import Float,TOWER_TYPES,TOWER_TYPES_VALUES
def assertRaises(block,exception=Exception,shout='This should raise an exception'):
try:
block()
except exception:
pass
else:
assert False,shout
"""
PyPy issues : >>>> 1=1 prod... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
import datetime
import typing
from cryptography import x509
from cryptography.x509.name import _ASN1_TYPE_TO_ENUM
def _obj2txt(backend,... |
#!/usr/bin/env python3
import pytest
from helpers.client import QueryRuntimeException
from helpers.cluster import ClickHouseCluster
cluster = ClickHouseCluster(__file__)
node1 = cluster.add_instance("node1", with_zookeeper=True)
node2 = cluster.add_instance("node2", with_zookeeper=True)
@pytest.fixture(scope="modul... |
"""
Copyright (c) 2018, Salesforce.com, 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:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the foll... |
import redis
# redisに接続する。ホスト、ポート、db番号を指定する
# r = redis.StrictRedis(host='localhost', port=6379, db=0)
# # キーと値をセットする
# r.set('key01', 'aaaa')
# # セットした値を取得する
# v = r.get('key01')
# # 文字列型に変換する
# v_str = v.decode()
# # 削除する
# r.delete('key01')
def countjapan():
r = redis.StrictRedis(host='localhost', port=63... |
"""Tests src/common/math.py"""
import os
import pytest
import numpy as np
from common.math import bootstrap_ci
def test_bootstrap_ci_fixed_seed():
"""Testing the bootstrap_ci method, but we can't have a non-deterministic test here. """
sample_data = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 5.0])
opera... |
'''
Date: 2021-06-08 10:04:21
LastEditors: Liuliang
LastEditTime: 2021-06-22 09:44:15
Description: main
'''
# 首先导入包
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from PIL import Image
import os
import matpl... |
import sys
import json, gzip
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datasets
def combine_results(*jsons):
jsons0 = []
for js in zip(*jsons):
j0 = {}
for j in js:
for k, v in j.items():
j0[k] = v
jsons0.append(j0)
r... |
import subprocess, time
import pytest
from driver import Driver
def _start_bot_process():
"""
Function to run a bot for testing in subprocess
"""
args = ['python', 'tests/behavior_tests/run_bot.py',]
return subprocess.Popen(args)
@pytest.fixture(scope='module')
def driver():
driver = Driver()
... |
from tests.utils import W3CTestCase
class TestFlexbox_MarginAuto(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flexbox_margin-auto'))
|
"""
Defines the convolutional neural network with 3 convolutional and 3 fully-connected layers.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils import data
import numpy as np
class Net3(nn.Module):
def __init__(self):
super(Net3, self).__init__()
# 3 inpu... |
import discord
import datetime
import io
import asyncio
import random
import helpers.helpers as helpers
from helpers import paginator
from PIL import Image, ImageSequence
import re
import errors
import aiohttp
from typing import Optional
import typing
from discord.ext import commands
def setup(client):
client.add_... |
from __future__ import division
from __future__ import print_function
import time
import argparse
import pickle
import os
import datetime
import torch.optim as optim
from torch.optim import lr_scheduler
from utils import *
from modules_clevrer import *
from clevrer.clevrer_dataset_v2 import load_obj_track, get_one_h... |
import cv2
import numpy as np
# select the digit we want
digit = 9
# define path where the digit is stored
path = "handwritten/" + str(digit) + ".png"
print(path)
# read image, grayscale and change resolution to 28x28
img_gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
img_28 = cv2.resize(255 - img_gray, (28, 28), int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.