text stringlengths 3.07k 12.6k |
|---|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from collections import OrderedDict
from icecream import ic
import os
import glob
import sys
from dataset import MyDataLoader
from tqdm import tqdm
import numpy as np
from gML... |
import torch
import torch.nn as nn
import os
import math
import copy
import graph
import numpy as np
from rdkit import Chem
STOP = None
ATOM_TYPES = ['C', 'N', 'O', 'F', 'P', 'S', 'CL', 'BR', STOP]
ATOMIC_NUM = [6, 7, 8, 9, 15, 16, 17, 35]
BOND_TYPES = [Chem.BondType.SINGLE, Chem.BondType.DOUBLE, \
Ch... |
import gc
from datetime import datetime
import logging
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split # train/test data split
from sklearn.metrics import accuracy_score
import tensorflow as tf
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from tens... |
import math
import math
import os
import numpy
import pandas
import torch
from helpers.eval import get_bleu_score
from helpers.text import devectorize
from helpers.viz import seq2seq_attentions
from models.translate import seq2seq_translate_ids, \
seq2seq_output_ids_to_file
from modules.callbacks import TrainerCa... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 11:16:34 2016
@author: <NAME>
"""
from sys import argv, stderr
import argparse
from datetime import datetime
def parse_arguments():
"""Parse arguments passed to script"""
parser = argparse.ArgumentParser(description=
"This script is designed to identify r... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import re
def _intorfloat(v):
vi = int(v)
if v == vi:
return vi
return v
def _vec2string(x, y, suf=""):
i... |
# -*- coding utf-8 -*-#
# ------------------------------------------------------------------
# Name: core
# Author: liangbaikai
# Date: 2020/1/16
# Desc: there is a jsonfy core
# ------------------------------------------------------------------
import json
from datetime import datetime
class BaseDe... |
import io
import re
import ssl
import urllib
from django.conf import settings
from django.contrib import sessions
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core import exceptions
from django.http.response import HttpResponse, HttpRes... |
"""
DESCRIPTION
-----------
For each directory provided on the command line the
headers all of the FITS files in that directory are modified
to add information like LST, apparent object position, and more.
See the full documentation for a list of the specific keywords
that are modified.
Header patching
^^^^^^^^^^^^^^... |
"""Bazel rules and macros for running tsec over a ng_module or ts_library."""
load("@bazel_skylib//lib:new_sets.bzl", "sets")
load("@npm//@bazel/typescript/internal:ts_config.bzl", "TsConfigInfo")
load("@build_bazel_rules_nodejs//:providers.bzl", "DeclarationInfo")
load("@npm//tsec:index.bzl", _tsec_test = "tsec_test"... |
import os
import time
from typing import List
import yaml
import datetime
from pathlib import Path
import pytz
from redis import Redis
from pottery import Redlock
from redis_pal import RedisPal
from google.cloud.storage.blob import Blob
from dagster.core.definitions.run_request import PipelineRunReaction, SkipReason
f... |
import json
import numpy as np
from scipy.integrate import solve_ivp
from matplotlib import pyplot as plt
from math import cos
from modeling.cortical_sheet import OscillatorArray
from modeling.wavelet import make_kernel
from modeling.interaction import Interaction
np.set_printoptions(precision=3, suppress=True)
cl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import EurocReader
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pose.PyLie.transform as tf
def sync_trajectory(gt_traj_file, output_traj_file):
gt_traj = EurocReader.read_ground_truth(gt_traj_file)
out_traj = E... |
# -*- coding: utf-8 -*-
import abc
import json
from splash import defaults
from splash.engines.webkit import WebkitBrowserTab
from splash.render_scripts import (
BaseRenderScript,
BaseFixedRenderScript,
stop_on_error,
)
class WebkitRenderScript(BaseRenderScript):
""" Base class for Webkit-based rende... |
import dill
import torch
import logging
import numpy as np
from torchtext import data
logger = logging.getLogger(__name__)
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class ClassifierHelper:
def __init__(self, model, text_field, label_field):
if not isinstance(model, torch.n... |
import discord
from discord.ext import commands, tasks
from search.youtube import YoutubeUtils, YtAccount
import tools.members as Members
import tools.channels as ChannelTools
import tools.error as Error
class Youtube(commands.Cog):
def __init__(self, client):
self.client = client
self.youtube = ... |
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from .models impo... |
import os
import typing
from PyQt5 import QtWidgets, uic, QtCore, Qt, QtGui
from PyQt5.QtWidgets import QLabel, QTextEdit, QHBoxLayout, QVBoxLayout, QLineEdit, QCheckBox, QWidget, QGridLayout, \
QSpacerItem, QSizePolicy, QPushButton, QFileDialog, QComboBox
from ament_index_python import get_resource
class Abstrac... |
from typing import List, Type
import click
from .dependencies import DependencyGraph
from .contract import Contract
VERBOSITY_QUIET = 0
VERBOSITY_NORMAL = 1
VERBOSITY_HIGH = 2
def get_report_class(verbosity: int) -> Type['BaseReport']:
return {
VERBOSITY_QUIET: QuietReport,
VERBOSITY_NORMAL: No... |
#!/usr/bin/python -o
import argparse
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import pandas as pd
import numpy as np
import pymc3 as pm
import pickle
from prev_ts_GP import extractData
def plotPrediction(ax,X,y,N,pred,mindate,lag=None,prev_mult=1,plot_gp=False):
"""Predict... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
splice complie command for all kind of targe... |
import argparse
from speedypy.common import get_data
from speedypy.args import subcommand, argument, get_exclude_servers, \
subparsers_map
args = []
args.append(argument(
'-o', '--outfile',
default=None,
type=argparse.FileType(mode='wb'),
help="path to an output file (default: open an X window)"... |
#!/usr/bin/env python3
'''
kinematic_substructuring.py
This script demonstrates the kinematic substructuring algorithm
described in Generalized Coordinate Partitioning for Complex
Mechanisms Based on Kinematic Substructuring.
Copyright(c) 2015 <NAME>
All rights reserved.
Redistribution and use in source and binary ... |
import logging
import numpy as np
import warnings
import numpy as np
from numpy.typing import ArrayLike
from typing import Tuple, Union
from ..utils import anscombe
logger = logging.getLogger(__name__)
def corr(
y1: ArrayLike, y2: ArrayLike, axis: Union[None, int, Tuple[int]] = -1, eps: int = 1e-8, **kwargs
) -... |
import torch
from numpy import pi
from torch.utils.data import TensorDataset
from sggm.definitions import STAGE_SETUP_SHIFTED_SPLIT
"""
Helper for shifted datamodules
"""
def t_log(x: float) -> torch.Tensor:
return torch.log(torch.Tensor([x]))
def log_density(x: torch.Tensor) -> torch.Tensor:
"""Computes... |
'''
* Author: <NAME>
* Date: 9/14/13
* Time: 3:43 PM
*
* This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/.
'''
from collections import namedtuple
import csv
from da... |
# MIT License
#
# Copyright (c) 2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
#
# 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... |
import ui
import validator
def _color_error(attr):
raise Exception(f"'{attr}' expects expects a valid color string, RGB tuple, or RGBA tuple")
def _font_error(attr):
raise Exception(f"'{attr}' expects a 2 tuple like: (font_family_str, float_or_int)")
def _int_or_float_error(attr, tup=False):
raise Exception(f"'... |
import requests
import pandas as pd
import folium
from folium.plugins import MiniMap
import pickle
from time import time
def get_live_station(url):
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
stations = response.json()
output = []
for station in stations['featu... |
'''
Created with love by Sigmoid
@Author - <NAME> - <EMAIL>
'''
# Importing all libraries
import numpy as np
import pandas as pd
import random
import sys
from math import floor
from .erorrs import NotBinaryData, NoSuchColumn
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
cla... |
from training_evaluation import train, evaluate
from dataset import _sorted_checkpoints, set_seed, load_and_cache_examples
from model import logger
import glob
import logging
import os
import torch
from transformers import (
WEIGHTS_NAME,
AutoConfig,
AutoModelWithLMHead,
AutoTokenizer,
)
class Args(... |
import numpy as np
from sklearn.model_selection import train_test_split
from skimage.util import random_noise
import torch
import torch.utils.data as Data
from tqdm import tqdm
import os
from PIL import Image
# 首先,从上述链接中下载完STL10的数据集后,开始对数据做预处理。STL10中都是96*96的RGB图片,训练集放在了train_X.bin的文件中,可以用做自编码器的无监督学习,下面是第数据的预处理:
def r... |
import numpy as np
import quaternion
class Euler:
__slots__ = ['phi', 'th']
def __init__(self, phi, th):
self.phi = phi
self.th = th
class XY:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
def apply_rotation(v, rot):
return rot * v * rot... |
from __future__ import annotations
from dataclasses import dataclass, fields
from typing import Any, Generic, Literal, NamedTuple, TypeVar, overload
from coil.protocols._bound import Bound, TwoWayBound
from ._bindings import bind
from ._core import bound_attr_name, notify_subscribers, tail
from ._runtime import runt... |
from faker import Faker
import random as rnd
import os, argparse, logging, gzip, shutil
import pandas as pd
from multiprocessing import Pool
from functools import partial
logging.basicConfig(format='%(asctime)s %(levelname)-10s %(message)s', datefmt="%Y-%m-%d-%H-%M-%S",
level=logging.INFO)
def parse_args():
ap... |
"""
Trains cifar on bn network
Usage:
run.py [options]
Options:
--save SAVE subdirectory to save logs [default: logs]
--batchSize BATCHSIZE batch size [default: 128]
--learningRate LEARNINGRATE learning rate [default: 1]
--learningRateDecay LRDECAY learning rate decay [default: 1e-... |
import struct
import bitstring
import Peer
class Request:
def __init__(self,Buffer,piece_length,chunk_length,pos,seconds):
self.Buffer = Buffer
#self.piece_length = piece_length
self.pos = pos
self.seconds = seconds
self.ps = pos + seconds
self.chunk_length = chunk_l... |
import os
import ctypes
import numpy
import pandas
from numpy.ctypeslib import ndpointer
import pkg_resources
import platform
import struct
from fps_inspector_sdk.exit_codes import PresentMonExitCodes
class FpsInspectorError (Exception):
def __init__ (self, message, exit_code):
detailed_message = '%s:%d %... |
from qulacs import Observable
from qulacs import QuantumState, QuantumCircuit
from qulacs.gate import CZ, RY, RZ, merge
from numpy import polyfit
import numpy as np
import matplotlib.pyplot as plt
def convert_openfermion_op(n_qubit, openfermion_op):
"""convert_openfermion_op
Args:
n_qubit (... |
'''
本模块用于部分方程求解运算
This module is used for solving equations
'''
import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
class Scatter():
'''
求解散点方程
求解由一系列二维散点组成的曲线的交点
参数
----
x:一维或二维列表,二维列表表示多组散点
y:一维或二维列表,二维列表表示多组散点
acc:浮点数类型,可选,插值精度,默认0.1
... |
'''
Definitions of specific models (e.g. the DCNN used in Percival paper)
Copyright(C) 2017 Engineering Department, University of Cambridge, UK.
License
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 th... |
from .vector import Vec3
# UV coordinates (includes w for perspective correction)
class UV:
def __init__(self, u = 0, v = 0, w = 0):
self.u = float(u)
self.v = float(v)
self.w = float(w)
class Triangle:
def __init__(self, v1 = None, v2 = None, v3 = None, uv1 = None, uv2 = None, uv3 = N... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pycompat - Library to check Python and System version in a easy way.
#
__author__ = '<NAME>'
__version__ = '0.1.0'
__license__ = 'MIT'
'''
The MIT License (MIT)
Copyright (c) 2014 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
o... |
import requests
from bs4 import BeautifulSoup
import random
import os
import time
import pymysql
HEADERS = (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36',
'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14',
'Mozilla/5.0 (Win... |
import os
import sys
from MiscUtils.PropertiesObject import PropertiesObject
class PlugInError(Exception):
"""Plug-in error."""
class PlugIn:
"""Template for Webware Plug-ins.
A plug-in is a software component that is loaded by Webware in order to
provide additional Webware functionality without n... |
# Copyright (c) 2017 <NAME>.
# Uranium is released under the terms of the LGPLv3 or higher.
from typing import Optional
from PyQt5.QtCore import QObject, pyqtProperty, Q_ENUMS, pyqtSignal
from UM.FlameProfiler import pyqtSlot
from datetime import timedelta
import math
from UM.i18n import i18nCatalog
i18n_catalog = i... |
#!/usr/bin/env python
from __future__ import print_function
import sys
try:
import rfc822
except ImportError as e:
import rfc822py3 as rfc822
import time
import json
from sqlite3 import connect
try:
from urllib import urlopen, urlencode, quote_plus
except ImportError as e:
from urllib.... |
import torch
import torch.nn
import re
import torch.nn.functional
from eight_mile.utils import Offsets
from typing import Dict, Optional, Callable
import numpy as np
from collections import defaultdict, Counter
class PrefixBeamSearch:
def __init__(self, vocab_list, alpha=0.2, beta=5.0, beam: int = 100, lm_file: O... |
from ...util import set_units
from ...config import default_units, observing_bands
from ...field import Grid, SeparatedCoords, CartesianGrid, Field, UnstructuredCoords
import numpy as np
import astropy.constants as const
import warnings
import astropy.units as u
__all__ = ['make_spectrum_unit_field', 'make_wavelengt... |
#***************************************************************************#
# Copyright (c) 2016 - 2017, University of California, Berkeley. #
# #
# Author(s): <NAME>, EECS Department, UC Berkeley. #
# ... |
"""Provides data for the ucf11 dataset.
The dataset scripts used to create the dataset can be found at: convert_ucf11.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
from datasets import dataset_utils
from collecti... |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
/**
* Copyright 2020 Tianshu AI Platform. 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... |
"""
640. Solve the Equation
Medium
Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are ... |
"""This module include all core manipulation for server"""
import os
import shutil
from pathlib import Path
import discrete_kit.configuration.config
import jsonschema.validators
from discrete_kit.functions.shape_functions import *
from discrete_kit.validator.schema_validator import *
from configuration import config
fr... |
import random
import operator
import tkinter
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot
import matplotlib.animation
import agentframework
import csv
import requests
import bs4
import time
start_time = time.time()
# We set the random seed so we can see repeatable patterns
random.seed(0)
#Func... |
import argparse
import torch
from det3d import torchie
from det3d.datasets import build_dataloader, build_dataset
from det3d.models import build_detector
from det3d.torchie.apis.train import example_convert_to_torch
from det3d.torchie.trainer import load_checkpoint
from det3d.torchie.trainer.trainer import example_to... |
from modules.FlaskModule.FlaskModule import flask_app
from opentera.modules.BaseModule import BaseModule, ModuleNames
from opentera.config.ConfigManager import ConfigManager
# Same directory
from .TwistedModuleWebSocketServerFactory import TwistedModuleWebSocketServerFactory
from .TeraWebSocketServerUserProtocol impo... |
import sys, os, re
import numpy as np
from kdd_categories import category_str2int, category_int2str
class Kdd_Schema(object):
def __init__(self, schema_file, label_type):
"""
Inputs:
- schema_file : the file with the schema description
- label_type : int, binary, or one-hot... |
import os, h5py
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
from torchvision.transforms import Compose, Normalize, ToTensor
from lib.alphabet import strLabelConverter
from lib.path_config import data_roots, data_paths
class Hdf5Dataset(Dataset):
def __init__(self, r... |
import datetime
import discord
import os
import random
import re
import string
from discord.ext import commands
from sys import argv
class Extras:
"""
Extra things.
"""
def __init__(self, bot):
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
prune_key = "n... |
#!/usr/bin/env python
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2009-2020 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.ec... |
""" types for gihtub_linter dependabot tests """
from typing import Any, Dict, List, Optional, TypedDict
import pydantic
import pytz
from ruyaml.scalarstring import DoubleQuotedScalarString
from .constants import DEPENDABOT_SCHEDULE_INTERVALS, PACKAGE_ECOSYSTEM
class DependabotSchedule(pydantic.BaseModel):
""... |
import pandas as pd
import numpy as np
from tqdm.auto import tqdm
from kgextension.utilities_helper import is_valid_url, url_exists
from kgextension.endpoints import DBpedia
from kgextension.sparql_helper import endpoint_wrapper
from kgextension.uri_helper import uri_querier
def link_validator(df, columns, purge=True... |
#! /usr/bin/env python
import sys
import re
import os
import subprocess
import shutil
import tempfile
from datetime import date
from collections import defaultdict
from natsort import natsorted
from file_builders import build_card_files
SCRIPT_DIR = "/home/teddy/projects/dixit/cards"
FRONTEND_DIR = "/home/teddy/pr... |
# Copyright 2016 Google 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 applicable law or ... |
#
# Copyright 2015 Quantopian, 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... |
import os
import shutil
import numpy as np
import open3d as o3d
from open3d._ml3d.datasets.utils import BEVBox3D
import supervisely_lib as sly
def kitti_paths(path, mode='write'):
shutil.rmtree(path, ignore_errors=True) # WARN!
os.mkdir(path)
path = os.path.join(path, 'training')
bin_dir = os.path.... |
# -*- coding: utf-8 -*-
# Author: XuMing <<EMAIL>>
# Brief: seq2seq model with keras (refs: keras-example)
import numpy as np
from keras.callbacks import LambdaCallback, EarlyStopping
from keras.callbacks import ModelCheckpoint
from keras.layers import Input, LSTM, Dense
from keras.models import Model
from pycorrector... |
import tweepy
import time
import schedule
import random
import re
import configparser
config = configparser.ConfigParser()
config.read('auth.ini')
auth = tweepy.OAuthHandler(config['AUTH']['auth_token'],config['AUTH']['auth_secret'])
auth.set_access_token(config['AUTH']['access_token'],config['AUTH']['access_secret']... |
import os
os.environ['GDAL_DATA'] = os.environ['CONDA_PREFIX'] + r'\Library\share\gdal'
os.environ['PROJ_LIB'] = os.environ['CONDA_PREFIX'] + r'\Library\share'
import itertools
import time
from scipy import ndimage
import ogr
import gdal
import numpy as np
from fit_plane_to_points import fit_plane
from rasteration im... |
# MIT License
#
# Copyright (c) 2022 TrigonDev
#
# 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, modify, merge, pu... |
from __future__ import absolute_import
import scipy.signal
from autograd.core import primitive
import autograd.numpy as np
import numpy as npo # original numpy
import itertools as it
from numpy.lib.stride_tricks import as_strided
from builtins import range, zip
from future.utils import iteritems
def prod(x):
retur... |
from db import session, User, create_new_user, check_if_user_exists
from telegram import ReplyKeyboardMarkup
from telegram.ext import ConversationHandler
from notion.client import NotionClient
from notion.block import TextBlock
TYPING_NOTION_API_KEY, TYPING_NOTION_PAGE_ADDRESS = range(2)
keyboard = ReplyKeyboardMarku... |
from django.shortcuts import render
from django.http import Http404
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import mixins
from r... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
__author__ = 'mdavid'
import json
import logging
import logging.handlers
import os
import sys
import urllib
from ecdsa import curves
from ecdsa.der import UnexpectedDER
from ecdsa.keys import VerifyingKey, BadDigestError, BadSignatureError
from flask import request, current_app, Response
from functools import wraps
f... |
from datetime import datetime, date
from osmanager import db, login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Strin... |
#!/usr/bin/python
import scipy
from scipy import stats
import numpy as np
from math import sqrt, asin, cos, sin, atan2
import networkx as nx
from .env_utils import Obstacle, Environment
from .geometry_utils import *
import sys
import pickle
class EnvironmentGenerator(object):
def __init__(self, x_range, y_range... |
"""
Actor-Critic using TD-error as the Advantage, Reinforcement Learning.
The cart pole example. Policy is oscillated.
View more on my tutorial page: https://morvanzhou.github.io/2_tensorflow_old/
Using:
tensorflow 1.0
gym 0.8.0
"""
import numpy as np
import tensorflow as tf
import gym
np.random.seed(2)
tf.set_ran... |
# -*- coding: utf-8 -*-
"""
File resnext.py
@author: ZhengYuwei
"""
from tensorflow import keras
def _conv_bn(**conv_params):
""" 返回设定结构的网络函数(convolution -> batch normalization)
:param conv_params: 包含参数:
filters: 整数,输出的channel数
kernel_size: 卷积核大小,(width, height)
strides: 步长,(width, hei... |
"""Class that counts the emotes from chat messages."""
import logging
import sqlite3
import time
from collections import deque
from bot.paths import DATABASE_PATH
class EmoteCounter(object):
"""Generic class to handle emote per minute."""
def __init__(self, t=60):
"""Set up counters."""
# Qu... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Interfaces to generate reportlets."""
import os
import time
import re
import pandas as pd
from collections import Counter
from nipype.interfaces.base import (
traits, TraitedSpec, BaseInterfaceInpu... |
"""distutils.spawn
Provides the 'spawn()' function, a front-end to various platform-
specific functions for launching another program in a sub-process.
Also provides the 'find_executable()' to search the path for a given
executable name.
"""
import sys
import os
from distutils.errors import DistutilsPlatf... |
import streamlit as st
import joblib
import os
import numpy as np
attrib_info = """
#### Attribute Information:
- Age 1.20-65
- Sex 1. Male, 2.Female
- Polyuria 1.Yes, 2.No.
- Polydipsia 1.Yes, 2.No.
- sudden weight loss 1.Yes, 2.No.
- weakness 1.Yes, 2.No.
- Polyphagia 1.Yes, 2.No.
- ... |
# -*- coding: utf-8 -*-
"""
test_autosummary
~~~~~~~~~~~~~~~~
Test the autosummary extension.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from six import iteritems, StringIO
from sphinx.ext.autosummary import mangle_signature, impo... |
import tkinter as tk
from PIL import ImageTk, Image
import speech_recognition as sr
import os
import moviepy.editor as mp
from pydub import AudioSegment
from pydub.silence import split_on_silence
from nltk.corpus import stopwords
from nltk.cluster.util import cosine_distance
import numpy as np
import networkx as nx
imp... |
import json
import logging
from typing import Any, Dict, List, Mapping, Optional, Union
import gremlin_python
from amundsen_common.models.table import Table
from amundsen_common.models.user import User as UserEntity
from gremlin_python.driver.driver_remote_connection import \
DriverRemoteConnection
from gremlin_py... |
#
# Copyright 2013 Apache Software Foundation
#
# 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 agree... |
import json
import io
import freezegun
import pytest
from FeedMandiant import MandiantClient
def mock_client():
MandiantClient._get_token = lambda x: 'token'
client = MandiantClient('url', 'username', 'password', False, False, 60, '90 days', 1, ['Malware'])
return client
def util_load_json(path):
wi... |
# Faster insertion and deletion than AVL, slower search
class Color:
RED = 1
BLACK = 2
class Node:
def __init__(self, data, parent=None, color=Color.RED):
self.data = data
self.color = color
self.parent = parent
self.left = None
self.right = None
class RedBlackTre... |
#!/usr/bin/env python
"""Given the output of jemalloc's `malloc_stats_print`, analyse and show
utilization information. Insipired by:
http://www.canonware.com/pipermail/jemalloc-discuss/2013-November/000675.html
"""
from __future__ import division
from __future__ import print_function
import re
import sys
def size... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from pandas_datareader.data import DataReader
import time
from collections import deque
import plotly.graph_objs as go
import random
app = dash.Dash('vehicle-data')
data_dict = {"Oil Temperature":oil_temps,
"Intake Temperature": intake... |
# Copyright 2019 DeepMind Technologies Ltd. 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 appl... |
# Larger CNN for the MNIST Dataset
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input
... |
import os
from time import sleep
from flask import render_template, abort, request, send_file, flash, redirect, url_for
import psutil
from arm.ui import app, db
from arm.models.models import Job, Config
from arm.config.config import cfg
from arm.ui.utils import convert_log, get_info, call_omdb_api, clean_for_filename
f... |
import requests
from unidecode import unidecode # retira todos os acentos de uma string
from bs4 import BeautifulSoup
import PySimpleGUI as sg
def escolha_da_palavra():
"""
Escolhe a palavra e cria o arquivo palavra.txt na qual ela será armazenada
:return: str randomizada pela API 'dicionário aberto'
... |
import collections
import sys
from multiprocessing import Pool
from shutil import get_terminal_size
from utils.tools.timer import Timer
class ProgressBar(object):
"""A progress bar which can print the progress"""
def __init__(self, task_num=0, bar_width=50, start=True):
self.task_num = task_num
... |
"""ALKIS Flurstuecke."""
import json, time
from gbd.core import db, log, util, config, debug
from gbd.plugins import alkis_adresse as adresse
from gbd.core.util import inline_format as _f
from . import index
def count():
return db.count(index.main_index)
def list_gemarkung():
rs = db.select(_f('''
... |
import json
import logging
import os
from pathlib import PurePath
from crum import get_current_request
from django.conf import settings
from django.db import transaction
from django.template.loader import render_to_string
from django.utils.translation import override
from django_ilmoitin.models import NotificationTemp... |
"""dropbox utilities."""
import sys
import base64
import pickle
import dropbox
import keychain
import clipboard
from stashutils import core
DB_SERVICE = "DropBox"
def dropbox_setup(username, stdin, stdout):
"""helper-interface to setup dropbox."""
_stash = core.get_stash()
Text = _stash.text_color # alias
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.