text
stringlengths
2
999k
__version_info__ = (0, 0, 57, 'alpha', 0) def get_version(version): main = '.'.join(str(x) for x in version[:3]) if version[3] == 'final': return main symbol = { 'alpha': 'a', 'beta': 'b', 'rc': 'rc', } return main + symbol[version[3]] + str(version[4]) __version...
"""============================================================= ~/pjtk2/utils/update_pjtk2/pjtk2_update_utils.py Created: 13 Mar 2020 10:49:34 DESCRIPTION: Utilities to get objects out of a Project Tracker database with unique identifiers so they can be moved from one version of Project tracker to the next. A. C...
# Purpose: Prepare Areas of Open Space (AOS) for ntnl liveability indicators # -- *** Assumes already in correct projection for project (e.g. GDA2020 GA LCC) *** # -- copies features within study region to project gdb # -- calculates geodesic area in hectares # -- makes temp...
#!/usr/bin/env python3 import itertools import gatenlphiltlab # annotation_file_path = "/path/to/annotation_file.xml" annotation_file_path = "/home/nick/hilt/pes/conversations/16/4-MG-2014-06-02_PES_3_consensus.xml" annotation_file = gatenlphiltlab.AnnotationFile(annotation_file_path) # Automatically links any ann...
import sys import logging from laka import LakaServer, Param, Handler, HandlerFailed, HandlerOK from laka.errors import ValidateError, HandlerNotFound, InvalidHandler, \ InvalidMessage, MakeCommandError, MakeResponseError, MakeHandlerResponseError # 定义命令 COMMAND_CREATE_USER = 101 # 返回码定义 SUCC...
import setuptools version = int(setuptools.__version__.split('.')[0]) assert version > 30, "tensorpack installation requires setuptools > 30" from setuptools import setup import os import shutil import sys # setup metainfo CURRENT_DIR = os.path.dirname(__file__) libinfo_py = os.path.join(CURRENT_DIR, 'tensorpack/libin...
""" User Manager testing. Executable directly using: python -m test.unit.managers.test_UserManager """ import json import unittest from datetime import datetime, timedelta from sqlalchemy import desc from galaxy import exceptions, model from galaxy.managers import base as base_manager from galaxy.managers import his...
#!/usr/bin/env python3 # # This file is part of LiteX-Boards. # # Copyright (c) 2015-2019 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause import os import argparse from migen import * from litex_boards.platforms import nexys_video from litex.build.xilinx.vivado import vivado_bui...
#!/usr/bin/env python # Copyright 2017 Calico 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/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
from empyrial import *
# -*- coding: utf-8 -*- from setuptools import setup from setuptools import find_packages with open('README.md') as f: README = f.read() with open('LICENSE') as f: LICENSE = f.read() setup( name='pCloud API', version='0.1', description='API that provides access to the data in pCloud infrastructu...
import json import logging import os import shutil import subprocess import sys import uuid from typing import List, Optional, TextIO, Union PROJECT_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir) PACK_CODE_APP = "pack_code_{}.sh" def project_absolute_path(*paths: str): return os.path....
# -*- coding: utf-8 -*- """DB""" import random import sys import pymongo from pymongo.errors import ConnectionFailure from sara.core.pre_processing import PreProcessing pre_processing = PreProcessing() # pylint: disable=R0903, C0103 class SingletonClient: """Generate a singleton the MongoDB client.""" clas...
#!/usr/bin/env python import os import argparse import configparser import requests try: import simplejson as json except ImportError: import json version = '%(prog)s 20180912' class VT(): def __init__(self): conffile = 'conf/exist.conf' conf = configparser.SafeConfigParser() con...
# 3rd-party imports import numpy as np class SporadicParticleSizes: """ A SporadicParticleSizes object holds altitude info of particle sizes and can interpolate them onto a model grid""" def __init__(self, altitude_grid, particle_size_grid, model_grid): """ Parameters ---------- ...
import torch from torch import nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, inchannel, outchannel,kernel_size,stride=2): super(ResidualBlock, self).__init__() self.stride = stride self.conv = nn.Sequential( nn.Conv2d(inchannel, out...
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
# coding: utf-8 """Base class of pre-processing. If you want to add new pre-processing method to extend HDNNP, inherits this base class. """ from abc import (ABC, abstractmethod) class PreprocessBase(ABC): """Base class of pre-processing.""" name = None """str: Name of this class.""" def __init__(...
from __future__ import absolute_import, division, print_function class GModelBackgroundExt(object): """An extension class implementing a robust GLM background algorithm.""" name = "gmodel" @classmethod def phil(cls): from libtbx.phil import parse phil = parse( """ ...
#!/usr/bin/env python3 from ruthie import cli if __name__ == '__main__': cli.main()
#!/usr/bin/env python3 try: import torch except ImportError: pass from easypbr import * config_file="./config/high_poly.cfg" view=Viewer.create(config_file) #puts the camera in a nicer view than default. You can also comment these two lines and EasyPBR will place the camera by default for you so that the scene...
# 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 ...
"""This program shows the different protections that PyTables offer to the user in order to insure a correct data injection in tables. Example to be used in the second tutorial in the User's Guide. """ from __future__ import print_function import tables import numpy as np # Describe a particle record class Partic...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='sample', version='0.1.0', description='Sample package for Python', long_description=readme, author='Mike Chirico...
from django.core.management.base import BaseCommand from tuning.models import Competition, Participation, Trial class Command(BaseCommand): args = "" help = "Initialize the database with competitions data" def _create_competitions_participations_trials(self): # Check if we need to initialize database or ...
############################################################################ # LeetCode Problem Number : 581 # Difficulty Level : Easy # URL : https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ ############################################################################ from typing import List class...
"""string splitting is allows you to break apart strings""" print("split:", "A Test String".split()) print("split t:", "A Test String".split("t")) print("rsplit:", "A Test String".rsplit()) print("partition t:", "A Test String".partition("t")) print("rpartition t:", "A Test String".rpartition("t")) print("splitlines n...
from typing import TYPE_CHECKING, Optional from PyQt5.QtWidgets import QLabel, QVBoxLayout, QGridLayout, QPushButton from electrum.i18n import _ from electrum.lnutil import ln_dummy_address from electrum.transaction import PartialTxOutput, PartialTransaction from .util import (WindowModalDialog, Buttons, OkButton, C...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest # Local script to test. from fibonacci import fib class FibonacciTest(unittest.TestCase): def test(self): self.assertEqual(0, fib(0)) self.assertEqual(1, fib(1)) self.assertEqual(1, fib(2)) self.assertEqual(2, fib(3))...
from django.shortcuts import render, redirect, HttpResponseRedirect from forms import SignUpForm, LoginForm, ResetPasswordForm, ChangePasswordForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.co...
import numpy as np from ztlearn.utils import plot_opt_viz from ztlearn.initializers import InitializeWeights as init from ztlearn.optimizers import OptimizationFunction as optimize class GbOptimization(object): def __init__(self, optimizer, init_method = 'ones'): self.optimizer = optimizer self...
import logging import functools import sqlalchemy from connexion import problem from dateutil.parser import isoparse as date_parse from rhub.lab import SHAREDCLUSTER_USER from rhub.lab import model from rhub.api import db, di, DEFAULT_PAGE_LIMIT from rhub.auth import ADMIN_ROLE from rhub.auth.utils import route_requi...
from datetime import datetime, timedelta import warnings import operator from textwrap import dedent import numpy as np from pandas._libs import (lib, index as libindex, tslib as libts, algos as libalgos, join as libjoin, Timedelta) from pandas._libs.lib import is_da...
from direct.interval.IntervalGlobal import * from direct.distributed.ClockDelta import * from direct.directnotify import DirectNotifyGlobal from direct.fsm import ClassicFSM from toontown.building import DistributedDoor from toontown.hood import ZoneUtil from toontown.building import FADoorCodes, DoorTypes from toontow...
import re from faker.providers.automotive.de_DE import Provider as DeDeAutomotiveProvider from faker.providers.automotive.es_ES import Provider as EsEsAutomotiveProvider from faker.providers.automotive.ru_RU import Provider as RuRuAutomotiveProvider class _SimpleAutomotiveTestMixin: """Use this test mixin for si...
import turtle, textwrap, document, time #defines bitmap patterns for letters A='2,0000000:0011100:0100010:0100010:0111110:0100010:0100010:0100010:0000000' B='2,0000000:0111100:0100010:0100010:0111100:0100010:0100010:0111100:0000000' C='2,0000000:0011100:0100010:0100000:0100000:0100000:0100010:0011100:0000000' D='2,000...
"""Part 2: Write a Python program to add two given lists using lambda. Hint : Map nums1 = [1, 4, 5, 6, 5] nums2 = [3, 5, 7, 2, 5] Expected Input Output Result: after adding two list [4, 9, 12, 8, 10] Update code in script_2/lambda_2.py""" nums1 = [1, 4, 5, 6, 5] nums2 = [3, 5, 7, 2, 5] result = map(lambda x, y: x + ...
from collections import namedtuple from union_find import DisjointSet # Putting weight as the first element means Edges will sort by weight first, # then source and target (lexicographically). Edge = namedtuple('Edge', ['weight', 'source', 'target']) def kruskal_mst(n, edges): """ Given a positive integer n (nu...
from .constants import * from .retimers import *
import string import numpy as np import pandas as pd from numpy import argmax from numpy import array import re import matplotlib.pyplot as plt import matplotlib.image as mpimg import seaborn as sns from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models...
# Crow Damage Skin success = sm.addDamageSkin(2435196) if success: sm.chat("The Crow Damage Skin has been added to your account's damage skin collection.")
# # Copyright 2016 Metamarkets Group 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...
# Copyright 2017 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class KbdishDetailInfo(object): def __init__(self): self._out_dish_id = None self._out_sku_id_list = None @property def out_dish_id(self): return self._out_dish_id ...
# 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 ...
''' Write a Python program to create a set. ''' num = [1, 2, 3, 4, 8] set1 = set(num) print(set1)
# # Base class for Ohm's law submodels # import pybamm from ..base_electrode import BaseElectrode class BaseModel(BaseElectrode): """A base class for electrode submodels that employ Ohm's law. Parameters ---------- param : parameter class The parameters to use for this submodel domain...
import json import pkgutil import textwrap from typing import Callable, Dict from jsonschema import validate from .plugin_registry import PluginRegistry from .mimebundle import spec_to_mimebundle # ============================================================================== # Renderer registry # =================...
# Copyright 2019 Nexenta Systems, 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 req...
# GENERATED BY KOMAND SDK - DO NOT EDIT from .decode.action import Decode
#!/usr/bin/env python # -*- coding: utf-8 -*- # Note: To use the 'upload' functionality of this file, you must: # $ pipenv install twine --dev import io import os import sys from pkg_resources import parse_requirements from shutil import rmtree from setuptools import find_packages, setup, Command here = os.path.a...
# -*- coding: utf-8 -*- """ Apache state .. versionadded:: 2014.7.0 Allows for inputting a yaml dictionary into a file for apache configuration files. The variable ``this`` is special and signifies what should be included with the above word between angle brackets (<>). .. code-block:: yaml /etc/httpd/conf.d/w...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/22 17:21 # @Author : Steve Wu # @Site : # @File : ec.py # @Software: PyCharm # @Github : https://github.com/stevehamwu import itertools import numpy as np from metrics.metrics import Metrics from utils.app.log import Logger from sklearn.metrics ...
""" SEMI-PASSIVE Plugin for Testing for Session Management Schema (OWASP-SM-001) https://www.owasp.org/index.php/Testing_for_Session_Management_Schema_%28OWASP-SM-001%29 """ from collections import defaultdict import json from owtf.dependency_management.dependency_resolver import ServiceLocator DESCRIPTION = "Normal...
""" =================== Latent Dynamics CRF =================== Solving a 2d grid problem by introducing latent variable interactions. The input data is the same as in plot_grid_crf, a cross pattern. But now, the center is not given an extra state. That makes the problem much harder to solve for a pairwise model. We c...
# -*- coding: utf-8 -*- """CCXT: CryptoCurrency eXchange Trading Library""" # MIT License # Copyright (c) 2017 Igor Kroitor # 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 restricti...
"""Working with built in CX Validation featrure.""" # Copyright 2022 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/licenses/LICENSE-2.0 # # Unless...
#!/usr/bin/python r""" Bot to upload pages from a text file. This bot takes its input from the UTF-8 text file that contains a number of pages to be put on the wiki. The pages should all have the same beginning and ending text (which may not overlap). The beginning and ending text is not uploaded with the page content...
import warnings from phi import math from ._geom import Geometry, NO_GEOMETRY from ._transform import rotate from ._box import bounding_box, Box from ..math._shape import merge_shapes class Union(Geometry): def __init__(self, geometries): self._geometries = tuple(geometries) assert len(self._geo...
"""[HTTP AGENT SERVER] """ # Copyright 2019 BlueCat Networks (USA) Inc. and its affiliates # # 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 # # ...
class config(): video_path = 0 img_path = 'data/dog.jpg' resize_img_size = 608 #确保是最大降采样32的倍数, 160, 320, 416, 512, 608等等 cfg_path = 'cfg/yolov3.cfg' weightfile = 'yolov3.weights' classes_names = 'data/coco.names' obj_confidence = 0.5 num_classes = 80 nms = True nms_confidence ...
import unittest import larcv from random import Random random = Random() # Testing import of Point.h objects: def test_import_Point_h(): pt = larcv.Point2D() pt = larcv.Point3D() def test_import_BBox_h(): bb = larcv.BBox2D() bb = larcv.BBox3D() # Testing import of Vertex.h objects: def test_impor...
print("Hello again Python!") x = 63 y = 18 soma = x + y print(soma)
import matplotlib matplotlib.use('Qt5Agg') from astropy.io import fits import matplotlib.pyplot as plt import numpy as np from copy import deepcopy from astropy.convolution import convolve, Box1DKernel import pdb import sys import os class Spec_Inspect(object): def __init__(self,two_d_spec): self.two_d_s...
#====================== BEGIN GPL LICENSE BLOCK ====================== # # 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 vers...
""" NOTE: This swerve drive system is far from ideal. There tidy few strange things that arise due to our hardware implementation of swervedrive. 3/4 through build season I started to notice this but by that point things just needed to work. I told my team many times that if I were to rewrite swerve drive it would look...
import os, sys sys.path.insert(1, '../') import torch import cv2 import shutil import torchvision import numpy as np import itertools import subprocess import random import matplotlib.pyplot as plt import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms import torch.nn.functional a...
""" Reads Classified Module. This chart shows the proportion of reads in each sample assigned to different groups. """ from app.display_modules.display_module import SampleToolDisplayModule from app.tool_results.reads_classified import ReadsClassifiedResultModule # Re-export modules from .models import ReadsClassifi...
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = ['Click>=6.0', ] setup_requirements =...
#!/usr/bin/env python3 # Copyright (c) 2015-2020 The Samcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Templates for constructing various sorts of invalid transactions. These templates (or an iterator ove...
import numpy as np from skimage.feature import blob_log from joblib import Parallel, delayed ############################### # Loop for parallelization # ############################### def task(image, i, n_patches_x, n_patches_y): ###LoG step blobs_log = blob_log(image, min_sigma=1.43, max_sigma=1.43, ...
import numpy as np from geometry import * import plot def in_circle(circle, p): x = p.x - circle.center.x y = p.y - circle.center.y if np.sqrt(x ** 2 + y ** 2) <= circle.r: return True else: return False def in_ellipse(ellipse, p): f1 = Point(np.sqrt(ellipse.a ** 2 - ellipse.b ** ...
import functools from unittest import mock import sys import numpy as np import scipy from pygsti.baseobjs.basis import Basis from pygsti.baseobjs.errorgenlabel import LocalElementaryErrorgenLabel as LEEL import pygsti.tools.basistools as bt import pygsti.tools.lindbladtools as lt import pygsti.tools.optools as ot fr...
""" ParallelCluster ParallelCluster API # noqa: E501 The version of the OpenAPI document: 3.0.0 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from pcluster_client.api_client import ApiClient, Endpoint as _Endpoint from pcluster_client.model_utils...
# -*- coding: utf-8 -*- """module for Timeline.""" import os from modules import manager from modules import interface from modules import logger from modules.windows_timeline import lv1_windows_timeline as wt class WindowsTimelineConnector(interface.ModuleConnector): NAME = 'windows_timeline_connector' DESC...
import os import pickle from PyQt5 import QtCore, QtWidgets from PyQt5.QtMultimedia import QSoundEffect from PyQt5.QtGui import QIcon, QFontDatabase from pathlib import Path from source_ui import main_window from type_test import highscores, settings, statistics, type_test # PATHS BASE_FOLDER = Path(__file__).parents...
# Copyright 2015-2015 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file ...
from django.contrib import admin from .models import Review @admin.register(Review) class TagAdmin(admin.ModelAdmin): # filter_horizontal = ('documents',) list_display = ('applicant_id', 'reviewer_first_name', 'reviewer_last_name', 'education', 'work', 'extracurriculars', 'skills_and_awards', 'comments') # T...
#-*- coding: utf-8 -*- '''! @file DFRobot_PAJ7620U2.h @brief Define the basic structure of the class DFRobot_PAJ7620 gesture sensor @n The PAC7620 integrates gesture recognition function with general I2C interface into a single chip forming an image analytic sensor @n system. It can recognize 9 human hand gesti...
# Copyright 2017 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 ...
# -*- coding: utf-8 -*- """Webex Teams Room data model. Copyright (c) 2016-2018 Cisco and/or its affiliates. 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...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2020-05-27 06:08 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('commercialoperator', '0055_auto_20200522_1612'), ] ...
class demo: @staticmethod def mymethod1(): print("Hello") myobj = demo() demo.mymethod1()
from copy import deepcopy from django.db import models from django.utils.datastructures import SortedDict from django.utils.encoding import StrAndUnicode from django.utils.safestring import mark_safe from .charts import Chart __all__ = ('BaseReport', 'Report') def pretty_name(name): """Converts 'f...
""" Database models """ from flask_sqlalchemy import SQLAlchemy # import database, capital for global scope DB = SQLAlchemy() class User(DB.Model): """Twitter users that we analyze""" id = DB.Column(DB.BigInteger, primary_key=True) name = DB.Column(DB.String(15), nullable=False) newest_tweet_id = DB....
import importlib import importlib.util import inspect import os import pkgutil from importlib._bootstrap import ModuleSpec from importlib._bootstrap_external import FileFinder from typing import Any, Callable, Generator, Iterable, List from ward.testing import Test, anonymous_tests from ward.models import Marker, Ward...
""" Validation of the modelDescription.xml """ def validate_fmu(filename): """ Validate the following aspects of an FMU modelDescription.xml: - validation against the XML schema - uniqueness and validity of variable names - completeness and integrity of the ModelStructure - required start val...
""" Funções - def em python (Parte 1) """ # def divisão(n1, n2): # if n2 == 0: # return # return n1 / n2 # divide = divisão(8, 0) # if divide: # print(divide) # else: # print('conta invalida')
import schedule import time def job01(): print('job01() working ....') # return def job02(param01, param02): print('job02() working ....',param01, param02) schedule.every(1).minutes.do(job01) schedule.every().day.at('14:30').do(job01) schedule.every(1).minutes.do(job02, 'p01', 'p02') while True: sche...
import pandas as pd def match_names(df): shuffled = df.sample(frac=1).reset_index(drop=True) shuffled['buy_for_index'] = shuffled.index + 1 shuffled['buy_for_index'].replace(len(df), 0, inplace=True) return ( shuffled[["email_address", "name"]].merge( shuffled[["buy_for_...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('cms', '0011_auto_20151121_1507'), ] operations = [ migrations.AlterField( model_name='pagedraft', na...
import numpy as np import redis import threading import copy import time others_grads = list() cnt_msgs_received = list() cur_iter = 0 class Clock_thread(threading.Thread): def __init__(self, msgQs, ping, num_workers, synch_max_diff): threading.Thread.__init__(self) self.msgQs = msgQs sel...
from unittest import TestCase from phi import math, field from phi.math import extrapolation from phi.physics import Domain, diffuse, PERIODIC, OPEN class TestDiffusion(TestCase): def test_constant_diffusion(self): DOMAIN = Domain(x=4, y=3, boundaries=PERIODIC) grid = DOMAIN.scalar_grid(1) ...
from collections import defaultdict import torch class ASAM: def __init__(self, optimizer, model, rho=0.5, eta=0.01): self.optimizer = optimizer self.model = model self.rho = rho self.eta = eta self.state = defaultdict(dict) @torch.no_grad() def _grad_norm(self): ...
import os import sys import boto3 from dateutil import parser from botocore.exceptions import ClientError def get_latest_ami(ec2_conn, ami_filter, nodetype): try: latest = None response = ec2_conn.describe_images(Filters=ami_filter) if len(response['Images']) != 0: print('[INFO] AMIs found:') ...
from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from hotel_app.models import * from hotel_app.serializers import RoomSerializer, StaffSerializer, GuestSerializer, CleaningSerializer class RoomAPIView(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] ser...
""" Given a directed graph, design an algorithm to find out whether there is a route between two nodes. """ class Node: def __init__(self, value): self.value = value self.children = [] self.visited = False class Graph: def __init__(self): self.nodes = [] def get_nodes(sel...
# -*- coding: utf-8 -*- #--------------------------------------------------------------------------- # Copyright 2020 VMware, Inc. All rights reserved. # AUTO GENERATED FILE -- DO NOT MODIFY! # # vAPI stub file for package com.vmware.nsx.node.services.ntp. #------------------------------------------------------------...
''' Builder for Skills HTML ''' # ----- Local Imports ----- import importlib common = importlib.import_module('src.python.common') # ----- Local Helpers ----- # Build HTML from JSON def build(fType, fName, j): t = "skills" html = f"<script>i.{t} = {str(len(j))};</script><p class='iconHeader'>"+t.capitalize()...
import torch import torch.utils.data import h5py from datetime import datetime from helper import * import PeptideBuilder import Bio.PDB from Bio.PDB.vectors import Vector import math AA_ID_DICT = {'A': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'K': 9, 'L': 10, 'M': 11, 'N': 12, 'P': 13,...