content
stringlengths
5
1.05M
from __future__ import annotations import socket from pylivelinkface import PyLiveLinkFace, FaceBlendShape UDP_PORT = 11111 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # open a UDP socket on all available interfaces with the given port s.bind(("", UDP_PORT)) while True: data, addr...
import numpy as np import matplotlib.pyplot as plt from uncertainties import ufloat from scipy import optimize import scipy.constants as const from scipy.stats import sem
import datetime import uuid from sqlalchemy import Column, ForeignKey, DDL, event from sqlalchemy.orm import relationship, backref from sqlalchemy.dialects.postgresql import TIMESTAMP, TEXT, BYTEA, UUID from .base import Base from .users import Users from .swarms import SwarmHealthStatuses, Swarms from .apiaries impo...
from echolib.pyecho import * double = type('double', (), {}) char = type('char', (), {}) long = type('long', (), {}) _type_registry = {} def registerType(cls, read, write, convert=None): if cls.__name__ in _type_registry: raise Exception("Type %s already registered" % cls.__name__) _type_registry[cl...
import dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output import pandas as pd import plotly.express as px # load in dataset happiness = pd.read_csv('world_happiness.csv') # create dash object app = dash.Dash() # items in dataset for region column r...
# Copyright 2019 PrivateStorage.io, 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
#!/usr/bin/env python """ Copyright (c) 2016, Meissner Pascal, Schleicher Ralf 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 notice...
current = list(map(int, input().split(':'))) target = list(map(int, input().split(':'))) s = current[0]*3600+current[1]*60+current[2] m = target[0]*3600+target[1]*60+target[2] h = (m-s)%86400 print(h//36000, h//3600%10,':',h//600%6, h//60%10,':',h//10%6, h%10, sep='')
"""Define utility methods for users test_api.""" import binascii import logging import os import secrets import time import datetime from base64 import b64decode from urllib.parse import quote_plus, urlencode from django.core.exceptions import SuspiciousOperation from django.http import HttpResponseRedirect import j...
import logging import warnings import numpy as np import os import typing from typing import Any, Dict, List, Optional, Text, Tuple from rasa.utils import io as utils from rasa.nlu.classifiers import LABEL_RANKING_LENGTH from rasa.shared.nlu.constants import TEXT from rasa.nlu.components import Component from rasa.nlu...
from gquant.dataframe_flow import Node class AverageNode(Node): def process(self, inputs): """ Compute the average value of the key column which is defined in the `column` of the node's conf Arguments ------- inputs: list list of input dataframes. ...
#!/usr/bin/python import sys import os from eclipse2buck import decorator from eclipse2buck import config def get_current_dep_name(file): if os.path.isdir(file): return os.path.realpath(file) else: return os.path.dirname(os.path.realpath(file)) def get_reference_lists(file): filename = ge...
######################################## # Automatically generated, do not edit. ######################################## from pyvisdk.thirdparty import Enum HostSystemIdentificationInfoIdentifier = Enum( 'AssetTag', 'OemSpecificString', 'ServiceTag', )
import numpy as np from _svd_lsq import _lsq def lsq(x, y): """ Compute reast square regression. Parameters ---------- x : np.ndarray (m,1) y : np,ndarray (1,) Returns ------- np.ndarray Coefficients of OLS model. """ x = x.astype(np.float64) y = y.astype(np.f...
# The MIT License (MIT) # # Copyright © 2021 Maurizio Tomasi # # 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, copy, mod...
# https://www.codewars.com/kata/5526fc09a1bbd946250002dc/train/python # You are given an array (which will have a length of at least 3, # but could be very large) containing integers. The array is either # entirely comprised of odd integers or entirely comprised of even # integers except for a single integer N. Write ...
from paddlefsl.datasets import CubFS root = '~/.cache/paddle/dataset' training_set = CubFS(mode='train', root=root) validating_set = CubFS(mode='valid', root=root, backend='pil') def get_item_test(): image, label = training_set[16] print(image.shape) # (3, 84, 84) print(image) # A numpy array image...
import pytest # noqa from datar.core.backends.pandas import Interval, DataFrame, Series from datar.core.backends.pandas.testing import assert_frame_equal from datar import f from datar.base.funs import ( cut, identity, outer, make_names, make_unique, data_context, expandgrid, diff, ...
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers """ ### Build a model Each convolution and fully-connected layer (with exception for end layers) consits of Convolution / Dense -> Batch Normalization -> ReLU Activation. """ def conv_bn(x, filters): x = layers.Conv1D(filt...
import sys import numpy as np from keras.models import Sequential from keras.layers import Conv1D, Activation from learning_to_adapt.model.layers import LHUC, FeatureTransform def parse_nnet1(line_buffer, with_lhuc_layers=False): components = [] line = next(line_buffer) assert line.startswith("<Nnet>") for l...
from h_pyramid_sentry import report_exception from kombu.exceptions import OperationalError from pyramid.events import BeforeRender, subscriber from h import __version__, emails, storage from h.events import AnnotationEvent from h.exceptions import RealtimeMessageQueueError from h.notification import reply from h.task...
import os import numpy as np import autofit as af import autolens as al from test import integration_util test_type = "galaxy_fit" test_name = "deflections" test_path = "{}/../../".format(os.path.dirname(os.path.realpath(__file__))) output_path = test_path + "output/" config_path = test_path + "config" af.conf.insta...
# !/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2019/11/10 4:46 PM # @Author: wuchenglong import os import tensorflow as tf import tensorflow.keras as kr import tokenization import helper class Prediction(object): def __init__(self): pass def _config_(self, model): """模型调用的一些配置信息""" ...
import numpy as np from paddle import fluid from interaction.transformer import TransformerDecoder from interaction.trigger import TriggerController from perception.common.backbone import MobileNetV2 class AttentionController(object): def __init__(self, inputs_type='visual_token', ...
from setuptools import find_packages, setup setup( name="dialogue-generation-models", version="0.0.1", description="Pingpong Dialogue Generation Models", install_requires=[ "torch==1.6.0", "sentencepiece==0.1.91", "tensorflow==2.1.0", "transformers==3.1.0", ], ur...
from .test import * # noqa DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', 'USER': os.environ.get('PG_USER'), 'PASSWORD': os.environ.get('PG_PASSWORD'), 'PORT': '5435', # Postgres 9.5, # 'PORT': '5436', # Postgres 9....
""" @ Harris Christiansen (code@HarrisChristiansen.com) Generals.io Automated Client - https://github.com/harrischristiansen/generals-bot Generals Bot: Common Move Logic """ import logging import random from . import bot_base from .client.constants import * ######################### Move Priority Capture ########...
""" 6-11. Cities: Make a dictionary called cities. Use the names of three cities as keys in your dictionary. Create a dictionary of information about each city and include the country that the city is in, its approximate population, and one fact about that city. The keys for each city’s dictionary should be something l...
import _plotly_utils.basevalidators class ModebarValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="modebar", parent_name="layout", **kwargs): super(ModebarValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
from werkzeug.exceptions import Unauthorized class UnauthorizedWWWAuthenticate(Unauthorized): """ This is a near verbatim copy of an improvement to an as-yet-unreleased upstream version of werkzeug that allows us to specify a www_authenticate argument containing the contents of that field. We should get r...
# An interactive table from a Pandas.DataFrame import qgrid qgrid.set_grid_option('maxVisibleRows', 5) # Edit and filter the data qgrid_widget = qgrid.show_grid(data) display(qgrid_widget) # retrieve the filtered and edited data fltered_data = qgrid_widget.get_changed_df()
from .ggnn import sparse_ggnn_layer from .gnn_edge_mlp import sparse_gnn_edge_mlp_layer from .gnn_film import sparse_gnn_film_layer from .rgat import sparse_rgat_layer from .rgcn import sparse_rgcn_layer from .rgdcn import sparse_rgdcn_layer from .rgin import sparse_rgin_layer
from django.db import models # Create your models here. class CreateBetLotto(models.Model): numberLotto = models.IntegerField() top = models.BooleanField(default=False,null=False,blank=False) down = models.BooleanField(default=False,null=False,blank=False) price = models.IntegerField() class Employee(...
casa = float(input('Valor da Casa: R$')) salario = float(input('Valor do salário: R$')) tempo = int(input('Quantos anos para pagar: ')) prest = casa / (tempo * 12) prestmax = salario * 0.3 if prest > prestmax: print('Como o valor da prestação R${:.2f} ultrapassa o limite de 30% do salário (R${:.2f}), o empréstimo...
# Generated by Django 3.2.9 on 2021-11-30 00:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dso', '0020_dso_priority'), ] operations = [ migrations.AlterField( model_name='dso', name='priority', f...
import miind.grid_generate as grid_generate def cond(y,t): E_r = -65e-3 tau_m = 20e-3 tau_s = 5e-3 v = y[0]; h = y[1]; v_prime = ( -(v - E_r) - (h * v) ) / tau_m h_prime = -h / tau_s return [v_prime, h_prime] grid_generate.generate( func = cond, timestep = 1e-05, times...
import py.path import uritools from ..decorators import signature from ..inner.uritools import uridisplay class Source(object): """ABC for sources.""" def cache(self, cache): """Generates a filesystem local source from this source. The :class:`~arx.sources.files.File` thus returned can be us...
""" Helper functions for osbrain (usually for testing purposes). """ import re import time from uuid import uuid4 def regex_count_in_list(regex, strings): """ Returns ------- int The number of times a regular expression was found in a list of strings. """ matches = 0 for ca...
T = int(input()) for test in range(0, T) : A, B = input().split() print(int(A) + int(B))
from django.contrib import admin from . import models class ManufacturerAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'slug', 'website', 'description', 'created', 'updated') admin.site.register(models.Manufacturer, ManufacturerAdmin)
from tkinter import * from center_tk import Center_root from tkinter.scrolledtext import ScrolledText import os , threading from tkinter import ttk class _entry(Entry) : def __init__(self , perent , *args , **kwargs): Entry.__init__(self , perent , *args , **kwargs) self.pop = Menu(self ,tearoff =0 ...
""" Usage: comigean get-genomes [--help] [options] <OUTDIR> <REF_DIR> [--USER_GENOMES=<PATH>] [--REF_TAXA=<TAXA>] [--OUTGROUP_TAXA=<TAXA>] Required positional arguments: OUTDIR Path to a directory to download genomes & proteomes REFDIR Path to da...
# Imports import csv import sys from datetime import datetime import time from random import randint import math from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics.pairwise import euclidean_distances import numpy as np import math import tensorflow as tf # Path to data inputFile = sys.arg...
# file.py file = open('test.log', 'r', encoding='utf8') sizeLimits = 209715200 # byte ==200m position = 0 lines = file.readlines(sizeLimits) try: while not file.tell() - position < 0: position = file.tell() else:
import requests import re import tumblr_client import html from datetime import datetime def append_to_file(filename, contents): with open(filename, 'a', encoding='utf8') as file: file.writelines(contents + '\n') # inline tags keep text together visually (<b>S</b>ame) # non-inline tags keep t...
""" Django settings for Eportal project. Generated by 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os i...
''' This module is a self contained routine to ransack Bing for results around a query. The main entry point is class SearchBing()::runSearchEngine. Notes: - You'll want to substitute your own application key (self.key) if using it a lot - It depends on module b_openUrl.py (this wraps urllib2 functions) - The s...
%python #install prerequisite modules in Databricks #%pip install pyspark from pyspark.sql.functions import col, countDistinct, isnan, avg, length, max, min def categorical_summarized(df, dfName, limit): # spark SQL data summary functions # list of columns dfCol = df.columns rowCount = df.count() ...
import numpy as np from tqdm import tqdm import pytorch_ssim def ssim(vae, images): decoded_images,_,_ = vae(images.view(images.shape[0],784)) ssim_list = list() for i in tqdm(range(images.shape[0])): ssim_list.append(pytorch_ssim.ssim(images[i].view(1,1,28,28), decoded_images[i].view(1,1,28,28))....
# Time: O(n) ~ O(n^2) # Space: O(n) class Solution(object): def maxProduct(self, words): """ :type words: List[str] :rtype: int """ def counting_sort(words): k = 1000 # k is max length of words in the dictionary buckets = [[] for _ in xrange(k)] ...
from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from debug_toolbar.debug.version import DebugVersions from debug_toolbar.panels import DebugPanel class VersionDebugPanel(DebugPanel): """ Panel that displays the Django version. """ name = 'Ve...
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors # For information on the respective copyright owner see the NOTICE file # # 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 # #...
#!/usr/bin/env python3 #script desenvolvido primeiramente para ser executado em sistemas Linux. import re import getopt import os import sys import requests from html.parser import HTMLParser import time import random import smtplib import datetime,pytz import pymongo from pymongo import MongoClient from validador imp...
# Copyright 2018-2019 SourceOptics Project Contributors # # 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...
from difflib import SequenceMatcher def run(arguments): with open(arguments[0], encoding='utf-8') as fp: text1 = fp.read() #text1 = text1.decode('utf-8') fp = open(arguments[1], encoding='utf-8') text2 = fp.read() fp.close() #text2 = text2.decode('utf-8') utf_char = '\u00a0'...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from panda3d.core import * import random, string, json, zipfile, argparse, time, midi from direct.task.Task import Task from direct.gui.DirectGui import * from direct.interval.IntervalGlobal import * from direct.showbase.ShowBase import ShowBase from direct.gui.O...
from .solids import bash_command_solid, bash_script_solid from .version import __version__ __all__ = ['bash_command_solid', 'bash_script_solid']
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator import os import sys import glob if len(sys.argv) != 2: raise Exception("wrong usage: python tensorboard_summarize.py <path_to_events>") step = 350 metrics = {} metrics_ema = {} exceptions = ['learning_rate', 'consistency_weight'...
import os # Training image data path #IMAGEPATH = 'data/face/' #IMAGEPATH = '../models/train.txt' IMAGEPATH = '../../../../data/faces/' # LFW image data path LFW_IMAGEPATH = '../data/LFW/lfw-deepfunneled/' # Path to caffe directory #CAFFEPATH = '~/caffe' CAFFEPATH = '~/anaconda3/bin' # Snapshot iteration SNAPSHOT_I...
import sys import train_model import eval_results import torch import torch.optim as optim import torch.nn as nn import pickle import os import pandas as pd import numpy as np # local imports from dataset import get_data_loaders from dataset_chunking_fxns import subsample_df_by_groups DATA_DIR = '../../data' def s...
# TODO: properly handle enumerated nodes import os.path import sys #import xml.etree.ElementTree as ET import lxml.etree as ET from props import PropertyNode, root # internal xml tree parsing routine def _parseXML(pynode, xmlnode, basepath): overlay = 'overlay' in xmlnode.attrib exists = xmlnode.tag in pyno...
# -*- coding: utf-8 -*- import json class DataType(object): def __init__(self, description, defaultvalue=None): self.description = description self.defaultvalue = defaultvalue class Interger(DataType): pass class Float(DataType): pass class String(DataType): pass class DateTime...
from .. import DBType, Insert, sirix_sync, SirixServerError import httpx import json import cmd import argparse import shlex from datetime import datetime import getpass from pathlib import Path from xml.etree import ElementTree as ET def delete_parser(): parser = argparse.ArgumentParser( description=f"...
from unittest import TestCase class TestMain(TestCase): def test_main(self): self.assertTrue(True)
from hashlib import sha1 import json import re import requests from django.conf import settings from django.core.exceptions import SuspiciousOperation from desecapi import metrics from desecapi.exceptions import PDNSException, PDNSValidationError, RequestEntityTooLarge NSLORD = object() NSMASTER = object() _config...
# mapper.py # Ryan Zembrodt # Lines to sentences code partially taken/modified from project with Dr. Harrison import re import sys from unidecode import unidecode import zipimport importer = zipimport.zipimporter('nltk.mod') nltk = importer.load_module('nltk') try: from nltk.corpus import stopwords except Exceptio...
from .ping import ping from .validator import StrictDraft7Validator from .click_options import simple_verbosity_option, show_trace_option from .utils import get_module_from_file __all__ = [ "RenderJSON", "ping", "StrictDraft7Validator", "simple_verbosity_option", "show_trace_option", "get_modu...
import pandas as pd pokemon = pd.read_csv('data/pokemon.csv', index_col=0) pokemon = pokemon.loc[ : , ['attack', 'defense', 'capture_rt', 'total_bs', 'legendary']] # Make a groupby object on the column legendary # Find the maximum and minimum value of each column for each legendary groups using # .agg() and save t...
import b y = b.x
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-08-29 20:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('problem', '0005_auto_20170825_2201'), ] operations = [ migrations.AlterFiel...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-02-14 19:39:08 # @Author : eclipse_sv (eclipse_sv@163.com) # @Link : https://eclipsesv.com # @Version : $Id$
# Copyright 2021 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 applicable law or agreed to...
from copy import deepcopy from django import forms from django.conf import settings from django.core.validators import MaxValueValidator from django.db import models import django_filters from django_filters.constants import EMPTY_VALUES from django_filters.utils import get_model_field, resolve_field from nautobot.dc...
import re from streamlink.plugin import Plugin from streamlink.plugin.api import http from streamlink.compat import urljoin from streamlink.stream import HLSStream class TVNBG(Plugin): url_re = re.compile(r"https?://(?:live\.)?tvn\.bg/(?:live)?") iframe_re = re.compile(r'<iframe.*?src="([^"]+)".*?></iframe>'...
"""Unit test package for op-env."""
""" In this example a custom specs_route is set. """ from flask import Flask try: from http import HTTPStatus except ImportError: import httplib as HTTPStatus from flasgger import Swagger swagger_config = { "headers": [ ], "specs": [ { "endpoint": 'specifications', "...
"""This superclass represents our get_value abstract class""" from abc import abstractmethod from typing import List from utils.setting import Setting class SettingMitigator(Setting): @abstractmethod def h_mit_bound(self, param_l_list: List[float]) -> float: """ new Lyapunov standard_bound ...
# @Author: Manuel Rodriguez <valle> # @Date: 08-Jul-2017 # @Email: valle.mrv@gmail.com # @Last modified by: valle # @Last modified time: 27-Feb-2018 # @License: Apache license vesion 2.0 import os try: FA_ENTER = unichr(0xf090) except Exception as e: unichr = lambda s: chr(s) PATH_RES = os.path.join(os....
from django.db import models from django.conf import settings from django.utils.functional import cached_property from . import commands class WebOperator(models.Model): """ A web operator has limited access to console commands via a web interface. """ SURVIVAL = 0 CREATIVE = 1 ADVENTURE ...
# ---------------------------------- Imports --------------------------------- # import logging import discord from discord.ext import commands from discord_slash import cog_ext, SlashContext import lavalink from ... import config from ..core.voice import VoiceStateManager as VSM from ..core.music import Music from ....
""" thanks.py - FlutterBitch anger module Author: miggyb About: http://berrytube.tv/ """ import random def thanks(willie, input): greeting = random.choice(( 'Shut up', 'I hate you', 'Go away', 'Eat a boat', 'Leave me alone', 'Get bent', 'Screw you', 'Nopony loves you', ...
def calc(a): s = set([2]) for n in range(1, 2 * a + 1, 2): r = (2 * n * a) % (a * a) s.add(r) return max(s) if __name__ == "__main__": print sum([calc(a) for a in range(3, 1001)])
from iotfs.listener.listener import Listener class CustomListener(Listener): def __init__(self): super().__init__() def process(self, item): with open("./log", "a+") as f: f.write(item.event.name + "_" + item.operation.name + "\n")
""" population.py ~~~~~~~~~~~~~ This stores a fixed set of genomes, and provides methods to create new generations based on the existing one. """ import random import collections from operator import attrgetter from genome import Genome SIZE = 270 # The static size that the population will be kept at MATE_DIST = 50 ...
""" OMEN API endpoint definition. ## noteworthy URLs: - The OpenAPI descriptor is exposed as `/omen/api/1.0/openapi.json`. - The API itself lives under `/omen/api/1.0/`. - A visual instance of Swagger UI is available under `/omen/api/1.0/ui`. """ # pylint: disable=no-self-use,too-many-instance-attributes import logg...
"""Contacts are quite simple. It contains some links to tech riders and contact information in a single database row. They basically could be hard-coded to the site too, but for some flexibility they'll be in the DB.""" import json import unittest from flask_caching import Cache from sqlalchemy import desc from app ...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
from boa3.boa3 import Boa3 from boa3.exception.CompilerError import MismatchedTypes from boa3.neo.vm.opcode.Opcode import Opcode from boa3.neo.vm.type.Integer import Integer from boa3_test.tests.boa_test import BoaTest class TestWhile(BoaTest): def test_while_constant_condition(self): jmpif_address = Int...
import numpy as np import pytest import starfish.data from starfish import FieldOfView from starfish.image import Filter from starfish.spots import FindSpots from starfish.types import TraceBuildingStrategies @pytest.mark.skip('This test runs but takes forever') def test_allen_smFISH_cropped_data(): # set rando...
from .file import File # noqa from .subscriber import Subscriber # noqa
import gdal, ogr, osr, os, time import numpy as np import CM_intern.common_modules.array2raster as a2r #array2raster def rasterize(inRasterPath, inVectorPath, fieldName, dataType , outRasterPath=None, noDataValue=0, saveAsRaster=False , pixelWidth=100, pixelHeight=-100): inRastData...
import time def test_slow_passing(): time.sleep(2) assert True
from django.apps import AppConfig class OurgamesConfig(AppConfig): name = 'ourGames'
import os def getConf(confKey): db_name = os.getenv('SCHEDULE_WAREHOUSE_DB_NAME', 'db_name') db_username = os.getenv('METER_WAREHOUSE_DB_USERNAME', 'username') db_password = os.getenv('METER_WAREHOUSE_DB_PASSWORD', 'password') db_host = os.getenv('METER_WAREHOUSE_DB_HOST', 'hostip') db_port = os.g...
# -*- coding:utf-8 -*- # &Author AnFany # 大数加、减法 # 正实数的减法 def big_subtraction(a, b): """ 计算两个正实数的减法 :param a: 实数 :param b: 实数 :return: a-b的差 """ if a == b: return '0' # 获取实数的小数点位数 decimal_a = 0 if '.' in a: decimal_a = len(a) - a.index('...
# dash libs import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html # pydata stack import pandas as pd from sqlalchemy import create_engine import plotly.express as px from fpl_test import DB_ENGINE_LOC import pdb # set params conn = create_engi...
from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional from yaml import safe_load from .data_loader import DataFormat @dataclass class ModelVersion: """Model version details and schema.""" name: str type: str predictions: Dict...
'''Train a Bidirectional LSTM on the IMDB sentiment classification task. Output after 4 epochs on CPU: ~0.8146 Time per epoch on CPU (Core i7): ~150s. ''' from __future__ import print_function import numpy as np np.random.seed(1337) # for reproducibility from keras.preprocessing import sequence from keras.models im...
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the COPYING file. import os import posixpath import qisys.qixml def convert_project(project): """ Convert a qidoc2 project so it's still usable in qidoc2 and q...
#!/usr/bin/env python3 import os os.environ['KERAS_BACKEND'] = 'tensorflow' from keras.datasets import reuters from keras.preprocessing import sequence from keras.utils.np_utils import to_categorical import numpy as np from reuters_model import createHierarchicalAttentionModel batch_size = 16 max_features = 20000 ma...