content stringlengths 5 1.05M |
|---|
import re, time
from IxNetRestApi import IxNetRestApiException
from IxNetRestApiFileMgmt import FileMgmt
class QuickTest(object):
def __init__(self, ixnObj=None, fileMgmtObj=None):
self.ixnObj = ixnObj
if fileMgmtObj:
self.fileMgmtObj = fileMgmtObj
else:
self.fileMgm... |
"""
This file defines restricted arithmetic:
classes and operations to express integer arithmetic,
such that before and after translation semantics are
consistent
r_uint an unsigned integer which has no overflow
checking. It is always positive and always
truncated to the internal machine word size... |
# -*- coding: utf-8 -*-
import numpy as np
import logging
import datetime
import oxdls
from .edge_definer import marker_edge_definer
class MetadataMaker():
def __init__(self, image_name, unstitched, datatype):
# Set up attributes and variables
self.boundaries = unstitched.boundaries
sel... |
# Generated by Django 3.0a1 on 2020-01-30 19:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
#!/usr/bin/env python
import os
import sys
import hashlib
import logging
############
#
# Download utilities
#
####
# COPYRIGHT DISCALIMER:
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Founda... |
"""activities URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
#!/usr/bin/env python3
import pyaudio
import sys
sys.path.insert(0, "../")
from pwmaudio import noALSAerror
with noALSAerror():
p = pyaudio.PyAudio()
info = p.get_host_api_info_by_index(0)
print(p.get_host_api_count())
print(info)
numdevices = info.get('deviceCount')
for i in range(0, numdevi... |
# -*- coding: utf-8 -*-
#
# test_contexts_mpi4py.py
import unittest
import arbor as arb
# to be able to run .py file from child directory
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
try:
import options
except ModuleNotFoundError:
from test import opt... |
# vim: sw=4:ts=4:et:cc=120
#
# ACE Hunting System
#
# How this works:
# A HunterCollector reads the config and loads all the sections that start with hunt_type_
# each of these configuration settings defines a "hunt type" (example: qradar, splunk, etc...)
# each section looks like this:
# [hunt_type_TYPE]
# module = p... |
# -*- coding: utf-8 -*-
import numpy as np
import welltestpy as wtp
import seaborn as sns
import pandas as pd
from anaflow import thiem
from ogs5py import specialrange
from matplotlib import pyplot as plt
#from gstools import SRF, Gaussian
from project import get_srf, ogs_2d, priors
from scipy.optimize import curve_fi... |
'''Dark Souls 3 msg XML processor'''
# pylint: disable=E1101,E1136,E1137,C0111,C0103
import asyncio
import codecs
import random
import re
import time
from dataclasses import dataclass, field
from functools import partial, reduce, wraps
from pathlib import Path
from typing import Dict
from xml.etree import ElementTree
... |
# The MIT License (MIT)
#
# Copyright (c) 2017 Paul Sokolovsky
# Modified by Brent Rubell for Adafruit Industries, 2019
#
# 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, ... |
from django.test import TestCase
from django.contrib.auth.models import User
from datetime import datetime
from .models import Task, Project
# Create your tests here.
def create_test_user():
return User.objects.create_user(username='User', email='mail@example.com', password='password')
class TestModels(TestCa... |
from .constants import Constants
from donation_play.games.common_cheater import CommonCheater
class Gothic2Cheater(Constants, CommonCheater):
"""Class for working with Gothic cheats."""
def __init__(self, gothic_title, mem_editor=None):
"""Class initialization.
:param str gothic_title: game ... |
#!/usr/bin/env python
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
install_requires = []
# install_re... |
# Copyright 2018 Red Hat Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
"""
Module containing common generator constants
"""
LOGGER_NAME = "logger"
|
from rjgtoys.yaml import yaml_load
data = yaml_load("""
---
a: 1
b: 2
""")
print(data)
|
import mock
import hashlib
import pytest
from botocore.exceptions import ClientError
from webservices.rest import db, api
from webservices.tasks import download as tasks
from webservices.resources import download as resource
from tests import factories
from tests.common import ApiBaseTest
class TestDownloadTask(Api... |
"""
Run all the unit tests in the cea/tests folder
"""
import os
import unittest
import cea.config
import cea.workflows.workflow
__author__ = "Daren Thomas"
__copyright__ = "Copyright 2020, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Daren Thomas"]
__license__ = "MIT"
__version__ = "0.1"
__mai... |
from __future__ import absolute_import
import pytz
from datetime import datetime, timedelta
from django.utils import timezone
from sentry.testutils import AcceptanceTestCase, SnubaTestCase
from mock import patch
event_time = (datetime.utcnow() - timedelta(days=3)).replace(tzinfo=pytz.utc)
class OrganizationGroup... |
from DataPreparation import DataPreparation
import numpy as np
from scipy.special import expit
class ANN:
def __init__(self):
self.neuralNetwork = NeuralNetwork()
def trainNetwork(self, numberOfIteration):
dataPreparation = DataPreparation()
# testData = dataPreparation.prepareTestDat... |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# File: transform.py
import inspect
import pprint
from typing import Callable, List, TypeVar
from fvcore.transforms.transform import Transform
from fvcore.transforms.transform_util import to_float_tensor, to_numpy
import nu... |
from typing import List
def rose_smell_increase(roses: List[int]) -> int:
n, max_sub = len(roses), 0
forward, backward = [1 for _ in range(n)], [1 for _ in range(n)]
for i in range(1, n):
if roses[i] > roses[i - 1]:
forward[i] = forward[i - 1] + 1
else:
max_sub = ma... |
#!/usr/bin/python
from nagioscheck import NagiosCheck, UsageError
from nagioscheck import PerformanceMetric, Status
import urllib2
import optparse
try:
import json
except ImportError:
import simplejson as json
class ESShardsCheck(NagiosCheck):
def __init__(self):
NagiosCheck.__init__(self)
... |
# @Author: Varoon Pazhyanur <varoon>
# @Date: 28-08-2017
# @Filename: image_combine.py
# @Last modified by: varoon
# @Last modified time: 28-08-2017
import cv2
import numpy as np
#GOAL: put the opencv logo on an image and make it opaque(rather than transparent)
messi = cv2.imread("messi5.jpg")
cv_logo = cv2.imr... |
"""Helpers for data entry flows for helper config entries."""
from __future__ import annotations
from abc import abstractmethod
from collections.abc import Callable, Mapping
import copy
from dataclasses import dataclass
from typing import Any
import voluptuous as vol
from homeassistant import config_entries
from hom... |
"""
This code uses the onnx model to detect faces from live video or cameras.
"""
import sys
#import time
import argparse
import cv2
import numpy as np
import onnx
from caffe2.python.onnx import backend
import onnxruntime as ort
import vision.utils.box_utils_numpy as box_utils
def predict(width,
height,
... |
from scheduler.problem import Instance, InstanceSolution
from collections import deque
def solve(instance: Instance) -> InstanceSolution:
"""Solves the P||Cmax problem by using a greedy algorithm.
:param instance: valid problem instance
:return: generated solution of a given problem instance
"""
... |
# Copyright (c) 2020, Xilinx
# 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 follow... |
import json
import os
import pytest
from json_expand_o_matic import JsonExpandOMatic
class TestLeaves:
"""Test `leaf_node` functionality."""
# Our raw test data.
_raw_data = None
@pytest.fixture
def raw_data(self, resource_path_root):
if not TestLeaves._raw_data:
TestLeaves... |
#
# 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... |
import re
import os
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from urllib import urlencode
import csv
from product_spiders.items import Produc... |
from django import template
from django.conf import settings
from images.models import Image
register = template.Library()
@register.simple_tag
def insert_image(id, class_names):
image = Image.objects.get(id=id)
return f"<img src='{settings.MEDIA_ROOT}/{image.file}' class='{class_names}' alt='{image.alt_tag}'... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... |
#!/usr/bin/env python
import logging
import os
import boto3
from botocore.exceptions import ClientError
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def lambda_handler(event, context):
s3c... |
from core.helpers import create_ps_command, obfs_ps_script, gen_random_string
from datetime import datetime
from StringIO import StringIO
class CMEModule:
'''
Executes PowerSploit's Invoke-Mimikatz.ps1 script
Module by @byt3bl33d3r
'''
name = 'Mimikatz'
def options(self, context, modu... |
"""Calculate Functions"""
# Authors: Jeffrey Wang
# License: BSD 3 clause
import numpy as np
def calculate_batch(batch_size, length):
"""
Calculate the batch size for the data of given length.
Parameters
----------
batch_size : int, float, default=None
Batch size for training. Must be one of:
- int : Use ... |
import pandas as pd
df_estimation = pd.read_csv('results_pooled/strucfunc_estimation.csv')
df_forecast = pd.read_csv('results_pooled/strucfunc_forecast.csv')
def make_column(df):
res = []
for i in ['1', '2', '3', '4', '5']:
m = df[i].mean()
std = df[i].std()
str = f"{m:.2f}({std:.2f})"... |
"""
Provides build and test targets for JUnit 5.
All of the test targets in this file support tags= and exclude_tags= parameters. These are
translated to JUnit 5 @Tag filters.
junit5_test_suite and junit5_test have the following naming convention:
${base_name}+${tags[0]}+${tags[1]}...+${tags[n]}-${exclude_tags[0]... |
from django.shortcuts import render, redirect,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from .models import Image, Profile,Instagram
from .forms import UserRegisterForm,CommentForm
from .email import send_welcome_email
from django.contrib.auth.decorators import login_required
# Creat... |
#!/usr/bin/env python
'''
Exercise 2 - class 10
'''
from jnpr.junos import Device
from jnpr.junos import exception
from jnpr.junos.op.ethport import EthPortTable
from getpass import getpass
import sys
HOST = '184.105.247.76'
USER = 'pyclass'
PWD = getpass()
def remote_conn(hst, usr, pwd):
'''
Open the remote ... |
# coding=utf-8
import pickle
import pathlib
# dictionary of unitid's to fix
# key = NSF inst_id, value = IPEDS Unitid
fixes = {
1081: 104151, # Arizona State University
100132: 109651, # Art Center College of Design
1158: 110468, # Alliant International University
8718: 129020, ... |
#!/usr/bin/env python3
"""
WRITEME [outline the steps in the pipeline]
This pipeline preprocesses CoughVid 2.0 data.
The target is the self-reported multiclass diagnosis.
The idea is that each of these tasks should has a separate working
directory in _workdir. We remove it only when the entire pipeline
is done. This ... |
# HOW TO USE:
# gsutil -q -m cp -r 'gs://magentadata/models/music_transformer/*' <destination folder>
# python main.py -model_path=path/to/model/checkpoints/unconditional_model_16.ckpt -output_dir=/tmp -decode_length=1024 -primer_path=path/to/primer_mid -num_samples=1
# python main.py -model_path=./checkpoints/uncondit... |
import os
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from pax.dsputils import InterpolatingMap
from pax.core import data_file_name
from pax import units
map_file = '../../pax/data/XENON100_s2_xy_patterns_Xerawdp0.4.5.json.gz'
try:
os.mkdir(map_file)
except FileExistsError:
pas... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sys
import os
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
from runserver import app
from maple.extension import db, redis
from maple.model import (Blog, Tag, Category, User, TimeLine, Question,
... |
from turtle import Turtle
from config import BORDER_HEIGHT
ALIGNMENT = 'center'
FONT = ("Arial",15,"normal")
class ScoreBoard(Turtle):
def __init__(self) -> None:
super().__init__()
self.score = 0
self.highScore = self.get_highscore()
self.color("white")
self.penup()
... |
"""Middleware to handle forwarded data by a reverse proxy."""
from ipaddress import ip_address
import logging
from aiohttp.hdrs import X_FORWARDED_FOR, X_FORWARDED_HOST, X_FORWARDED_PROTO
from aiohttp.web import HTTPBadRequest, middleware
from homeassistant.core import callback
_LOGGER = logging.getLogger(__name__)
... |
#!/usr/bin/env python
###############################################################################
#
# pairwise2matrix.py - convert list of pairwise scores to distance matrix
#
# File: pairwise2matrix.py
# Author: Alex Stivala
# Created: September 2008
#
#
# Given list of pairwise scores from qptabmatch_allpairs... |
#/**
# *\file Simulated_Annealing.py
# *\brief This code contains the simulated annealing algorithm implemented
# * to solve the Assignment 2, group project, rubix cube problem
# * - Solves both n=2, n=3 cubes
# * - Utilises calculate_cost() function based on number of missplaced ... |
from rest_framework_extensions.routers import ExtendedSimpleRouter
from .views import PostViewset
router = ExtendedSimpleRouter()
router.register(r'posts', PostViewset, base_name='posts')
urlpatterns = router.urls
|
# EMACS settings: -*- tab-width: 2; indent-tabs-mode: t; python-indent-offset: 2 -*-
# vim: tabstop=2:shiftwidth=2:noexpandtab
# kate: tab-width 2; replace-tabs off; indent-width 2;
# =============================================================================
# ___ ______ __ _ ____ _____
# _ __ ... |
from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Profile
class ProfileTestClass(TestCase):
'''
test class for Profile model
'''
def setUp(self):
self.user = User.objects.create_user("tes... |
from sklearn import svm
import visualization
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report
import pickle
from sklearn.svm import SVC
from x... |
import pandas as pd
import math
import numpy as np
import cv2
import argparse
from glob import glob
from itertools import chain
import os
CORRECTW = 1350
CORRECTH = 720
SIDE_DISTANCE = 8000
FRONT_DISTANCE = 6000
REAR_DISTANCE = 8000
W_OFFSET = 50
VEHICLE_L = 5023
VEHICLE_W = 1960
HALF_VEHICLE_L = VEHICLE_L / 2
HALF_... |
import pytest
LV_BASIC_TOKENIZATION_TESTS = [
(
"Nevienu nedrīkst spīdzināt vai cietsirdīgi vai pazemojoši ar viņu "
"apieties vai sodīt.",
[
"Nevienu",
"nedrīkst",
"spīdzināt",
"vai",
"cietsirdīgi",
"vai",
... |
from .markov import MarkovImage
from .scanner import ImageScanner
from .traversal import Traversal, HLines, VLines, Spiral, Blocks, Hilbert
from .type import ImageType, RGB, Grayscale, Indexed
from ..scanner import Scanner
from ..parser import Parser, LevelParser
Scanner.add_class(ImageScanner)
Traversal.add_class(HL... |
import os, sys, cdms2, vcs, vcs.testing.regression as regression
baselineName = sys.argv[1]
projection = sys.argv[2]
zoom = sys.argv[3]
f = cdms2.open(vcs.sample_data + "/clt.nc")
a = f("clt")
x = regression.init()
p = x.getprojection(projection)
b = x.createboxfill()
b.projection = p
if (zoom == 'none'):
x.plot... |
from upside.enforcer import config
from upside.enforcer.upload.chunks import chunk_secret_value, adjust_chunk_size
from upside.enforcer.upload.util import add_existing_secrets_to_secret_store
from upside.enforcer.util.secret import Secret
def test_chunking():
chunks = chunk_secret_value('abcdef', 1)
assert le... |
import os
import numpy as np
from linescanning import utils
import pandas as pd
def correct_angle(x, verbose=False, only_angles=True):
"""correct_angle
This function converts the angles obtained with normal2angle to angles that we can use on the scanner. The scanner doesn't like angles >45 degrees. If... |
import pytest
import os.path
import logging
from cryptography import x509
from cryptography.hazmat.primitives.asymmetric import rsa
from commandment.pki.models import RSAPrivateKey, CACertificate
logger = logging.getLogger(__name__)
class TestORMUtils:
def test_find_recipient(self, certificate):
pass
|
import logging
from logging.handlers import RotatingFileHandler
import os
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_moment import Moment
from config import Config
db = SQLAlchemy()
login = LoginManager()
moment = Moment()
def... |
"""
*
* Copyright (c) 2021 Manuel Yves Galliker
* 2021 Autonomous Systems Lab ETH Zurich
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source cod... |
import ast
import base64
import json
import requests
import pytest
from pytest_bdd import parsers, scenario, then, when
# Scenario {{{
@scenario('../features/salt_api.feature', 'Login to SaltAPI using Basic auth')
def test_login_basic_auth_to_salt_api(host):
pass
@scenario('../features/salt_api.feature',
... |
from abc import ABC, abstractmethod
from machine.plugin import PluginType
class Resource(ABC):
@abstractmethod
def __call__(self) -> PluginType:
raise NotImplementedError
|
"""
Top level CLI commands.
"""
from .dcos_docker import dcos_docker
from .dcos_vagrant import dcos_vagrant
__all__ = [
'dcos_docker',
'dcos_vagrant',
]
|
from mygtestabcde.Ml import Ml
|
import textwrap
import sys
import os
import json
import pytest
import pendulum
from click.testing import CliRunner
from unittest.mock import MagicMock
from prefect import Flow
from prefect.engine.state import Scheduled
from prefect.run_configs import UniversalRun
from prefect.storage import Local as LocalStorage
from ... |
import os
import unittest
import yaml
from remote_controller.ir_sender import IRSender
FILE_PATH = os.path.dirname(__file__)
ACTIONS_PATH = '../resources/commands/commands-actions.yml'
class IRSenderTest(unittest.TestCase):
def setUp(self):
with open(os.path.join(FILE_PATH, ACTIONS_PATH), 'r') as str... |
import pytest
import requests
from .utils import SECRET_KEY
from microq_admin.utils import load_config
from microq_admin.tools import delete_claims
from microq_admin.projectsgenerator.qsmrprojects import (
create_project, delete_project, is_project
)
from microq_admin.jobsgenerator.qsmrjobs import (
main as jo... |
import pyotp
from flask import url_for
from itsdangerous import Signer
from app.config import FLASK_SECRET
from app.extensions import db
from app.models import User
def test_auth_mfa_success(flask_client):
user = User.create(
email="a@b.c",
password="password",
name="Test User",
a... |
import string
import random
import urllib.request
import requests
import timeit
def script():
start = timeit.default_timer()
print("Welcome to ")
print("""\
▓█████ ███▄ █ ██████ ▄▄▄█████▓ ██▒ █▓ ▄▄▄
▓█ ▀ ██ ▀█ █ ▒ ██ ▒ ▓ ██▒ ▓▒ ▓██░ █▒▒ ████▄
▒███ ▓ ██ ▀█ ██▒░ ▓██▄ ▒... |
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the... |
# monte um dicionario com as seguintes chaves = lista, somatorio, tamanho, maior valor, menor valor
|
from website_manager import WebsiteManager
class NewsManager:
def __init__(self):
self.website_manager = WebsiteManager()
self.titles = []
# Find the titles of several news websites
def find_titles(self, urls):
titles = []
for url in urls:
articles_titles = se... |
import os
import time
from pathlib import Path
from typing import List, Dict
import cv2
import numpy as np
from decord import VideoReader
from decord import cpu
from appearance_module.base import AppearanceModel
from detection_module.detector.base import Detector
from interfaces.face import Face
from interfaces.frame... |
"""Extract HRRR radiation data for storage with COOP data.
Run once at 10 PM to snag calendar day stations. (RUN_50_AFTER.sh)
Run again with RUN_NOON.sh when the regular estimator runs
"""
from __future__ import print_function
import datetime
import os
import sys
import pytz
import pyproj
import numpy as np
import py... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2017, Zhijiang Yao, Jie Dong and Dongsheng Cao
# All rights reserved.
# This file is part of the PyBioMed.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the PyBioMed source tree.
"""
#####... |
"""
Author: Mohammad Dehghani Ashkezari <mdehghan@uw.edu>
Date: 2019-07-27
Function: Trains machine learning models using Simons CMAP data sets.
"""
|
#
# FILE: Balanced.py
# AUTHOR: Andy Szybalski
# PURPOSE: Global map script - Solid pangaea, balanced strategic resources.
#-----------------------------------------------------------------------------
# Copyright (c) 2004, 2005 Firaxis Games, Inc. All rights reserved.
#-----------------------------------------... |
import numpy as np
class LensConeUniform(object):
"""
This class generates samples drawn uniformly in two dimensions out to maximum radius
r(z) = 0.5 * cone_opening_angle * f(z), where cone_opening_angle is the opening angle of the rendering volume
specified when creating the realization, and f(z) is... |
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse
from .serializers import EstimatorSerializer
from src.estimator import estimator
from rest_framework_xml.renderers import X... |
import os
from utils.file_utils import strip_ext
from utils.logger import get_logger
from utils.signal_processing import units_to_sample
from utils.eaf_helper import eaf2df
import logging
class TxtSegments(object):
def __init__(self, root_dir, ts_units="s", add_labels=False, sep="\t", ext=".txt"):
self.ro... |
# -*- coding: utf-8 -*-
"""EEGNet: Compact Convolutional Neural Network (Compact-CNN) https://arxiv.org/pdf/1803.04566.pdf
"""
import torch
from torch import nn
from .common.conv import SeparableConv2d
class CompactEEGNet(nn.Module):
"""
EEGNet: Compact Convolutional Neural Network (Compact-CNN)
https://a... |
#!/usr/bin/env python
def parse_column_file(input,output=None,offsets=None):
f = open(input,'r').readlines()
dict = {}
for l in f:
import re
res = re .split('\s+',l)
print res
if len(res) > 3:
t = {}
t['cols'] = res[1]
t['offset'] = float(... |
import shutil
from pathlib import Path
from typing import Generator
import pytest
from hub_scraper.models import DataFolder, Hub
from hub_scraper.scraper import HabrScraper
BASEDIR = Path(__file__).resolve().parent
@pytest.fixture()
def default_hub() -> Hub:
return Hub(
hub_name="python",
thr... |
def banner(text, ch='=', length=78):
"""Return a banner line centering the given text.
"text" is the text to show in the banner. None can be given to have
no text.
"ch" (optional, default '=') is the banner line character (can
also be a short string to repeat).
"... |
from django.test import TestCase
from platforms.models import Platform, PlatformGroup
from tenancy.models import Tenant
class PlatformGroupTest(TestCase):
def _get_tenant(self):
tenant = Tenant.objects.create(name="Acme Corp.")
return tenant
def test_slug_is_generated_on_save(self):
... |
def main():
#Short program that does some small math with
#integers and floating point data-types.
#int numbers
i_num1 = 5
i_num2 = 8
#float point numbers
f_num1 = 4.5
f_num2 = 8.25
#quicc maths
print("Float: " + str(f_num1) + " + " + str(f_num2) + " = " + str(f_num1+f_num2))
print("String: " + str(i_... |
# -*- coding: utf-8 -*-
#
# Copyright (c), 2016-2019, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author ... |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='FunctionalPy',
version='1.0.0',
description='Functional programming library for Python',
author='Aruneko',
author_email='aruneko99@gmail.com',
url='https://www.github.com/aruneko/functionalpy',
packages=['functionalpy']
)
|
import unittest
from click.testing import CliRunner
import ytmusic_deleter.cli as cli
class TestCli(unittest.TestCase):
def test_delete_uploads(self):
runner = CliRunner()
result = runner.invoke(cli.delete_uploads, ["--add-to-library"])
assert result.exit_code == 0
def test_remove_alb... |
import spectral as sp
import numpy as np
import math
import traceback
from PIL import Image
#attention: need to change res's name and
#cal the average spectrum of a img. Input a img and return an array (the same format as Spectral lib's )
def cal_aver_SP(img):
width, height, deepth = img.shape
sum_SP = 0
... |
# ---------------------------------------------------------
# Tensorflow MPC-GAN Implementation
# Licensed under The MIT License [see LICENSE for details]
# Written by Hulin Kuang
# ---------------------------------------------------------
import os
import tensorflow as tf
from solver import Solver
import numpy as np
i... |
import os
import sys
from threading import Thread, currentThread
import json
from kafka import KafkaConsumer
import django
def consumer(canonical_source):
from Sync.models import CanonicalUpdate, ENUM_UpdateStatus
consumer = KafkaConsumer(canonical_source.name,
bootstrap_serv... |
"""
Автор: Моисеенко Павел, подгруппа № 2.
ИСР 4.2. Задание: разработать фрагмент программы с использованием
библиотеки pyqrcode, позволяющей создавать изображение QR-кода на
основе переданной в программу текстовой строки.
"""
import pyqrcode
image = pyqrcode.create(input("Введите текст: "))
image.... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Brandon Nielsen
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
def normalize(value):
"""Returns the string with decimal separators normalized."""
return value.replac... |
from __future__ import absolute_import
from sentry.plugins import Plugin2
class GemstoneYetAnotherPlugin(Plugin2):
pass
|
from gna.exp import baseexp
from gna.configurator import uncertaindict, uncertain, NestedDict
from gna import constructors as C
from gna.expression.index import NIndex
import numpy as np
from load import ROOT as R
seconds_per_day = 60*60*24
class exp(baseexp):
"""
JUNO experiment implementation v01 (frozen)
Deri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.