text
stringlengths
2
999k
import torch from cape import CAPE2d def test_cape2d(): pos_emb = CAPE2d(d_model=512, max_global_shift=0.0, max_local_shift=0.0, max_global_scaling=1.0, batch_first=False) print("Checking correct dimensionality input/output (16x16) for batch_size = False...") exp_shape = (16, 16, 32, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright Blaze 2021. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) """ from flask import Blueprint, jsonify from syn.utils.charts.bridge im...
#! /usr/bin/env python3 from gpiozero import Button from time import sleep from hashlib import sha256 from picamera import PiCamera import requests # get the board serial number def getserial(): # Extract serial from cpuinfo file cpuserial = "0000000000000000" try: f = open('/proc/cpuinfo','r') ...
# coding=utf-8 # *** WARNING: this file was generated by 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 __all__ ...
import logging from typing import Callable from petisco.logger.logger import ( Logger, INFO, ERROR, WARN, WARNING, DEBUG, CRITICAL, FATAL, ) class LoggingBasedLogger(Logger): def __init__( self, logger_name: str, logging_level=logging.INFO, format: ...
# THIS FILE IS AUTO-GENERATED. DO NOT EDIT from verta._swagger.base_type import BaseType class ModeldbAddProjectTagsResponse(BaseType): def __init__(self, project=None): required = { "project": False, } self.project = project for k, v in required.items(): if self[k] is None and v: ...
# -*- coding: utf-8 -*- ''' Manage Chocolatey package installs .. versionadded:: 2016.3.0 ''' # Import Python libs from __future__ import absolute_import # Import Salt libs import salt.utils from salt.exceptions import SaltInvocationError def __virtual__(): ''' Load only if chocolatey is loaded ''' ...
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework import filters from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_sett...
from typing import List class Solution: def countBits(self, num: int) -> List[int]: res = [0] * (num + 1) previous = 0 for x in range(num + 1): if x == 0: res[x] = 0 elif x == 1: res[x] = 1 else: if x & (x ...
# Given the head of a Singly LinkedList, write a function to determine if the LinkedList has a cycle in it or not. # O(N) space:O(1) class Node: def __init__(self, value, next = None) -> None: self.value = value self.next = None def linkedlist_cycle(head): slow, fast = head, head whil...
import random with javascript: import THREE console.log(THREE) Meshes = [] def setup_threejs(): width = 640; height = 320 ren = new THREE.WebGLRenderer( { antialias: true, canvas:document.getElementById('canvas') } ) ren.setPixelRatio( window.devicePixelRatio ) ren.setSize( width, height ) scn = new THRE...
# # This file is part of m.css. # # Copyright © 2017, 2018, 2019 Vladimír Vondruš <mosra@centrum.cz> # # 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...
from typing import Any, Dict, List, Optional, Sequence, Type, Union from graphql import ( ExecutionContext as GraphQLExecutionContext, GraphQLSchema, get_introspection_query, parse, validate_schema, ) from graphql.subscription import subscribe from graphql.type.directives import specified_directive...
import argparse # import functools from pprint import pprint from datetime import datetime, timedelta, timezone from dateutil.parser import parse from google.oauth2.credentials import Credentials from googleapiclient.discovery import build from googleapiclient.errors import HttpError class YoutubeBroadcasts(object):...
# coding=utf-8 # Copyright 2020 HuggingFace Datasets 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 applica...
import os import copy import logging import time import numpy as np import carla import math import weakref import shapely.geometry from enum import Enum from easydict import EasyDict from collections import deque from typing import Any, Dict, List, Optional, Tuple, Union from haco.DIDrive_core.simulators.carla_data_p...
from django.urls import reverse_lazy from django.utils.text import format_lazy DEBUG = True ROOT_URLCONF = 'testshop.urls' SECRET_KEY = 'test' SITE_ID = 1 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } STATIC_URL = '/static/' MEDIA_URL = '/media...
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class ReviewsItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() product_rating = scrapy.Field() review_title = scrapy.Fiel...
# coding=utf-8 import os from datetime import datetime from tzlocal import get_localzone from edoc_assinatura.certificado import Certificado from edoc_assinatura.assinatura import Assinatura certificado_nfe_caminho = os.environ['certificado_nfe_caminho'] certificado_nfe_senha = os.environ['certificado_nfe_senha'] c...
from collections import OrderedDict from typing import Collection, List, Mapping, MutableSequence, Optional, Tuple, Union import numpy as np from slicedimage import TileSet from starfish.imagestack.parser import TileCollectionData, TileData, TileKey from starfish.imagestack.physical_coordinate_calculator import recal...
import os import sys import glob import numpy as np import torch import utils import logging import argparse import torch.nn as nn import genotypes import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn from torch.autograd import Variable from model import NetworkCIFAR as Network ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import onnxruntime import onnx import json import numpy as np from onnx import helper, numpy_helper import os import tensorflow as tf from pathlib import Path import torch def caffeRunner(model_path, inputs_path): # TODO: Install pycafe ...
# (c) 2017, Patrick Deelman <patrick@patrickdeelman.nl> # (c) 2017 Ansible Project # 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 DOCUMENTATION = ''' name: passwordstore author...
""" DEMO 6 ------ Calculate flow coefficient and resistance coefficient of draw-off point from known flow rate and pressure drop. """ import quantities as qty from pypeflow.core.flow_coefficient import FlowCoefficient from pypeflow.core.resistance_coefficient import ResistanceCoefficient from pypeflow.core.pipe_schedul...
from aws_cdk import core import aws_cdk.aws_ec2 as ec2 class VpcConstruct(core.Construct): def __init__(self, scope: core.Construct, id: str, cidr_range: str, region: str, mazAz: int, tgw: str, has_endpoints: bool, **kwargs) -> None: super().__init__(scope, id)
#!/usr/bin/env python # Python 2/3 compatibility from __future__ import print_function import sys PY3 = sys.version_info[0] == 3 if PY3: xrange = range import numpy as np from numpy import random import cv2 def make_gaussians(cluster_n, img_size): points = [] ref_distrs = [] for i in xrange(cluster_...
import logging import time from functools import wraps from typing import Final def timing(f): """Decorator for timing functions Usage: @timing def function(a): pass """ @wraps(f) def wrapper(*args, **kwargs): start: Final = time.time() result: Final = f(*args, **k...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Excel PublicComp表单解析器基类, 由公共数据类型定义文件生成复合结构类型 ExcelPublicCompParser Sheet struct: (复合结构数据类型名称 ns 数据类型描述 数据项名称 ns1 数据项中文名称 数据项数据类型 粒度 单位 默认值 最小值 最大值 数据项描述) """ import excelsheetparser class ExcelPublicCompParser(excelsheetparser.ExcelSheet...
from pathlib import Path from setuptools import setup, find_packages # Based on PyPA's sampleproject located at https://github.com/pypa/sampleproject PROJECT_NAME = 'yav' here = Path(__file__).parent readme_path = here / 'README.md' version_path = here / PROJECT_NAME / 'VERSION' with readme_path.open(encoding=...
#!/usr/bin/python # # Copyright 2020 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 ag...
import time from iqoptionapi.stable_api import IQ_Option import time def compare(prev, curr): if curr>prev: return "high" elif curr < prev: return "low" else: return 0 print("username: ") username = input() print("password: ") password = input() history = [] o...
import sys from networkcomponents import * from db_meta import * from multiple_pointer_custom import * from valueunit_gen_network import * def check_nan( t, msg, vals = None, s = 3, rev = False ): if vals == None: vals = [ t ] v = tf.reduce_sum( t ) if rev: t = t...
import _plotly_utils.basevalidators class TextValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="text", parent_name="image.legendgrouptitle", **kwargs ): super(TextValidator, self).__init__( plotly_name=plotly_name, parent_name=par...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Donny You(youansheng@gmail.com) import numpy as np import torch from utils.helpers.det_helper import DetHelper from models.det.layers.fr_priorbox_layer import FRPriorBoxLayer class RPNTargetAssigner(object): """Compute prior boxes coordinates in center-off...
from screeps_loan import app from flask import render_template, redirect, request, session, url_for, escape, flash from werkzeug.utils import secure_filename import os import hashlib import screeps_loan.models.alliances as alliances_model import screeps_loan.models.invites as invites import screeps_loan.models.users as...
from .SubprocessKernel import *
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from Box2D import b2Color class testColor (unittest.TestCase): def checkAlmostEqual(self, v1, v2, msg, places=3): for i, (a, b) in enumerate(zip(v1, v2)): self.assertAlmostEqual(a, b, places=places, msg="(index %...
from .common import InfoExtractor from ..utils import int_or_none class NFBIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?nfb\.ca/film/(?P<id>[^/?#&]+)' _TESTS = [{ 'url': 'https://www.nfb.ca/film/trafficopter/', 'info_dict': { 'id': 'trafficopter', 'ext': 'mp4', ...
import logging import importlib.util from .dicts import merge_dict_list, merge_dicts logger = logging.getLogger(__name__) def load_configs(config_paths): configs = [load_config_dict_py(path) for path in config_paths] return merge_dict_list(configs) def load_config_dict_py(config_path): def _read_pyfile...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.async.base.exchange import Exchange import hashlib from ccxt.base.errors import ExchangeError class mercado (Exchange): de...
import logging from argparse import ArgumentParser from pathlib import Path import psutil from pid_file_checker.exceptions import InvalidPidError logger = logging.getLogger(__name__) def main(): parser = ArgumentParser( description="Check for the presence of a pid file. " "The file must contain...
# -*- coding: utf-8 -*- # Copyright (c) 2016-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2016 Derek Gustafson <degustaf@gmail.com> # Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com> # Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com> # Copyright (c) 2019 Ashley Whetter <ashley@awhett...
# Copyright (c) 2012 Spotify AB # # 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...
# -*- coding: utf-8 -*- import os import subprocess from unittest import TestCase import time from mock import MagicMock from openprocurement.bot.identification.databridge.caching import Db, db_key from openprocurement.bot.identification.databridge.process_tracker import ProcessTracker from openprocurement.bot.identi...
import sys import subprocess class Runner(object): def __init__(self, executable, size, iterations): self.executable = executable self.size = size self.iterations = iterations def run(self): args = self.__prepare_arguments() proc = subprocess.Popen(args, stdout=subproc...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.zone_hvac_controls_and_thermostats import ZoneControlThermostatStagedDualSetpoint log = logging.getLogger(__name__) class TestZoneControlThermostatStagedDualSetpoint(unittest.Te...
from dataset import * from registry import * from pygame import * from utils import * import image import sys import os import re # import grammar_v5 as grammar # import text_encode as encode # encode.globals_init() class SceneIterator: def __init__(self, n, gen, seed): gen.set_seed(seed) self.g...
# Copyright (c) 2016 Intel Corporation. # # 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 la...
import math import numpy as np import os from .utils.mygym import convert_to_gym import gym import opensim import random import akro ## OpenSim interface # The amin purpose of this class is to provide wrap all # the necessery elements of OpenSim in one place # The actual RL environment then only needs to: # - open a ...
from contextlib import closing from smart_open import smart_open from airflow.hooks.S3_hook import S3Hook from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator class PostgresToS3Operator(BaseOperator): template_fields = ('sql', 's3_key') template_ext = ('.sql',) d...
import nessrest from nessrest import ness6rest import threading import Queue from threading import Semaphore import time from output import * #Dependencies: #git clone https://github.com/golismero/openvas_lib.git #python setup.by build #python setup.py install #or: #pip install openvas_lib class AutoNessus(): def ...
import numpy as np import tensorflow as tf from PIL import Image from keras import backend as K def load_data(path='./mnist.npz'): f = np.load(path) x_train = f['x_train'] f.close() return (x_train) x_train = load_data() index=15 #选择第n个数据 im = Image.fromarray(x_train[index]) im.show() img_rows, im...
# Natural Language Toolkit: CCG Categories # # Copyright (C) 2001-2017 NLTK Project # Author: Graeme Gange <ggange@csse.unimelb.edu.au> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT from __future__ import unicode_literals from functools import total_ordering from abc import ABCMeta, abstractmeth...
import _plotly_utils.basevalidators class FamilysrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="familysrc", parent_name="pie.outsidetextfont", **kwargs ): super(FamilysrcValidator, self).__init__( plotly_name=plotly_name, parent...
from enum import Enum, unique from typing import cast from mypy.plugin import FunctionContext, MethodContext, MethodSigContext from mypy.typeops import erase_to_bound from mypy.types import AnyType, CallableType, Instance, TupleType from mypy.types import Type as MypyType from mypy.types import TypeOfAny, TypeVarType,...
import logging logger = logging.getLogger(__name__) import numpy as np import os.path from shutil import rmtree from subprocess import call from time import time import pwkit.environments.casa.tasks as tasklib import pwkit.environments.casa.util as casautil import sdmpy import rtpipe.parseparams as pp from rtlib_cython...
#!/usr/bin/env python # Copyright 2011 Google Inc. All Rights Reserved. """Tests for grr.parsers.chrome_history.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import datetime import io import os from absl import app from future.builtins import str ...
import numpy as np import pandas as pd from scipy.spatial import distance import scipy from tqdm import tqdm import math data_filename = "example/data/zoo.txt".replace('\\', '/') class GSOM: def __init__(self, spred_factor, dimensions, distance='euclidean', initialize='random', learning_rate=0.3, ...
#%% import argparse import os import time import json import autolab_core.utils as utils from autolab_core import YamlConfig, Logger from gqcnn import get_gqcnn_model, get_gqcnn_trainer, utils as gqcnn_utils #%% logger = Logger.get_logger('tools/train.py') dataset_dir = '/home/ai/git/gqcnn/data/training/Dexnet-2.0_te...
# @desc This is a description of **simple_choice2** def simple_choice2(sunny, raining): if (sunny or raining): return sunny return not raining def main(): print(simple_choice2(True, True)) print(simple_choice2(True, False)) print(simple_choice2(False, True)) print(simple_choice2(False...
""" Created on 17 Apr 2017 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ import optparse # -------------------------------------------------------------------------------------------------------------------- class CmdControlReceiver(object): """unix command line handler""" def __init__(se...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mycars.settings') try: from django.core.management import execute_from_command_line except Impor...
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: # Maintained By: DEBUG = True TESTING = True HOST = '0.0.0.0' SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/ggrc-dev-test.db' #SQLALCHEMY_ECHO = True
from __future__ import unicode_literals import torchtext.data as data from ..common.torchtext_test_case import TorchtextTestCase class TestDataset(TorchtextTestCase): def test_batch_with_missing_field(self): # smoke test to see if batches with missing attributes are shown properly with open(self....
from tkinter import Frame, Scrollbar, Canvas, Widget from tkinter import VERTICAL, HORIZONTAL class DoubleScrolledFrame: def __init__(self, master, **kwargs): width = kwargs.pop('width', None) height = kwargs.pop('height', None) self.outer = Frame(master, **kwargs) self.vsb = Sc...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: addr_book.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.pro...
import asyncio import sys if sys.version_info >= (3, 9): from zoneinfo import ZoneInfo else: from pytz import timezone as ZoneInfo import acron async def do_the_thing(): print("Doing the thing") async def run_jobs_forever(): do_thing = acron.SimpleJob( name="Do the thing daily", schedule="...
""" ORY Hydra Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. # noqa: E501 The version of the OpenAPI document: v1.9.1 Generated by: https://openapi-generator.tech """ class OpenApiException(Exception): """The base exception class for all Op...
"""Tests for our places functionality.""" import pytest from metno_locationforecast import Place from dryrock import places @pytest.fixture def simple_places_file(): return "./tests/test_data/simple_places.csv" class TestGetPlaces: def test_with_simple_places_file(self, simple_places_file): expect...
# # -*- coding: utf-8 -*- """Development related tasks to be run with 'invoke'""" import os import shutil import invoke # shared function def rmrf(items, verbose=True): "Silently remove a list of directories or files" if isinstance(items, str): items = [items] for item in items: if verbo...
# Copyright 2018 The Bazel 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 applicable la...
# -*- coding: utf-8 -*- """ tkcalendar - Calendar and DateEntry widgets for Tkinter Copyright 2017-2018 Juliette Monsel <j_4321@protonmail.com> with contributions from: - Neal Probert (https://github.com/nprobert) - arahorn28 (https://github.com/arahorn28) tkcalendar is free software: you can redistribute it and/o...
import urllib.parse import requests import json from django.conf import settings def encode_name(raw_name): return urllib.parse.quote(raw_name, safe='') \ .replace('.', '%2e') \ .replace('-', '%2d') \ .replace('~', '%7e') \ .replace('_', '%5f') \ .replace('%', '-') def us...
from hashlib import sha224 from random import randint from uuid import uuid4 from django.contrib import admin from django.forms import ModelForm from django.utils.translation import gettext_lazy as _ from oidc_provider.models import Client, Code, RSAKey, Token class ClientForm(ModelForm): class Meta: mo...
''' Trains a DenseNet-40-12 model on the CIFAR-10 Dataset. Gets a 94.84% accuracy score after 100 epochs. ''' from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np from keras import backend as K from keras.callbacks import ModelCheckpoint, Red...
import tensorflow as tf import jinja2 output_file = "test_avgpool.cpp" const_file = "constants_avgpool.hpp" PADDING = "VALID" const_str = """ static const float s_in_{{ test_name }}[{{ input_size }}] = { {% for x in ref_in %} {{ x }}{{ "," if not loop.last }} {% endfor %} }; static const float s_ref_out_{{ test_name...
# coding: utf-8 # In[2]: import numpy as np import pandas as pd from keras.utils.np_utils import to_categorical from sklearn.model_selection import train_test_split # In[2]: # This function is called from Main and expects train and test values for x and y def load_ag_data(authors = None, docID = None): ...
import networkx as nx from nose.tools import * def test_random_partition_graph(): G = nx.random_partition_graph([3, 3, 3], 1, 0) C = G.graph['partition'] assert_equal(C, [set([0, 1, 2]), set([3, 4, 5]), set([6, 7, 8])]) assert_equal(len(G), 9) assert_equal(len(list(G.edges())), 9) G = nx.rand...
"""Test the Synapse command line client. """ import base64 import os import pytest from unittest.mock import call, Mock, patch, MagicMock import synapseclient.__main__ as cmdline from synapseclient.core.exceptions import SynapseAuthenticationError, SynapseNoCredentialsError from synapseclient.entity import File imp...
import os import pygame from .animation import Animation class FireExplosion(Animation): def __init__(self, position): super().__init__(position) self.numImages = 11 self.width = 100 self.height = 100 self.attackAnimationDuration = 15 self.animationSpeed = 3 ...
import json import pytest from PyQt5.QtCore import (QByteArray, QDataStream, QIODevice, QMimeData, QPoint, Qt) from PyQt5.QtGui import QDragEnterEvent, QDragMoveEvent, QDropEvent import qmxgraph.constants import qmxgraph.js import qmxgraph.mime def test_error_redirection(loaded_graph): ...
# Copyright 2020 The Feast 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
# vFabric Administration Server API # Copyright (c) 2012 VMware, 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 ...
import os import sys import torch from pathlib import Path import nni.retiarii.evaluator.pytorch.lightning as pl from nni.retiarii import serialize from base_mnasnet import MNASNet from nni.retiarii.experiment.pytorch import RetiariiExperiment, RetiariiExeConfig from nni.retiarii.strategy import TPEStrategy from torch...
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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 Lice...
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
""" #Trains a ResNet on the CIFAR10 dataset. """ from __future__ import print_function import keras from keras.layers import Dense, Conv2D, BatchNormalization, Activation from keras.layers import AveragePooling2D, Input, Flatten from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, LearningRa...
#!/usr/bin/env python3 import json import logging import os import sys import redis import shared.util as util from shared.exceptions import AlreadyProcessed, CurrentlyProcessing def main(): for message in reddit.inbox.stream(): search(message) def search(message): bot_mention = util.contains_user...
from flask import jsonify, request from app import app, bcrypt from app.auth.utilities import AuthToken, ResponseCreator from app.auth.utilities import login_required_jwt from app.models.BlackListedToken import BlackListedToken from app.models.Tabs.Tab import Tab, TabStatus from app.models.Tabs.TabTransaction import T...
import os import argparse from management_api import ManagementAPIClient from utils import read_yaml, should_use_external_idp if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--global_config_yaml", help="global configuration file path", default=os.path.join('resource...
import random LOW_PRIMES = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 27...
from ..app.crud import CRUDBase from .models import Permission class PermissionCRUD(CRUDBase): model = Permission @classmethod def is_active(cls, session, id: int) -> bool: permission: Permission = cls.get(session, id) if permission: return permission.is_active @classmet...
import chainer def get_classifer(clsf_type, clsf_path): from common.models import Inception if clsf_type == 'inception': model = Inception() args = { 'get_feature': True, 'scaled': True, 'resize':True, } else: raise NotImpl...
# 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 ...
import torch import torchvision from torchvision import transforms import numpy as np from models.Q_mnist import QMNIST from models.Q_mnist import QMNIST_PSD from models.Q_mnist import Q from tensorboardX import SummaryWriter import argparse import os def print_losses(rec, q, tot, numerador, denominador): # print_...
import os, shutil import json from xml.etree import ElementTree as ET from GeometrA.src.File.Project import Project class WorkSpace: def __init__(self, path=None, project=None): self.projects = {} if path and project: self.load(path, project) self.focus = { "Projec...
# -*- coding: utf-8 -*- ''' Contract Context ''' __virtualname__ = 'ctx_update' def pre(hub, ctx): ''' ''' assert ctx.args == [hub, True] # Let's replace the context arguments ctx.args[1] = False assert ctx.args == [hub, False] def call(hub, ctx): ''' ''' assert ctx.args == [hub...
# filenames-to-html.py # match images w/ project titles ################### FUNCTIONS: ############# # write HTML to string, strip excess whitespace def textToString(file): with open(file, 'rt', encoding='utf-8') as myfile: html = myfile.read() string = html.strip().replace('\n', '').replace('\t', '') return s...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals import argparse import re import subprocess import tempfile import gdb import pwndbg.commands import pwndbg.vmmap parser = argparse.ArgumentParser(description="Dump ROP gadgets with Jon Salwan'...
# Copyright 2019 Google, Inc. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistribu...