text
stringlengths
1
927k
from __future__ import print_function """ Wrapper for the C++ drizzle overlap code. History ------- Created by Jon Nielsen in 2012 Updated for the new cubing algorithm by Francesco D'Eugenio 16/02/2017 Notes ----- This module contains a testing function. At the moment it requires that the libraries path be hardcode...
#!/usr/bin/env python # coding: utf-8 import argparse import json from tqdm.auto import tqdm from transformers import AutoTokenizer def pre_processing(tokenizer, file_input, file_output): with open(file_input, "r") as f: data = json.load(f)["data"] new_data = {} for p in tqdm([p for d in data fo...
from scipy import sparse as spsp import unittest import networkx as nx import numpy as np import dgl import dgl.function as fn import backend as F from dgl.graph_index import from_scipy_sparse_matrix import unittest from utils import parametrize_dtype D = 5 # line graph related def test_line_graph(): N = 5 G...
# -*- coding: utf-8 -*- u"""pksetupunit2 setup script :copyright: Copyright (c) 2016 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ import pykern.pksetup pykern.pksetup.setup( name='pksetupunit2', author='RadiaSoft LLC', author_email='pip@radiasoft.net',...
""" Base classes for all estimators. Used for VotingClassifier """ # Author: Gael Varoquaux <gael.varoquaux@normalesup.org> # License: BSD 3 clause import copy import warnings from collections import defaultdict import platform import inspect import re import numpy as np from . import __version__ from ._config imp...
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('requirements.txt') as req_file: requirements = req_file.read().split('\n') with open('...
"""Interact with Taskwarrior.""" import datetime import os import re import threading import traceback from pathlib import Path from shutil import which from subprocess import PIPE, Popen from typing import List, Optional, Tuple, Union import albert as v0 # type: ignore import dateutil import gi import taskw from fu...
#!/usr/bin/env python3 """ Read a lists of IP addresses from file and performs a HEAD request. Outputs HTTP response code, IP address and HTTP headers. """ import asyncio import time import aiohttp from pathlib import Path import sys async def get_header(session, ip): async with session.head(f"http://{ip}/", all...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 IBM Corp. # # 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 # # ...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
def alphabet_subsequence(s): return ''.join(sorted(s)) == s and len(set(s)) == len(s) def alphabet_subsequence_two(s): """ I like this solution better. Clear and concise """ return all(s[i]<s[i+1] for i in range(len(s) -1)) if __name__ == '__main__': s = 'effg' print(alphabet_subsequence...
#!usr/bin/env python3 ## /\ compatability line ## distribution notes - Calm Segment Extractor py34 v4.py """ Calm Segment Extractor by Chris Ward (C) 2015 updated for python 3.4 compatability by Chris Ward (C) 2016 provided free for non-commercial/fair use. This program attempts to define periods of calm behavior by ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 3rd party imports import numpy as np import xarray as xr __author__ = "Louis Richard" __email__ = "louisr@irfu.se" __copyright__ = "Copyright 2020-2021" __license__ = "MIT" __version__ = "2.3.7" __status__ = "Prototype" def _idx_closest(lst0, lst1): return [(np.ab...
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Pad(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "treemap.marker" _path_str = "treemap.marker.pad" _valid_props = {"b", "l", "r", "t"} # b ...
"""Currency exchange rate support that comes from fixer.io.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_NAME import homeassistant.helpers.config_validation as ...
#!/usr/bin/env python import os import hashlib from flask import Flask, request, make_response, abort from flask.ext.sqlalchemy import SQLAlchemy from flask import jsonify from sqlalchemy import desc, asc, Table, insert # Author: Christian Charukiewicz # Email: c.charukiewicz@gmail.com app = Flask(__name__) db = SQLA...
# CSV2PO Python (csv2po.py) v1.0.0 # By Tom CHEN <tomchen.org@gmail.com> (tomchen.org) # MIT License # Python 3.8+ import re import glob import os import time import random import importlib.util import gettext import polib from pathlib import Path from pluralforms import pluralforms import settings __version__ = '1....
# # -*- coding: utf-8 -*- # Copyright 2021 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import absolute_import, division, print_function __metaclass__ = type """ The nxos_bgp_global config file. It is in this file where the current configura...
#flask app from flask import Flask, render_template #instantiate the flask app app = Flask(__name__) #create index page function @app.route("/") def index(): return render_template("index.html") #run the app if __name__ == "__main__": app.run(debug=True)
# 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 ...
# Copyright (c) 2014, Guillermo López-Anglada. Please see the AUTHORS file for details. # All rights reserved. Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file.) import sublime class ContextProviderMixin(object): '''Provides a method to evaluate contexts. Us...
# -*- coding: utf-8 -*- from inspect import isgenerator from django.apps import apps from .testcase import DatatableViewTestCase from datatableview.exceptions import ColumnError from datatableview.datatables import Datatable, ValuesDatatable from datatableview.views import DatatableJSONResponseMixin, DatatableView fr...
"""Button for Shelly.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import Final, cast from homeassistant.components.button import ( ButtonDeviceClass, ButtonEntity, ButtonEntityDescription, ) from homeassistant.config_entries impo...
""" Scatter Plot with Tooltips -------------------------- A scatter plot of the cars dataset, with tooltips showing selected column values when you hover over points. We make the points larger so that it is easier to hover over them. """ # category: simple charts import altair as alt from vega_datasets import data so...
#!/usr/bin/python3 # Author: Dr. Christopher C. Hall, aka DrPlantabyte # Copyright 2021 Christopher C. Hall # Permission granted to use and redistribute this code in accordance with the Creative Commons (CC BY 4.0) License: # https://creativecommons.org/licenses/by/4.0/ from subprocess import call, Popen, PIPE, STDOUT ...
def main(): n = int(input("Enter no. of rows: ")) for i in range(n): for j in range(i+1): print(str((i + j + 1) % 2) + " ", end='') print() if __name__ == '__main__': main()
import pickle import nltk import measurements as msr import csv def main(): """ Collect and present data on the names of North American birds (US + Canada) :return: """ # Load list of NamedBirds birds_pickle = open('built_birds.pickle', 'rb') birds = pickle.load(birds_pickle) # Divide...
#!/usr/bin/python # coding: utf-8 -*- # # FIXME: required to pass ansible-test # GNU General Public License v3.0+ # # Copyright 2019 Arista Networks AS-EMEA # # 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 t...
from abc import abstractmethod from matplotlib import pyplot as plt from matplotlib.backends.backend_qt5 import NavigationToolbar2QT from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from qtpy import QtWidgets from solarviewer.config.base import Viewer, DataModel from solarviewer.ui.plo...
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
# TODO: specify what specifically to import from .block import * from .bloomfilter import * from .ecc import * from .hd import * from .helper import * from .merkleblock import * from .mnemonic import * from .network import * from .op import * from .pbkdf2 import * from .psbt import * from .script import * from .tx impo...
""" WSGI config for feedback project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION``...
# terminal # > python --version # > python # >>> 1 + 2 # >>> 1 - 2 # >>> 4 * 5 # >>> 7 / 5 # >>> 3 ** 2 # >>> type(10) # >>> type(2.718) # >>> type("hello") # >>> x = 10 # >>> print(x) # >>> x = 100 # >>> print(x) # >>> y = 3.14 # >>> x * y # >>> type(x * y) # >>> a = [1, 2, 3, 4, 5] # >>> print(a) # >>> len(a) # >>> a...
#!/usr/bin/env python # # Copyright 2019 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 os import sys import difflib from util import build_utils def _SkipOmitted(line): """ Skip lines that are to be intenti...
""" fastgame.widget.label Fastgame文本组件。 """ from typing import Tuple import pygame import fastgame from fastgame.exceptions import * from fastgame.utils.color import * __all__ = ['Label'] class Label(pygame.sprite.Sprite): def __init__(self, text: str, font: str = None, size: int = 16, use_sys_font: bool = F...
__all__ = ["tiff_handling","binary"]
# 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 ...
sec = eval(input("input secs")) print(sec, "seconds", sec//60, "min", sec%60, "sec")
# __init__.py # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php # flake8: noqa # @PydevCodeAnalysisIgnore from git.exc import * # @NoMove @IgnorePep8 import inspec...
# -*- 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...
value = [len(x) for x in open('ep001_version.py')] print(value) """ [11, 24, 19, 1, 4, 76, 77, 4] """ it = (len(x) for x in open('ep001_version.py')) print(it) print(next(it)) print(next(it)) """ <generator object <genexpr> at 0x0000023D58EAAA40> 11 24 """ roots = ((x, x ** 0.5) for x in it) print(next(roots)) """ (1...
from sqlalchemy import Column, DateTime, Integer, String, TEXT, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.sql import func from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class BaseModel(Base): __abstract__ = True creation_date = Column(DateTime(timez...
# The MIT License (MIT) # ===================== # # Copyright © 2020 Azavea # # 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 base64 import json from fireo.fields import NestedModel from fireo.fields.errors import FieldNotFound from fireo.queries import query_set as queries class ManagerError(Exception): pass class ManagerDescriptor: """Restrict user to get `Manager` from model instance and from abstract model""" def _...
#!/usr/bin/env python """ Setup script for citeproc-py """ import os import re import sys from datetime import datetime from subprocess import Popen, PIPE from setuptools import setup, find_packages from setuptools.command.build_py import build_py from setuptools.command.develop import develop PACKAGE = 'citeproc'...
from __future__ import print_function, division from sympy.core.basic import C from sympy.core.singleton import S from sympy.core.function import Function from sympy.core import Add from sympy.core.evalf import get_integer_part, PrecisionExhausted from sympy.core.relational import Gt, Lt, Ge, Le, Eq #################...
from functools import partial import pytest from ..vm.vm_test_helpers import run_test run_arithmetic_vm_test = partial( run_test, "tests/fixtures/LegacyTests/Constantinople/VMTests/vmArithmeticTest", ) @pytest.mark.parametrize( "test_file", [ "add0.json", "add1.json", "add2....
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Bin Xiao (Bin.Xiao@microsoft.com) # ------------------------------------------------------------------------------ from __future__ import absolute_import from __futu...
""" test_path.py - Test the path module. This only runs on Posix and NT right now. I would like to have more tests. You can help! Just add appropriate pathnames for your platform (os.name) in each place where the p() function is called. Then send me the result. If you can't get the test to run at all on your platf...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import pickle import unittest import warnings from functools import partial from io import StringIO f...
from pathlib import Path import os, sys, shutil import subprocess import pandas as pd import string if len(sys.argv) != 2: print("Usage: ./extract_gps.py <video dir>") sys.exit() def convert_latlong(in_str): split_latlong = in_str.split(' ') return float(split_latlong[0]) + float(split_latlong[2][:-1]...
# Generated by Django 2.1.15 on 2020-09-04 07:14 import core.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0004_recipe'), ] operations = [ migrations.AddField( model_name='recipe', name='image', ...
from typing import Optional, Union, Tuple, List, Dict import functools from torch import nn from torch import optim from torch.nn import functional as F from transformers.trainer_pt_utils import get_parameter_names import torchmetrics from .lr_scheduler import ( get_cosine_schedule_with_warmup, get_polynomial_d...
import os.path from typing import Union, Optional import torch _TEST_DIR_PATH = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) def get_asset_path(*paths): """Return full path of a test asset""" return os.path.join(_TEST_DIR_PATH, "assets", *paths) def convert_tensor_encoding( tensor:...
# Global Imports import json from collections import defaultdict # Metaparser from genie.metaparser import MetaParser # ============================================= # Collection for '/mgmt/tm/ltm/profile/server-ssl' resources # ============================================= class LtmProfileServersslSchema(MetaParse...
# Copyright 2019 The Meson development team # 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 ...
""" Reads queries from test collections @author: Faegheh Hasibi (faegheh.hasibi@idi.ntnu.no) """ import csv from nordlys.tagme import config def read_yerd_queries(y_erd_file=config.Y_ERD): """ Reads queries from Erd query file. :return dictionary {query_id : query_content} """ queries = {} ...
from fastapi import FastAPI, Form from fastapi.responses import HTMLResponse from pydantic import BaseModel from typing import Optional app = FastAPI() class UssdParams(BaseModel): session_id: str service_code: str phone_number: str text: str # dummy acc. data accounts = { "A001": { "bi...
import os os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '../gcs/mesolitica-storage.json' os.environ['CUDA_VISIBLE_DEVICES'] = '1' import tensorflow as tf import malaya_speech.train as train import malaya_speech.train.model.vggvox_v2 as vggvox_v2 import malaya_speech from glob import glob import librosa import numpy ...
#!/usr/bin/python # Classification (U) """Program: config_override.py Description: Unit testing of config_override in pulled_search.py. Usage: test/unit/pulled_search/config_override.py Arguments: """ # Libraries and Global Variables # Standard import sys import os if sys.version_info < (2...
""" Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Note:There are six instances where subtraction is used: I can be pla...
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('a.jpg',0) img2 = img.copy() template = cv2.imread('b.jpg',0) w, h = template.shape[::-1] # All the 6 methods for comparison in a list methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORME...
import click from app import app, db from app.backend.models.user import User from app.backend.models.cms import CMS from app.backend import user_manager from sqlalchemy.exc import SQLAlchemyError from redis.exceptions import RedisError @app.cli.command() def seed(): """ Add initial users to the db. """ ...
import json import requests from .objects import Product from ..base import ShopifyApiWrapper, ShopifyApiError, datetime_to_string class ProductsApiWrapper(ShopifyApiWrapper): valid_published_status_values = [ 'published', 'unpublished', 'any' ] max_results_limit = 250 def...
from datetime import datetime, timedelta import json import re import math from dateutil import relativedelta from django.core.cache import cache from django.conf import settings from django.contrib.auth.models import User from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ObjectD...
from web.msnotifier.example import add def test_add_correct(): assert add(5, 7) == 12 def test_add_incorrect(): assert add(15, 8) != 21
import torch from model import * from dataloader import * from utils.pyart import * import argparse import numpy as np from pathlib import Path def main(args): print("Processing...") # set device: if torch.cuda.is_available(): device = torch.device('cuda:0') else: device = torch.device...
from fh_webhook import create_app app = create_app() if __name__ == "__main__": app.run()
class Prm: @classmethod def get_prefix_kwargs(cls, kwargs: dict, prefix: str, default_param: dict, new_prefix=''): """ Remove param from kwargs and return the extracted result. Eg. column_kwargs = Prm.get_prefix_kwargs(kwargs, 'col_', {'size': 10}) This will remove all the "c...
import unittest import os from SecretManagerEnvInjector import inject class InjectTest(unittest.TestCase): @inject('arn:aws:secretsmanager:us-east-1:xxxxxxxxxxxxxx:secret:bogus-dj3g0R') def test_inject(self): self.assertEquals(os.getenv('bogus-dj3g0R'), 'test2')
import asyncio from pathlib import Path from typing import Text import pytest import rasa.shared.utils.io from rasa.core.domain import Domain from rasa.core.events import UserUttered, ActionExecuted from rasa.core.training.structures import StoryStep, StoryGraph from rasa.importers.importer import E2EImporter, Traini...
# Copyright 2013 - Mirantis, Inc. # Copyright 2015 - StackStorm, 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 # # Unl...
import logging from . import wrapper from ..app_settings import settings logger = logging.getLogger(__name__) class Mime(wrapper.Wrapper): def __init__(self, filepath): super().__init__(exec_name=settings.BINARY_FILE) self.filepath = filepath def get_cmd(self): cmd = super().get_cmd...
# -*- coding: utf-8 -*- """Test NbConvertApp""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import os import io import nbformat from .base import TestsBase from ..postprocessors import PostProcessorBase from ..tests.utils import onlyif_cmds_exist from nbconver...
import json from unittest import mock import pytest from django.urls import reverse from django.utils import timezone from django.utils.formats import localize from saleor.dashboard.menu.forms import AssignMenuForm from saleor.dashboard.menu.utils import ( get_menu_as_json, get_menu_item_as_dict, get_menu...
# Copyright (c) 2015 Rackspace # # 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 a...
import sys from pathlib import Path from setuptools import setup, find_packages if __name__ == '__main__': base_dir = Path(__file__).parent src_dir = base_dir/'src'/'regmod' sys.path.insert(0, src_dir.as_posix()) import __about__ as about with (base_dir/'README.rst').open() as f: long_de...
from rest_framework import serializers from books.serializers import UserSerializer, BookSerializer, LibrarySerializer from waitlist.models import WaitlistItem class WaitlistItemSerializer(serializers.ModelSerializer): user = UserSerializer() library = LibrarySerializer() book = BookSerializer() adde...
from os import environ, path from dotenv import load_dotenv basedir = path.abspath(path.dirname(__file__)) load_dotenv(path.join(basedir, ".env")) class Config(object): # You have to config your apikey for bioportal in a separate .env file that must not be in git # e.g. BIOPORTAL_APIKEY='xxxxxx-xxxxx-xxxx-x...
_base_ = '../faster_rcnn/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco.py' model = dict( roi_head=dict(bbox_head=dict(num_classes=2)) ) # Dataset path DDSM_TRAIN_DATASET = '/home/hqvo2/Projects/Breast_Cancer/data/processed_data/mass/train' DDSM_TRAIN_ANNOTATION = DDSM_TRAIN_DATASET + '/annotation_coco_with_classes_ex...
from mock import call from nose.tools import istest from provy.more.debian import AptitudeRole, RedisRole from tests.unit.tools.helpers import ProvyTestCase class RedisRoleTest(ProvyTestCase): def setUp(self): super(RedisRoleTest, self).setUp() self.role = RedisRole(prov=None, context={}) @i...
# Copyright 2012 OpenStack 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 l...
from twisted.internet import defer, task from twisted.python.failure import Failure from exchanges.base import ExchangeService from exchange import calcVirtualOrderBooks import copy import time def defaultErrHandler(failure): print(failure.getBriefTraceback()) return failure def handleMultipleErr(data): ...
""" Test base objects with context """ from pii_manager import PiiEnum, PiiEntity from pii_manager.api import PiiManager def _pii(pos): return PiiEntity(PiiEnum.GOV_ID, pos, "3451-K", country="vo", name="vogonian ID") TEST = [ ("my Vogon ID is 3451-K", [_pii(15)]), ("the number 3451-K is my Vogonian ID...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=47 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for...
import pkg_resources pkg_resources.require( "SQLAlchemy >= 0.4" ) from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.interfaces import * import logging log = logging.getLogger( __name__ ) dialect_to_egg = { "sqlite": "pysqlite>=2", "postgres": "psycopg2", "postgresql": "psycopg2", ...
from getgauge.python import (before_step, step, after_step, before_scenario, after_scenario, before_spec, after_spec, before_suite, after_suite, custom_screen_grabber, continue_on_failure) @step("Step 1") def step1(): pass @c...
# -*- coding: utf-8 -*- """ @author : Wang Meng @github : https://github.com/tianpangji @software : PyCharm @file : permissions.py @create : 2020/7/22 21:44 """ from rest_framework import serializers from drf_admin.common.models import get_child_ids from drf_admin.utils.views import TreeSerializer from sys...
# coding=utf-8 # Copyright 2019 The Tensor2Tensor 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 applicable...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import unicode_literals import unittest from pymatgen import Composition from pymatgen.analysis.reaction_calculator import Reaction, BalancedReaction, \ ReactionError, ComputedReaction fro...
from gui_version import App from tests.gui.app_testing_bed import FracDimTestingBed from tests.gui.common import check_report def test_fracdim_wo_windows(qtbot): window = App() qtbot.addWidget(window) test_app = FracDimTestingBed(qtbot=qtbot, window=window) qtbot.waitForWindowShown(window) tes...
from __future__ import absolute_import, division, print_function def profile2d(p, vmin=None, vmax=None): from dials.array_family import flex import string if vmin is None: vmin = flex.min(p) if vmax is None: vmax = flex.max(p) assert vmax >= vmin dv = vmax - vmin if dv == ...
from flask import Flask, g app = Flask(__name__) # arg = 'i' @app.before_request def sd(): arg = 123 bf(arg) def bf(arg): # global arg g.x = arg return arg @app.route("/index", methods=["POST", "GET"]) def index(): g.x = 123 return "index" @app.route("/test", methods=["POST", "GET"]...
from torch.nn.parallel import DistributedDataParallel as DDP import torch.distributed as dist from .fedml_trainer import FedMLTrainer from .process_group_manager import ProcessGroupManager from torch.nn.parallel import DistributedDataParallel as DDP from .trainer.my_model_trainer_classification import MyModelTrainer a...
# -*- coding: utf-8 -*- """ jishaku.help_command ~~~~~~~~~~~~~~~~~~~~ HelpCommand subclasses with jishaku features :copyright: (c) 2021 Devon (Gorialis) R :license: MIT, see LICENSE for more details. """ from hashcord.ext import commands from jishaku.paginators import PaginatorEmbedInterface, PaginatorInterface ...
import os class Config(object): def __init__(self, name=None, path=None): self.name = name self.path = os.path.abspath(path)
# 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 u...
import hashlib from typing import Dict, Iterable, List, NamedTuple, Sequence, Tuple, Union import numpy as np import qiskit import sympy from .. import _builtin_gates, _circuit, _gates from ..symbolic.qiskit_expressions import QISKIT_DIALECT, expression_from_qiskit from ..symbolic.sympy_expressions import SYMPY_DIALE...
# -*- coding: utf-8 -*- """ Created on Sun Apr 28 00:33:10 2019 @author: Aalap """ # -*- coding: utf-8 -* """ Created on Thu Mar 28 18:47:25 2019 @author: Aalap """ import numpy as np import matplotlib.pyplot as plt import math class Node: def __init__(self, nodex, nodey,nodetheta, cost, parentnode,vx,vy,vt):...
""" Modified from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py """ import oneflow as flow import oneflow.nn as nn import oneflow.nn.functional as F def drop_path(x, drop_prob: float = 0.5, training: bool = False): """Drop paths (Stochastic Depth) per sample (when appli...