content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
import pytest
from unittest.mock import MagicMock, patch, call
from chaoslib.exceptions import FailedActivity
from chaosaws.elbv2.actions import (deregister_target, delete_load_balancer,
set_subnets, set_security_groups)
@patch('chaosaws.elbv2.actions.aws_... |
# -*- coding: utf-8 -*-
'''
Created on 6 mars 2017
@author: Jacky
'''
import logging
from discord.ext import commands
import requests
from ArkDiscordBot import settings
from ArkDiscordBot.apps import bot
from ArkDiscordBot.discord import utils
logger = logging.getLogger('BOT.{}'.format(__name__))
API_KEY = getatt... |
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('player', '0017_room_can_adjust_volume'),
]
operations = [
migrations.AlterField(
model_name='room',
... |
"""
Executable for extracting the Single-Photoelectron spectrum from DL1 files
"""
import argparse
import pandas as pd
from pandas.errors import PerformanceWarning
from tqdm import tqdm, trange
from multiprocessing import Pool, Manager
import warnings
from CHECLabPy.core.io import DL1Reader, HDF5Writer
from CHECLabPy.c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-29 21:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('profiles', '0011_add_employment_history_table'),
]
... |
def expression_matter(a, b, c):
return max(a + b + c,
a + b * c,
(a + b) * c,
a * b + c,
a * (b + c),
a * b * c) |
"""loads the hwloc library, used by TF."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
tf_http_archive(
name = "hwloc",
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/download.open-mpi.org/release/hwloc/v2.0/hwloc-2.0.3.tar.gz",
"https://do... |
from .loader import Pickle
|
# -*- coding: utf-8 -*-
"""3rd.decisiontree.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1c4yY9Rr7VkaO1Cv0lBy9aXsg6cxYEXNc
3. **Write a program to demonstrate the working of the decision tree based ID3 Algorithm. Use an appropriate data set fo... |
print("Hello world!") # print ("not good style")
# print("Hello again!")
# print('Single quotes work as well')
# print(5+5)
# this is a comment for humans not computer
# print("Valdis" + 5) # this will not work
print(" this will not plint but print")
print("this will not end well ")
print("alus "*7) # one of the litt... |
# Generated by Django 2.2.9 on 2019-12-20 13:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('datasets', '0002_remove_profile_indicators'),
]
operations = [
migrations.AddField(
model_name='profile',
name='indi... |
#!/usr/bin/python
import matplotlib
matplotlib.use('Agg')
from scipy import *
from pylab import *
from numpy import *
from matplotlib.collections import LineCollection
import glob
import os
from os.path import join as pjoin
import spectrum
def comparacio(a,b):
(Sepa,numa) = a.split('_')
(pa,exta) = numa.sp... |
for name in dir():
if not name.startswith("_"):
del globals()[name]
import varius
from varius import *
def test_vr():
x = vr("cost [usd]", 100)
print(x)
x.latex_repr
show(x)
assert x.value == 100
x.value = 200
assert x.value == 200
y = vr("revenue [usd]", 200)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : Ampel-interface/ampel/cli/LoadJSONAction.py
# License : BSD-3-Clause
# Author : vb <vbrinnel@physik.hu-berlin.de>
# Date : 18.03.2021
# Last Modified Date: 18.03.2021
# Last Modified By : vb <vbrinnel@physik.hu-berlin... |
# -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE... |
""" Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Inglês de Futebol,
na ordem de colocação. Depois mostre: A: Apenas os 5 primeiros colocados; B: Os últimos 4 colocados da
tabela; C: Uma lista com os time em ordem alfabetica; D:Em que posição na tabela está o time do Tottenham."""
#Tu... |
from . import load_robot_and_display_00
from . import joint_move_01
from . import linear_move_02
from . import playground
|
from integ.utils import (
validate_feature_extraction,
validate_fill_mask,
validate_ner,
validate_question_answering,
validate_summarization,
validate_text2text_generation,
validate_text_classification,
validate_text_generation,
validate_translation,
validate_zero_shot_classifica... |
'''
Contains the parent class for screens to inherit from
'''
#Import needed modules
import os
import base64
from random import randrange
import pygame as pg
from pygame.locals import *
import modules.backend as be
from modules.display import display
class Gamestate(object):
'''
Contains variables and methods... |
import re
import socket
import select
from unit.main import TestUnit
class TestHTTP(TestUnit):
def http(self, start_str, **kwargs):
sock_type = (
'ipv4' if 'sock_type' not in kwargs else kwargs['sock_type']
)
port = 7080 if 'port' not in kwargs else kwargs['port']
url =... |
#!/usr/bin/env python
#
# make maps of the dust parameters from a BEAST stats file
import os
import glob
import math
from tqdm import trange, tqdm
import argparse
import numpy as np
from astropy import wcs
from astropy.io import fits
from astropy.table import Table
def setup_spatial_regions(cat,
... |
# QAutomate Ltd 2020. All rights reserved.
#
# Copyright and all other rights including without limitation all intellectual property rights and title in or
# pertaining to this material, all information contained herein, related documentation and their modifications and
# new versions and other amendments (... |
import wx
from gsnodegraph.constants import (BTN_NORMAL_COLOR, BTN_CLICKED_COLOR,
BTN_FOCUSED_COLOR)
from gsnodegraph.assets import ICON_ADD_NODE
class AddNodeBtn(object):
def __init__(self, parent):
self.parent = parent
self.bitmap = ICON_ADD_NODE.GetBitmap()... |
import hydra
from omegaconf import DictConfig
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import pandas as pd
from models.model_generator import get_model
from src.dataset import DatasetTabular
from src.trainer import SaintSupLightningModule
@hydra.main(config_path=... |
class ApiException(Exception):
"""
This class represents an Exception thrown when a call to the Vkontaktr API fails.
In addition to an informative message, it has a `function_name` and a `result` attribute, which respectively
contain the name of the failed function and the returned result that made the function... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .base_network import BaseNetwork
class BaseVAE(BaseNetwork):
"""
Base class for variational autoencoders (VAE), works for both MLP and CNN versions.
All inherited subclass should implement the following functions
1. make_enc... |
"""Tests for the HPSS daily report connector
"""
import json
import tokio.connectors.hpss
import tokiotest
TEST_STRINGS = [
"===== === ==== ======",
" ===== === ==== ======",
"===== === ==== ====== ",
"========",
"=",
"= ",
" =",
"= =",
"= = ",
" = =",
"",
]
TEST_TAB... |
#!/usr/bin/env python
"""Nose-based test runner.
"""
from __future__ import print_function
from nose.core import main
from nose.plugins.builtin import plugins
from nose.plugins.doctests import Doctest
from . import ipdoctest
from .ipdoctest import IPDocTestRunner
if __name__ == '__main__':
print('WARNING: this c... |
from aiogram import types
import text_templates as tt
btnCancelDelete = types.InlineKeyboardButton(text=tt.back, callback_data="cancelDelete")
btnBackMyInvites = types.InlineKeyboardButton(text=tt.back, callback_data="myInvites")
btnMyInvites = types.InlineKeyboardButton(text=tt.my_invites, callback_data="myInvites")
... |
# Lint as: python3
#
# Copyright 2020 The XLS 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... |
# 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... |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
import torch
import torch.nn.functional as F
from torch import nn
from project.fastreid.config import configurable
from project.fastreid.layers import *
from project.fastreid.layers import pooling, any_softmax
from project.fastreid.laye... |
from django.db import models
class Client(models.Model):
name = models.CharField(max_length=50, unique=True, verbose_name='Имя')
discount = models.IntegerField(default=0, verbose_name='Скидка (%)')
total_saved = models.IntegerField(default=0,
verbose_name='Всего сэкон... |
#!/usr/bin/env python
BLOCK_SIZE=512
HASH_ITERATIONS=1000
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
import getpass
import binascii
import struct
import sys
import argparse
parser = argparse.ArgumentParser(description="Encrypt and decrypt disk images (for usage with enst... |
# -*- coding: utf-8 -*-
import smtplib
import time
from mailtrigger.mailer.sender import Sender, SenderException
class DummyServer(object):
def __init__(self):
pass
def quit(self):
return
def sendmail(self, from_addr, to_addrs, msg):
return
def test_smtp():
config = {
... |
#!/usr/bin/python3
# A python3 port of musicctl.sh.
import time
import os
import sys
import re
import subprocess
import process
# warning() functions like print, except it prefixes everything and prints to
# stderr.
def warning(*objs, prefix='WARNING: '):
printed_list = str(prefix)
for i in objs:
pr... |
# Copyright 2018 Iguazio
#
# 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, softwa... |
from django.urls import path, include
from .views import (CreateProductView,
AdList,
ViewProductDetail,
ProductLikeToggle,
ProductLikeAPIToggle,
ProductSaveToggle,
ProductSaveAPIToggle,
... |
import RPi.GPIO as GPIO
import dht11
import time
import datetime
from influxdb import InfluxDBClient
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
# initialize influxDB
host=input("Enter host IP address where InfluxDB is running:");
port = "8086"
dbname = "mysensordb"
interval = 1
#... |
'''
functions to add derived metrics to the dictionaries of metrics
please use the examples to add more
Existing list of prewritten metrics:
'''
from utilities import *
def add_DERIVED_OTHER_INS(metrics):
'''
'''
TOT = 'PAPI_NATIVE_INST_SPEC'
LD = 'PAPI_LD_INS'
ST = 'PAPI_SR_INS'
FP... |
import requests
from userbot.utils import *
from userbot import *
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
@bot.on(admin_cmd(pattern="fsong$", outgoing=True))
async def _(event):
if event.fwd_from:
return
if not event.reply_to_msg_id:
await edit_... |
import logging
from flask import Flask
from flask import request
def api_interface(cache_obj, logger):
logger.info("Starting flask_processing")
app = Flask(__name__)
# Suppressing flask logs only to error because we want the input to be accepted by main process
log = logging.getLogger("werkzeug")
... |
from boa3.builtin import public
@public
def string_test(str1: str, str2: str) -> str:
return '"' + str1[:-1] + '"test_symbol":' + str2 + '}"'
|
from numpy import *
#import tvtk
from enthought.tvtk.api import tvtk
# create a renderer:
renderer = tvtk.Renderer()
# create a render window and hand it the renderer:
render_window = tvtk.RenderWindow(size=(400,400))
render_window.add_renderer(renderer)
# create interactor and hand it the render window
# This handle... |
from django.core.management import call_command
from django.conf import settings
from django.test import SimpleTestCase
from django.urls import reverse
from starterkit.utils import *
class TestUtils(SimpleTestCase):
"""
Console:
python manage.py test starterkit.tests.test_utils
"""
def setUp(self... |
import tensorflow as tf
from tensorflow import keras
from net import encoder, decoder
class VAE(keras.Model):
def __init__(self, input_shape, latent_shape):
super(VAE, self).__init__()
self.latent_shape = latent_shape
self.encoder = encoder(input_shape, latent_shape)
self.decoder =... |
is_destination = False
while is_destination is False:
destination = input()
if destination == "End":
is_destination = True
break
cost = float(input())
wallet = float(0)
while wallet < cost:
wallet += float(input())
print(f"Going to {destination}!")
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import Dataset, DataLoader
from asteroid.filterbanks.enc_dec import Filterbank, Encoder, Decoder
from asteroid.filterbanks import STFTFB
from asteroid.losses ... |
#!/usr/bin/python
'''Finish task with given tex_id.'''
import sys
import settings
from db_operation import remove, add_to_done
if len(sys.argv) == 1:
sys.exit()
try:
int(sys.argv[1])
except ValueError:
print('Argument is not integer.')
sys.exit()
for t in sys.argv[1:]:
if t.isdigit():
nam... |
from sharpy.plans.acts import *
from sharpy.plans.acts.terran import *
from sharpy.plans.require import *
from sharpy.plans.tactics import *
from sharpy.plans.tactics.terran import *
from sharpy.plans import BuildOrder, Step, SequentialList, StepBuildGas
from sharpy.knowledges import KnowledgeBot
from sc2 import UnitTy... |
# coding=utf-8
import xadmin
from .models import Course, Lesson, Video, CourseResource
class CourseAdmin(object):
list_display = ['name', 'desc', 'detail', 'degree', 'learn_times', 'students']
search_fields = ['name', 'desc', 'detail', 'degree', 'students']
list_filter = ['name', 'desc', 'detail', 'degre... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2016 PPMessage.
# Guijin Ding, dingguijin@gmail.com
# All rights reserved
#
# core/audioconverter.py
#
from tempfile import mkstemp
from os import unlink, close, write
import time
import base64
import subprocess
def _randomFileWithData(_data, _suffix):
_prefix = str(... |
# Copyright 2022 Tiernan8r
#
# 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, so... |
"""
Django settings for Greenline project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
... |
import os
class Pwned():
def __init__(self, file):
with open(file) as f:
self.record_len = len(f.readline())
self.records = os.stat(file).st_size // self.record_len
self.file = file
self.jumpsize = 100
def lookup(self, query):
query = ("%%0%dX" % (len(qu... |
#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.c... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from datetime import datetime, timedelta, timezone
import requests
import json
def get_day():
youbi = ["月","火","水","木","金","土","日"]
JST = timezone(timedelta(hours=+9), 'JST')
d = datetime.now(JST)
month = d.month
day = d.day
weekday... |
# -*- coding: utf-8 -*-
"""Create render node."""
from avalon import harmony
from pype.hosts.harmony.api import plugin
class CreateRender(plugin.Creator):
"""Composite node for publishing renders."""
name = "renderDefault"
label = "Render"
family = "render"
node_type = "WRITE"
def __init__(s... |
# Copyright 2016 Google 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, ... |
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.views.generic.list import ListView
from cms.forms import RecordForm, ReviewForm
from cms.models import Record, Review
def record_list(request):
re... |
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for, current_app
from flask.ext.login import login_required
from app.users.models import Users
from app.messages.forms import MessageForm
from app.messages.models import Messages
from app.users.decorators import admin_required
from ... |
#$Id: evtUtilsLib.py,v 1.2 2010/09/14 16:38:48 heather Exp $
def generate(env, **kw):
if not kw.get('depsOnly',0):
env.Tool('addLibrary', library = ['evtUtils'])
if env['PLATFORM']=='win32' and env.get('CONTAINERNAME','')=='GlastRelease':
env.Tool('findPkgPath', package = 'evtUtils')
... |
from __future__ import absolute_import
import logging
import copy
from flask import json
from sqlalchemy import Column, Integer, BigInteger, Unicode, UnicodeText
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.utils import cached_property
from huskar_api import settings
from huskar_api.extras.monitor import... |
# Generated by Django 2.0.4 on 2018-07-16 11:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0016_auto_20180607_0823'),
]
operations = [
migrations.AlterModelOptions(
name='custompermission',
options={'managed... |
# Generated by Django 2.2.1 on 2019-05-23 15:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('materials', '0084_auto_20190522_1547'),
]
operations = [
migrations.RenameField(
model_name='co... |
import datetime
import unittest2
from django.test import TestCase
from django.db import connection, transaction
from django.db.utils import IntegrityError
from django_temporal.db.models.fields import Period, DateRange, TIME_CURRENT, TZDatetime
from models import Category, CategoryToo, ReferencedTemporalFK, BothTempora... |
from inmanta.agent import handler
def convert_bool(val):
return "true" if val else "false"
def test_keygen(project, vy_host, clear):
def make_config(purge=False):
project.compile(
f"""
import vyos
import vyos::vpn
r1 = vyos::Host(
name="lab1",
user="vyos",
... |
import os
import sys
base = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')
sys.path.append(base)
import torch
import torchvision
from selectivenet.model import SelectiveNet
from selectivenet.loss import SelectiveLoss
def test_train_selective_loss():
# dataset
mean = [0.49139968, 0.48215841,... |
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
#
#
# SCRIPT : prepare_data_for_classifier.py
# POURPOSE : extract data for a machine learning breaking classifier.
# use naive_wave_breaking_detector.... |
from src.machines.turing_machine import TuringMachine
from src.grammars.unrestricted_grammar import UnrestrictedGrammar
from src.grammars.variable import Variable
from src.grammars.terminal import Terminal
from src.grammars.production import Production
from src.machines.direction import Direction
__all__ = ["TMToUnres... |
from bs4 import BeautifulSoup
from pymongo import MongoClient
import requests
import time
class ContentDownloader:
REQUEST_WAIT = 0.01
DATABASE_NAME = 'gog2'
PRODUCT_COLLECTION_NAME = 'product'
RANK_COLLECTION_NAME = 'rank'
SERIES_COLLECTION_NAME = 'series'
def __init__(self):
self.i... |
import discord
from discord.ext import commands, tasks
from itertools import cycle
import json
class Function(commands.Cog):
def __init__(self, client):
self.client = client
with open('config.json') as f:
data = json.load(f)
self.status = cycle(data["Status"])
@tasks.loop(seconds=15)
as... |
# -*- coding: utf-8 -*-
"""Main sweep functionality."""
import datetime
import os
from parasweep.namers import SequentialNamer
from parasweep.dispatchers import SubprocessDispatcher
from parasweep.templates import PythonFormatTemplate
def run_sweep(command, configs, templates, sweep, namer=SequentialNamer(),
... |
from .emoji_feedback_sensor import EmojiFeedbackSensor |
# -*- coding: utf-8 -*-
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# BSD 2-Clause License #
# ... |
# -*- coding:utf-8 -*-
import sys,os,threading,platform,time
path=sys.path[0]
sys.path.append(path+"/../../..")
from lib import *
try: from Queue import Queue
except:from queue import Queue
from copy import copy
class ReadCard(gsobject):
def __init__(self,modulename=None,serialname=None):
gsobject.__init_... |
import dash_mantine_components as dmc
from dash import html
component = html.Div(
[
dmc.Divider(size="xs"),
dmc.Space(h=20), # no-prism
dmc.Divider(size="sm"),
dmc.Space(h=20), # no-prism
dmc.Divider(size="md"),
dmc.Space(h=20), # no-prism
dmc.Divider(size... |
# -*- coding: utf-8 -*-
"""
chanjo.converter
~~~~~~~~~~~~~~~~~
Module for converting a CCDS dump to standard Chanjo BED-format.
"""
from __future__ import absolute_import
from .cli import convert
from .core import ccds_to_bed
from .stages import (
grep,
extract_intervals,
merge_related_elements,
parse_raw_int... |
__author__ = 'Guangrei <myawn@pm.me>'
__license__ = 'MIT'
__version__ = "v4.0"
|
# GPI DRP tests infrastructure
|
"""Test sam_to_fasta."""
from pathlib import Path
import pytest
from _pytest.capture import CaptureFixture
from src.sam_to_fasta import main
def create_sam_valid(
path: str,
) -> None:
"""Create a SAM file for testing.
Args:
path: path to test SAM file
Returns:
None
"""
... |
"""Utilities sub-module for FOOOF."""
from .data import trim_spectrum, interpolate_spectrum, subsample_spectra
|
import six
from unittest import skipIf
from django.test import TestCase
from v1.models.resources import Resource
class TestUnicodeCompatibility(TestCase):
@skipIf(six.PY3, "all strings are unicode")
def test_unicode_resource_title_str(self):
resource = Resource(title=u'Unicod\xeb')
self.asse... |
"""
@author fangyi.zhang@vipl.ict.ac.cn
"""
import numpy as np
from . import region
# import shapely
from shapely.geometry import Polygon
def calculate_failures(trajectory):
""" Calculate number of failures
Args:
trajectory: list of bbox
Returns:
num_failures: number of failures
... |
from collections import deque
import tempfile
import os
from six import text_type, binary_type
from pulsar.client.client import JobClient
from pulsar.client.manager import HttpPulsarInterface
from pulsar.client.transport import Urllib2Transport
from pulsar.client.decorators import retry, MAX_RETRY_COUNT
def test_wi... |
##############################################################################################
##############################################################################################
## ##
## ## ## ##### ### ... |
"""
Utilities for outputing results in TFRRS format.
"""
from collections import defaultdict, OrderedDict
from django.core.exceptions import ObjectDoesNotExist
from trac.models import Athlete, Tag
_TFRRS_FIELDS = [
'bib', 'TFFRS_ID', 'team_name', 'team_code', 'first_name', 'last_name',
'gender', 'year', 'da... |
import tensorflow as tf
def steps(model, loss_object, optimizer, train_loss, train_accuracy, test_loss, test_accuracy, **kwargs):
@tf.function
def train_step(images, labels):
with tf.GradientTape() as tape:
predictions = model(tf.cast(images, tf.float32), training=True)
loss =... |
import struct
import time
import sys
import pytest
from fido2.attestation import Attestation
from fido2.client import Fido2Client, _call_polling
from fido2.ctap import CtapError
from fido2.ctap1 import CTAP1
from fido2.ctap2 import ES256, AttestedCredentialData, PinProtocolV1
from fido2.hid import CtapHidDevice
from f... |
from .connexio import Connexio
from .memoria_cau import habilita_memoria_cau
|
'''
* This Software is under the MIT License
* Refer to LICENSE or https://opensource.org/licenses/MIT for more information
* Written by Kohulan Rajan
'''
#Implemenation of tensorboard on a 3 layer network
import tensorflow as tf
import os
import sys
import numpy as np
import matplotlib as mpl
import csv
mpl.use('Ag... |
import argparse
import colorama
import os
class Arguments():
def __init__(self):
self.initialized = False
def initialize(self, parser):
parser.add_argument('--name', required=True, type=str, help='experiment name')
parser.add_argument('--phase', default='train', type=str, choices=['... |
from mmdesigner.cli import pass_environment
import sys
import click
from mmdesigner.Generator import Generator
@click.command("status", short_help="Shows summary of current model.")
@pass_environment
def cli(ctx):
"""Shows status of model in the current working directory."""
gen = Generator(ctx.model_path)
... |
import pytest
from models.emergency_contact import EmergencyContactModel
@pytest.fixture
def create_emergency_contact(contact_number_attributes):
def _create_emergency_contact():
emergency_contact = EmergencyContactModel(
name="EMS",
description="For emergency health crises",
... |
from __future__ import absolute_import, print_function
import six
from django.db import connections, models
from django.db.models.signals import pre_migrate
__all__ = ("CITextField", "CICharField", "CIEmailField")
class CIText(object):
def db_type(self, connection):
engine = connection.settings_dict["... |
from django.test import TestCase
from elections.models import (
DEFAULT_STATUS,
Election,
ModerationHistory,
ModerationStatuses,
)
from elections.utils import ElectionBuilder
from .base_tests import BaseElectionCreatorMixIn
class TestElectionModel(BaseElectionCreatorMixIn, TestCase):
def setUp(sel... |
import anndata
import pandas as pd
from common import add_labels
adata = anndata.read_h5ad(snakemake.input[0])
adata.X = adata.layers["spliced"]
del adata.layers["spliced"]
del adata.layers["unspliced"]
del adata.layers["spliced_unspliced_sum"]
labels = pd.read_csv(snakemake.input[1], sep="\t", index_col=0)
labels =... |
# Sleeping doesn't block one complete process, it blocks one thread. By the POSIX/Linux/UNIX
# definitions a process (for instance one python program) may include multiple threads which all
# share the same memory, but behave like other processes would in all other ways.
# This means processes are more seperated than ... |
import os
import sys
import pytest
import shutil
sys.path.insert(0, "../shallow_backup")
from shallow_backup.utils import copy_dir_if_valid
DIR_TO_BACKUP = 'shallow-backup-test-copy-dir'
BACKUP_DIR = 'shallow-backup-test-copy-backup-dir'
TEST_TEXT_FILE = 'test-file.txt'
DIRS = [DIR_TO_BACKUP, BACKUP_DIR]
class TestC... |
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.glm import H2OGeneralizedLinearEstimator as glm
# Given arrays of alpha and no lambda, the lambdas will be estimated as the max of gradient divided by
# the corresponding alpha value.
#
# When an array of alpha an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.