content stringlengths 5 1.05M |
|---|
# -*- encoding=utf-8 -*-
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
PATH_TO_TENSORFLOW_MODEL = 'models/face_mask_detection.pb'
def load_tf_model(tf_model_path):
'''
Load the model.
:param tf_model_path: model to tensorflow model.
:return: session and graph
'''
... |
from semisupervised.labelpropagation.lp2 import label_propagation
__all__ = ['lp_helper', 'label_propagation', 'lp_iteration',
'lp_data_gen', 'lp_matrix_multiply'
] |
# Copyright 2013 Openstack Foundation
# 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 requ... |
from toontown.safezone import DistributedTreasure
from toontown.toonbase import ToontownGlobals
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import Point3
Models = {ToontownGlobals.ToontownCentral: 'phase_4/models/props/icecream',
ToontownGlobals.DonaldsDock: 'phase_6/models/props/starfish_tre... |
from preproc import Preprocessor
from preproc.errors import PreprocessorError, PreprocessorWarning
def runtest_error(filename, in_text, error_name, error_line, error_char):
pre = Preprocessor()
try:
pre.process(in_text, filename)
except PreprocessorError as err:
assert err.name == error_name and err.line == er... |
# *** Entertainment Center ***
#
# This acts as model and kicks the View in
import media
import fresh_tomatoes
# Model
apocalypse_now = media.Movie("Apocalypse Now",
"Let's kill a colonel, sorry terminate \
his commands",
"https:/... |
"""Contains helper functions for visualizing the results of experiments
and comparing recorded experiments to one another.
"""
import matplotlib.pyplot as plt
from numpy.lib.arraysetops import isin
from researcher.fileutils import *
def final_compare(experiments, metrics, draw_plots=False, **kwargs):
"""Prints t... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: spaceone/api/monitoring/plugin/event.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _r... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
convertor_registry = {}
missing = object()
no_default = object()
class log_action(object):
def __init__(self, *args... |
import json
import sys
with open(sys.argv[1],'r', encoding='utf-8') as inFile:
with open(sys.argv[2], 'w', encoding='utf-8') as outFile:
header = None
headix= None
for l in inFile:
o=json.loads(l)
if header is None:
header = []
for k ... |
"""
Render a template using Genshi module.
"""
import pyperf
from genshi.template import MarkupTemplate, NewTextTemplate
BIGTABLE_XML = """\
<table xmlns:py="http://genshi.edgewall.org/">
<tr py:for="row in table">
<td py:for="c in row.values()" py:content="c"/>
</tr>
</table>
"""
BIGTABLE_TEXT = """\
<table>
{% f... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.go import target_type_rules
from pants.backend.go.goals import package_binary
from pants.... |
import kivy
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
def build(self):
return Label(text='おはよう御座います', font_size=72, font_name='Arial')
if __name__ == '__main__':
MyApp().run()
|
"""
Assign bounds to deviation forces
Inputs:
boundDevID: (integer) The deviation edges ID that are allowed to change their force magnitude
boundUpDev: (float) The upper bound of allowable change of force magnitudes [kN]
boundLowDev: (float) The lower bound of allowable change of force magni... |
from ..util import register
from PIL import Image
import os
import random
plugin_dir = os.path.dirname(os.path.abspath(__file__))
FRAME_ORDER = [0, 1, 2, 3, 1, 2, 3, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 0, 0, 0, 4, 5, 5, 5, 6, 7, 8, 9]
BOXES = [(11, 73, 106, 100), (8, 79, 112, 96)]
@register(["cxk", "蔡徐坤", "篮球", "jntm", "鸡... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import sys
class Solution:
def _isValidBST(self, r, left, right):
if not r:
return True
else:
return all([
... |
# coding: utf-8
"""
The MIT License
Copyright (c) 2009 Marici, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, c... |
# hdf5-udf <file.h5> test-string.py Temperature.py:1000:double
def dynamic_dataset():
input_data = lib.getData("Dataset1")
input_dims = lib.getDims("Dataset1")
udf_data = lib.getData("Temperature.py")
udf_dims = lib.getDims("Temperature.py")
for i in range(input_dims[0]):
print(lib.string(i... |
"""
This module splits marc file into finding aid bibs and the rest
"""
from pymarc import MARCReader
from utils import save2csv
from manipulation import save2marc
def create_finding_aids_list(src, out_finding, out_no_finding, csvfile):
with open(src, "rb") as file:
reader = MARCReader(file)
for... |
import django
def pytest_configure(config):
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"HOST": "localhost",
"NAME... |
#
# This file is part of PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which
# is released under the BSD 3-clause license. See accompanying LICENSE.md for
# copyright notice and full license details.
#
default_app_config = 'pkpdapp.apps.PkpdAppConfig'
|
#
# PySNMP MIB module CISCO-CDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CDP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:35:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
from abc import ABCMeta, abstractmethod
from typing import Tuple
import numpy as np
import torch
import cv2
class ImageArrayGetter(ABCMeta):
@abstractmethod
def __call__(cls) -> np.array:
pass
class CV2CamImageArrayGetter(ImageArrayGetter):
def __init__(cls, resizer: callable, camera: any):
... |
# import tensorflow as tf
import tensorflowjs as tfjs
from tensorflowjs.converters import tf_saved_model_conversion_pb
saved_model_path = "../saved_model_js"
output_path = "web_model"
def convert_to_tfjs(input_dir, output_dir):
# Reference: https://github.com/tensorflow/tfjs-converter/blob/0.8.x/python/tensorflow... |
class Produto:
nome = ''
codigo = 0
compra = 0.0
venda = 0.0
def cadastrar(catalogo):
for c in range(2):
dados = Produto()
dados.nome = input('Digite o nome do produto: ')
dados.codigo = int(input('Insira o código do produto '))
dados.compra = float(input('Digite o ... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Kairo de Araujo
"""
import pytest
from unittest import mock
from voluptuous import MultipleInvalid
from ownca.exceptions import OnwCAInvalidDataStructure
from ownca.crypto.keys import (
_validate_owncakeydata,
_get_public_key,
OwncaKeyData,
generate,
)
@m... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import pytest
import spack.main
spack_filter = spack.main.SpackCommand('filter')
@pytest.mark.db
@pytest.mark.usefixtu... |
'''
Style Grader class with instance-method plugin-based functionality.
'''
import codecs
from ConfigParser import ConfigParser
from collections import defaultdict
import os
import sys
from copy import deepcopy
from glob import glob
from cpplint.cpplint import CleansedLines, RemoveMultiLineComments
from style_grader... |
import numpy as np
import pandas as pd
import os
import glob
import sklearn
from transformers import BertTokenizer
from torch.utils.data import TensorDataset
from sklearn.metrics import f1_score
import random
from transformers import BertForSequenceClassification
from torch.utils.data import DataLoader, RandomSampler,... |
"""The Triangular distrubution."""
from equadratures.distributions.template import Distribution
from equadratures.distributions.recurrence_utils import custom_recurrence_coefficients
import numpy as np
from scipy.stats import triang
RECURRENCE_PDF_SAMPLES = 8000
class Triangular(Distribution):
"""
The class de... |
import torch
from torch.autograd import Variable, grad
def grad_z(z, t, model, loss_criterion, n, λ=0):
model.eval()
# initialize
z, t = Variable(z), Variable(t) # here were two flags: volatile=False. True would mean that autograd shouldn't follow this. Got disabled
y = model(z)
loss = loss_cr... |
import random
import string
from asciimatics.exceptions import NextScene
from asciimatics.screen import Screen
from asciimatics.widgets import Button, Frame, Label, Layout
class HomePage(Frame):
"""A HomePage widget"""
def __init__(self, screen: Screen) -> None:
#
super().__init__(screen, sc... |
from rqalpha import run
from rqalpha.api import *
def init(context):
context.s1 = "000001.SZ"
logger.info(context.run_info)
logger.info('-- {} --'.format(context.universe))
# logger.info(all_instruments(type='CS'))
logger.info(instruments('000001.XSHE'))
logger.info(instruments(['000001.XSHE',... |
"""
tests.parsers.industry
~~~~~~~~~~~~~~~~~~~~~~
Industry table tests
"""
from evepaste import parse_industry
from tests import TableTestGroup
INDUSTRY_TABLE = TableTestGroup(parse_industry)
INDUSTRY_TABLE.add_test('''Tritanium (4662 Units)
Pyerite (1857 Units)
Mexallon (1027 Units)
Isogen (44 Units)
Nocxium (51 Un... |
class UserTechnology:
def __init__(self, name, skill, endorsements):
self.name = name
self.skill = skill
self.endorsements = endorsements
@classmethod
def from_dict(cls, dict_):
return UserTechnology(
name=dict_["name"],
skill=dict_["skill"],
... |
"""A parser for reading RINEX observation files with version 3.xx
"""
# Standard library imports
from datetime import datetime
from typing import Any, Dict, List, Optional, Union
# Third party imports
import numpy as np
import pandas as pd
# Midgard imports
from midgard.dev import plugins
from midgard.parsers.wip_rin... |
# -*- coding:utf-8 -*-
# Copyright 2019 Huawei Technologies Co.,Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
from Jumpscale import j
from .rooter import abort, env, app, package_route, redirect, static_file, PACKAGE_BASE_URL
@app.get("/wiki")
def list_all_wikis():
return env.get_template("wiki/home.html").render(wiki_names=j.tools.mdbook.list_books())
@app.get(f"{PACKAGE_BASE_URL}/wiki")
@package_route
def list_packa... |
import matplotlib.pyplot as plt
import numpy as np
def schism_timing(workdir,start=1, end=None, block_days = 1.0):
import glob,os
sample="elev.61"
files = [os.path.split(x)[1] for x in glob.glob(os.path.join(workdir,"*_0000_%s" % sample))]
files.sort(key = lambda x: int(x[0:x.index("_")]))
blocks ... |
from django.contrib.auth import get_user_model
from rest_framework.test import APITestCase, APIClient
from api.models import Pregunta, Auditoria, Respuesta, Sucursal, Incidente
class RespuestaViewTestCase(APITestCase):
def setUp(self):
self.client = APIClient()
self.user = get_user_model().objec... |
# Copyright 2021 Jared Hendrickson
#
# 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 wri... |
# Enhanced Embedded Flash Controller (EEFC) driver for Atmel SAM
from time import time, sleep
import logging
try:
xrange
except NameError:
# Remap xrange to range for Python 3
xrange = range
from . import FlashController
class CommandException(Exception):
def __init__(self, fsr_address, fsr):
self.fsr_address ... |
from .autocast_mode import autocast
|
from django.db import models
class Course(models.Model):
created = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey('auth.User', related_name='courses', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
teachers = models.ManyToManyField('auth.User', related_name='teac... |
"""This file contains functions that accept and process keyboard input."""
from .output_functions import display
def clean_input(text):
"""Converts raw text to a consistent format."""
return text.lower().strip()
def collect_input(message=None, prompt="> ", valid=[], cast=str):
"""Prompts the user for i... |
import cv2
import os
import subprocess
# File to shrink down the sizes of the captures images
W = 100.
subprocess.run("rm -rf neg", shell=True)
subprocess.run("mkdir neg", shell=True)
subprocess.run("rm -rf pos", shell=True)
subprocess.run("mkdir pos", shell=True)
# resize negatives
for filename in os.listdir('nega... |
from setuptools import setup, find_packages
import os
setup(
name='allele-project',
description='Projects allele specific alignments on reference genome',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
version='0.0.1',
url='https://github.com/Barski-lab/allele-p... |
from enum import Enum, auto, unique
import networkx as nx
@unique
class CodeType(Enum):
ACCESSOR = auto()
CALCULATION = auto()
CONVERSION = auto()
FILEIO = auto()
HELPER = auto()
LOGGING = auto()
MODEL = auto()
PIPELINE = auto()
UNKNOWN = auto()
def build_code_type_decision_tree... |
'''
Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
'''
metros=int(input("Digite o valor em metros "))
centímetros= metros*100
milímetros= metros*1000
print("{} metros em centímetros é igual a {}cm, e em milímetros é {}mm ".format(metros,centímetros,milímetros)) |
## import hotshot
## _prof = hotshot.Profile("hotshot.prf")
# Official parser plugin for MediaWiki language "MediaWiki 1"
# Last modified (format YYYY-MM-DD): 2013-05-06
import locale, pprint, time, sys, string, traceback
from textwrap import fill
import wx
import re # from pwiki.rtlibRepl import ... |
import unittest
import sys
sys.path.append('LeetCode/_0051_0100')
from _063_UniquePaths2 import Solution
class Test_063_UniquePaths2(unittest.TestCase):
def test_uniquePathsWithObstacles(self):
solution = Solution()
self.assertEqual(2, solution.uniquePathsWithObstacles([
[0,0,0],
... |
"""
=========================================================================
Comparing randomized search and grid search for hyperparameter estimation
=========================================================================
Compare randomized search and grid search for optimizing hyperparameters of a
random forest.
... |
# Copyright 2013-2021 The Salish Sea MEOPAR contributors
# and The University of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/... |
# This file is to preprocess the annotation file to keep the alternative
# exons with high quality, by using the following criteria:
# 1. surronding introns are no shorter than 100bp
# 2. not overlapped by any SE triplets or AS-exon
# 3. the length of the alternative exon within a given region, e.g. 50~450bp
# 4. with ... |
import pigpio
import time
motor_pin = 27 #メモしたGPIO番号
pi = pigpio.pi()
for i in range(3):
pi.set_servo_pulsewidth(motor_pin, 1500)
time.sleep(1)
pi.set_servo_pulsewidth(motor_pin, 1600)
time.sleep(1)
pi.set_servo_pulsewidth(motor_pin, 1700)
time.sleep(1)
pi.se... |
LIB_METHODS = ["unwrap"]
EXCEPTION_TYPE = "exception_handler"
ERROR_TYPE = "error_handler"
FUNC_TYPE = "function"
IGNORE_TYPE = "ignore"
|
import sqlite3
from sqlite3 import Error
class DB_Manager:
def __init__(self, db_file="database.db"):
try:
# create connection
self.conn = sqlite3.connect(db_file)
except Error as e:
print(e)
# create projects table
self.create_table(""" CREATE T... |
import yaml
from yabf import Likelihood, LikelihoodContainer, load_likelihood_from_yaml
def test_round_trip():
# subclass
yml = """
likelihoods:
- name: small
class: SimpleLikelihood
components:
- name: shared
class: SimpleComponent
- name: big
class: SimpleLikelih... |
import unittest
from xie.graphics.utils import TextCodec
class TextUtilsTestCase(unittest.TestCase):
def setUp(self):
self.codec = TextCodec()
def tearDown(self):
pass
def test_encodeStartPoint(self):
self.assertEqual("0.37.59", self.codec.encodeStartPoint((37, 59)))
self.assertEqual("0.59.37", self.codec... |
from output.models.nist_data.atomic.unsigned_byte.schema_instance.nistschema_sv_iv_atomic_unsigned_byte_min_inclusive_4_xsd.nistschema_sv_iv_atomic_unsigned_byte_min_inclusive_4 import NistschemaSvIvAtomicUnsignedByteMinInclusive4
__all__ = [
"NistschemaSvIvAtomicUnsignedByteMinInclusive4",
]
|
"""
Jonathan Moore 30JAN2022 m5.3 assignment
this module queries the database using find and find_one
"""
from pymongo import MongoClient
url = "mongodb+srv://admin:admin@cluster0.qyihp.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
client = MongoClient(url)
db = client.pytech
students = db.students
try... |
from . import get_fixture
# import modules from the project for testing
from config_validation_engine.config_validation_engine import *
custom = {
'schema': 'schema.yml',
'bad': 'data_bad.yml',
'good': 'data_good.yml'
}
def test_validate():
print('Data')
print(custom['schema'])
# validate(cus... |
frase = 'Curso em Vídeo Python'
#print(frase[::3])
#print(frase.count('o'))
#print(frase.upper().count('o'))
#print(len(frase))
#print(frase.replace('Vídeo','Android'))
#frase = frase.replace('Python','Android')
#print(frase.split())
|
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... |
"""
A simple unit test of 'run_deep_trainer.py'
"""
import run_deep_trainer
def test_deep_trainer():
# pass args=[] so we can pass options to nosetests on the command line
run_deep_trainer.main(args=[])
|
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
from classy import *
from classy import image
# <codecell>
images=image.load_images('data/digits')
# <markdowncell>
# with overlapping patches...
# <codecell>
data=image.images_to_patch_vectors(images,(4,4))
# <markdowncell>
# or with non-overlap... |
import torch
import numpy as np
from torch import nn
class NeuralFusionLoss(nn.Module):
def __init__(self, config, reduction='none', l1=True, l2=True):
super().__init__()
self.criterion1 = nn.L1Loss(reduction=reduction)
self.criterion2 = nn.MSELoss(reduction=reduction)
... |
import torch
import torch.nn as nn
import math
import json
from baseline.model import Classifier, load_classifier_model, create_classifier_model
from baseline.pytorch.torchy import *
from baseline.utils import listify
import torch.backends.cudnn as cudnn
cudnn.benchmark = True
class WordClassifierBase(nn.Module, Clas... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import grpc
import psutil
import time
import ray
from ray.core.generated import node_manager_pb2
from ray.core.generated import node_manager_pb2_grpc
from ray.tests.utils import RayTestTimeoutExcepti... |
import numpy as np
__all__ = ['get_kpt_variables', 'get_scf_variables', 'get_wfn_variables']
def get_kpt_variables(**kwargs):
"""Extract the variables to declare the k-points grid."""
variables = dict()
if 'kpt' in kwargs:
kpt = np.array(kwargs['kpt']).reshape((-1,3))
variables['kptopt... |
from typing import Callable, Optional, List, Union, Tuple
from pyjsg.jsglib import JSGObject
from pyjsg.jsglib import isinstance_
from rdflib import BNode, URIRef, Graph
from pyshex.shapemap_structure_and_language.p1_notation_and_terminology import RDFGraph, Node
from pyshex.utils.collection_utils import format_colle... |
import sys, yaml, os, os.path
sys.path.append(os.path.realpath(os.path.dirname(sys.argv[0])))
import tag_manager
from report_parser import LegatoReport
import pyparsing
def collect_access(tree):
if type(tree) == pyparsing.ParseResults:
to_ret = set()
for l in tree:
to_ret |= collect_acc... |
from .rules import Deny
from .context import Context
class Authorizations(object):
"""Authorizations base class.
Developper must inherit this class to create its own rules."""
def __init__(self, rules=None, default_rule=Deny()):
"""
Args:
rules (dict<Action, Rule>):
... |
#---------------------------------------
#Since : 2018/09/16
#Update: 2019/07/25
# -*- coding: utf-8 -*-
#---------------------------------------
import numpy as np
from ringbuffer import RingBuffer
from copy import deepcopy
from parameters import Parameters
class Othello():
def __init__(self):
self.params... |
# Parser: zagster (e.g., Wichita)
import json, re
def parse(df, data, utc):
# df is a dict with the following keys:
# [u'feedurl', u'feedname', u'bssid', u'format', u'feedurl2', u'keyreq', u'parsername', u'rid']
# parse out desired info
data = data.split("\n")
clean_stations_list = []... |
class Solution:
def powerfulIntegers(self, x, y, bound):
powx, curx = [1], x
if x != 1:
while curx < bound:
powx.append(curx)
curx *= x
powy, cury = [1], y
if y != 1:
while cury < bound:
powy.append(cury... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2019/2/13 13:59
# @User : zhunishengrikuaile
# @File : General.py
# @Email : binary@shujian.org
# @MyBlog : WWW.SHUJIAN.ORG
# @NetName : 書劍
# @Software: 百度识图Api封装
# 通用文字识别(含位置信息版)
# URL参数:
## access_token 调用AccessToken模块获取
# Headers参数
## 参数:Content-Ty... |
# Generated by Django 3.0.4 on 2020-04-28 19:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Classification',
fields=[
... |
class Board(object):
GAME_SPACES = 120
def __init__(self):
self.p1position = self.__class__.GAME_SPACES
self.p2position = self.__class__.GAME_SPACES
def peg_p1(self, score):
self.p1position -= score
def peg_p2(self, score):
self.p2position -= score
def get_p1_posi... |
import matplotlib.pyplot as plt
import numpy as np
# import scipy.odr
# from scipy.optimize import curve_fit
import scipy.linalg
import sympy as sp
from devices.mca import MeasMCA
import fitting
import plot
import utils
def spectra(
am_path: str,
fe_path: str,
noise_path: str,
gain: f... |
from glob import glob
from os import path
'''
Function "path_formater" convert a arr of relative paths to a arr of full paths
using a parent dir.
Arguments:
parent_dir: It is a string which indicates the path to a parent directory
extension: It is a string which indicates the type of files the... |
#!/usr/bin/env python
# BSD 3-Clause License
#
# Copyright (c) 2019, SIM Lab
# 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 code must retain the above copyright ... |
import json
import torch
import quaternion
import numpy as np
import pandas as pd
import torch.nn as nn
# from shapefit.utils.pathnames import ContainerPathnames as paths
from shapefit.utils.pathnames import LocalPathnames as paths
########################
### Global DICTIONARIES
########################
def get_va... |
from unit_test_common import execute_csv2_request, initialize_csv2_request, ut_id, sanity_requests
from sys import argv
# lno: CV - error code identifier.
def main(gvar):
if not gvar:
gvar = {}
if len(argv) > 1:
initialize_csv2_request(gvar, selections=argv[1])
else:
... |
import config
from hyperband import Hyperband
from model import get_base_model
from utils import prepare_dirs, save_results
def main(args):
# ensure directories are setup
dirs = [args.data_dir, args.ckpt_dir]
prepare_dirs(dirs)
# create base model
model = get_base_model()
# define params
... |
import numpy as np
class SimpleFourierFilter(object):
"""
Class to apply simple Fourier Filtration to a vector
Filter types:
'fraction' (requires kwarg: 'fraction' to be set)
'rule 36' (can set kwarg: 'power' but not necessary)
"""
def __init__(self, modes, filter_type, **kwargs):... |
# See https://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp?ecid=murl10006450#1441964
street_types = [
"abbey",
"acres",
"alley",
"allée",
"aut",
"autoroute",
"av",
"ave",
"avenue",
"bay",
"beach",
"bend",
"blvd",
"boul",
"boulevard",
"by-pass",
"b... |
class Colours:
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
MID_GREEN = (45, 173, 31)
|
# Purpose: Exceptions
class VeracodeError(Exception):
"""Raised when something goes wrong"""
pass
class VeracodeAPIError(Exception):
"""Raised when something goes wrong with talking to the Veracode API"""
pass
|
import numpy as np
import os
import pandas as pd
import shutil
import sys
import tempfile
import time
from contextlib import contextmanager
from fastparquet import write, ParquetFile
from fastparquet.util import join_path
@contextmanager
def measure(name, result):
t0 = time.time()
yield
t1 = time.time()
... |
from django.apps import AppConfig
class CallcontrolConfig(AppConfig):
name = 'callcontrol'
|
from django.db import models
# Create your models here.
from django.db import models
class Tweet(models.Model):
text = models.CharField(max_length=140)
author_email = models.CharField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
published_at = models.DateTimeField(null=True)
... |
# Generated by Django 3.1.2 on 2021-03-20 07:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cart', '0028_orderbeta_created_at'),
]
operations = [
migrations.AddField(
model_name='orderbeta',
name='status',
... |
# pylint: disable=no-self-use
from allennlp.common.testing import AllenNlpTestCase
from allennlp.data import Token, Vocabulary
from allennlp.data.token_indexers import ELMoTokenCharactersIndexer
class TestELMoTokenCharactersIndexer(AllenNlpTestCase):
def test_bos_to_char_ids(self):
indexer = ELMoTokenChar... |
import pytest
import os
import json
from elasticsearch import Elasticsearch
from ...wapo.parser import ParserWAPO
class TestParserNetzpolitik():
@classmethod
def setup_class(self):
self.es = Elasticsearch()
self.parser = ParserWAPO(self.es)
self.index = "wapo_clean"
file_locati... |
"""
Class for reading and manipulating head-related transfer functions. Reads files in .sofa format (started before
python implementations of the sofa conventions were available -> will be migrated to use pysofaconventions!)
"""
import copy
import warnings
import pathlib
import pickle
import bz2
import numpy
try:
... |
import wifi
inerface = input("WI-FI INTERFACE(default wlan0): ")
def Search():
wifilist = []
cells = wifi.Cell.all(inerface)
for cell in cells:
wifilist.append(cell)
return wifilist
def FindFromSearchList(ssid):
wifilist = Search()
for cell in wifilist:
... |
###########################################################################
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/l... |
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class RegisterForm(UserCreationForm):
email = forms.EmailField(label="Email", required=True,
help_text='Required. Inform a valid email address.')
name = fo... |
import data_process as dp
from Ensemble_Methods import EnsembleLearner
from Decision_Regression_Forest import RandomForest
from KNN import KNN
from Logistic_Regression import Logistic_Regression
from Naive_Bays import NaiveBays
from SVM import SVM_Kernel
# load data
data_raw, data_index = dp.load_data('heart_disease_d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.