text
stringlengths
1
927k
from pynput import mouse class MyException(Exception):pass X = [] Y = [] NumberOfMouseClicks = 0 print('Click Origin') def on_click(x, y, button, pressed): button = str(button) global NumberOfMouseClicks NumberOfMouseClicks = NumberOfMouseClicks + 1 if NumberOfMouseClicks==1: print('Click To...
from tkinter import * if __name__ == '__main__': widget = Button(text = 'spam', padx = 10, pady = 10) widget.pack(padx = 20, pady = 20) widget.config(cursor = 'gumby') widget.config(bd = 8, relief = RAISED) widget.config(bg = 'dark green', fg = 'white') widget.config(font = ('helvetica', 20, '...
# Copyright (c) 2011 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 ...
# -*- coding: utf-8 -*- """ bilibili user ~~~~~~~~~~~~~ 目标网站: www.bilibibli.com 爬虫描述: 爬取 bilibili 用户信息 示例链接: https://space.bilibili.com/33683045/ 接口格式: 示例接口: 用户信息 - https://api.bilibili.com/x/space/acc/info?mid=26019347&jsonp=jsonp 收藏夹 - https://api.bilibili.com/medialist/gateway/base/created?pn=1&ps=10&up_mid...
from itertools import islice from lxml import etree from urllib import parse MAIN_PAGE = "Wikiquote:Accueil" def extract_quotes(tree, max_quotes): # French wiki uses a "citation" HTML class node_list = tree.xpath('//div[@class="citation"]') quotes = list(islice((span.text_content() ...
from polog.handlers.file.rotation.rules.rules.file_size_rule import AbstractRule class DateTimeRule(AbstractRule): @classmethod def prove_source(cls, source): raise NotImplementedError def check(self): raise NotImplementedError
'''graph1 = { 'A' : ['B','S'], 'B' : ['A'], 'C' : ['D','E','F','S'], 'D' : ['C'], 'E' : ['C','H'], 'F' : ['C','G'], 'G' : ['F','S'], 'H' : ['E','G'], 'S' : ['A','C','G'] }''' def create_graph(): graph1={} no_of_nodes = int(input("Enter the no. of nodes in the graph : ")) for i in range(0,no_of_nodes): pr...
from sql_alchemy import banco class HotelModel(banco.Model): __tablename__ = 'hoteis' hotel_id = banco.Column(banco.String, primary_key=True) nome = banco.Column(banco.String(80)) estrelas = banco.Column(banco.Float(precision=1)) diaria = banco.Column(banco.Float(precision=2)) cidade = banco.C...
# BOJ 17219 import sys si = sys.stdin.readline n, m = map(int, si().split()) passwords = {} for _ in range(n): url, password = si().split() passwords[url] = password for _ in range(m): url = si().strip() sys.stdout.write(passwords[url]) print()
# test_rawread.py """unittest tests for dicom.filereader module -- simple raw data elements""" # Copyright (c) 2010-2012 Darcy Mason # This file is part of pydicom, relased under an MIT license. # See the file license.txt included with this distribution, also # available at http://pydicom.googlecode.com from io ...
"""f1_blog URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/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='home') Class-based...
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class Slider(Component): """A Slider component. A slider component with a single handle. Keyword arguments: - min (number; optional): Minimum allowed value of the slider. - max ...
import numpy as np import cross_sections as xs xs1 = xs.IBeam(1, 1, 0.1, 0.1) L = 10 p = 1 E = 29000 def constant(x, **kwargs): return 1 def linearup(s, **kwargs): return x load = constant def simpsons(f, a, b, n): #function, start, stop, intervals if n % 2 == 0: h = (b-a)/n k = 0.0 x = a + h for i ...
from django.shortcuts import render, redirect from django.utils import translation, timezone from django.http import HttpResponseRedirect from django.urls import reverse from product.models import Product, Product_type from .forms import ProductForm from django.core.paginator import Paginator, EmptyPage, PageNotAnInteg...
# Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project au...
import datetime from django.db import models from .models import ( Region, Department, Site, Building, Room, Rack, Device, ) def _regions(): """ All regions """ return Region.objects.all() def _departments(): """ All departments """ return Department...
import logging import json import os import shutil import subprocess import sys # PyArmor in the parent path PYARMOR_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) os.environ['PYARMOR_PATH'] = PYARMOR_PATH sys.path.insert(0, PYARMOR_PATH) from config import version, config_filename, capsule_fil...
# 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 ...
import datetime from pydantic import BaseModel, Field, validator class DateTimeModelMixin(BaseModel): created_at: datetime.datetime = None updated_at: datetime.datetime = None @validator('created_at', 'updated_at', pre=True) def default_datetime( cls, value: datetime.datetime...
def get_package_data(): return {'astropy_helpers.src': ['compiler.c']}
import toml from os.path import join, abspath, dirname import sys import re root = abspath(join(dirname(__file__), "..")) def update_cargo(ver): path = join(root, "Cargo.toml") raw = toml.load(path) raw['package']['version'] = ver with open(path, "w") as f: toml.dump(raw, f) def update_pypr...
# -*- coding: UTF-8 -*- ## Расчет растояний на сфере, система координат десятичные градусы WGS-84 # Created: 12.11.2015 # Copyright: (c) nsitala 2015 import math __all_ = ['distpointwgs84'] def distpointwgs84(precoord, nextcoord): # pi - число pi, rad - радиус сферы (Земли) rad = 6372795 # ко...
from collections import deque def main(): # input R, C = map(int, input().split()) sy, sx = map(int, input().split()) gy, gx = map(int, input().split()) cs = [[*input()] for _ in range(R)] # compute sy -= 1 sx -= 1 gy -= 1 gx -= 1 deq = deque([[sy, sx]]) dist = [[-1 for...
__all__ = [ 'Interval' ] class Interval(object): '''Interval - Arbitrary half-closed interval of the form [start, end)''' def __init__(self, start, end): self.start = start self.end = end def __call__(self, value): return (1. - value) * self.start + value * self.end def __str...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import json import o...
#from .datatypes import *
#!/usr/bin/env python3 from tiden.apps.app import App from tiden.apps.nodestatus import NodeStatus from tiden.util import * class Mysql(App): tmp_pwd_log_tag = "A temporary password is generated for root@localhost:" account_tmpl = [ "CREATE USER '__USER__'@'__HOST__' IDENTIFIED BY '__PWD__';", ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """Shell Doctest """ from __future__ import print_function import re import sys import os.path import difflib import threading import locale from io import open try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty # python...
# # BSD 3-Clause License # # Copyright (c) 2021, Fred W6BSD # All rights reserved. # See licence file for more information. # import logging import operator import re import socket import threading import time from datetime import datetime from importlib import import_module import wsjtx from config import Config L...
#!/usr/bin/python import sys class InvalidWeightError(Exception): def __init__(self, needed, actual): super(InvalidWeightError, self).__init__() self.needed = needed self.actual = actual class Program(object): def __init__(self, desc): super(Program, self).__init__() i ...
""" Unit tests for the fault system """ from cStringIO import StringIO import json import mock from jsonschema import ValidationError from twisted.trial.unittest import TestCase from twisted.internet import defer from twisted.python.failure import Failure from otter.rest.decorators import ( fails_with, select_d...
from dataclasses import dataclass from tequila import TequilaException, BitString, TequilaWarning from tequila.hamiltonian import QubitHamiltonian from tequila.circuit import QCircuit, gates from tequila.objective.objective import Variable, Variables, ExpectationValue from tequila.simulators.simulator_api import simu...
import enum import logging class IOC_v2(): """Models an indicator of compromise detected during an analysis. Every IOC belongs to an AnalysisResult. """ def __init__(self, analysis, match_type, values, field, link): self.id = analysis self.match_type = match_type self.values ...
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six fr...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import pipedrive.fields class Migration(migrations.Migration): dependencies = [ ('pipedrive', '0007_auto_20170519_0052'), ] operations = [ migrations.AddField( model_name...
# # This file is part of the PyMeasure package. # # Copyright (c) 2013-2021 PyMeasure Developers # # 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 limit...
"""Functions to interact with github API.""" import json import re from io import StringIO import requests GITHUB_API_BASE = 'https://api.github.com' def build_github_url( repo, branch=None, path='requirements.txt', token=None ): """Builds a URL to a file inside a Github repository.""" repo ...
# -*- coding: utf-8 -*- """ Routes Module Currently this module contains all of the routes for the main blueprint """ from flask import render_template from flask_login import current_user, login_required from app.main import main_bp @main_bp.route('/') @main_bp.route('/public') def public(): """Public Route...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: snake_case_names.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
#!/usr/bin/python3 #-*- coding: utf-8 -*- #Daniel Gonzalez # full filter full_filter = ''' <filter> <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> </native> </filter> ''' # Create a configuration filter interface_filter = ''' <filter> <native xmlns="http://cisco.com/...
""" A stacked bidirectional LSTM with skip connections between layers. """ from typing import Optional, Tuple, List import warnings import torch from torch.nn.utils.rnn import PackedSequence, pad_packed_sequence with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=FutureWarning) import h...
# Generated by Django 3.1.1 on 2020-10-15 01:08 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('school', '0001_initial'), migratio...
import unittest import numpy as np import polars as pl import pygef.robertson.util as util import pygef.expressions as exprs class RobertsonTest(unittest.TestCase): def test_n_exponent(self): df1 = pl.DataFrame( { "type_index_n": [1.0, 1.0, 1.0], "effective_soi...
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: @staticmethod def init_app(app): pass class DevConfig(Config): DEBUG = True class TestConfig(Config): pass class LiveConfig(Config): pass config = { 'dev': DevConfig, 'test': TestConfig, 'live...
from contextlib import contextmanager import errno import os import re from random import SystemRandom import tempfile from rstr import Rstr from ._compat import which rstr = Rstr(SystemRandom()) import_module = __import__ def genpass(pattern=r'[\w]{32}'): """generates a password with random chararcters ...
import numpy as np from seisflows.tools import unix from seisflows.tools.array import loadnpy, savenpy from seisflows.tools.array import grid2mesh, mesh2grid, stack from seisflows.tools.code import exists from seisflows.tools.config import SeisflowsParameters, SeisflowsPaths, \ ParameterError, custom_import from s...
from typing import Any from typing import Iterator from typing import List from django import forms from django.http import HttpRequest from django.http import HttpResponse from django.shortcuts import render from django.template.loader import render_to_string from django.utils.safestring import mark_safe from ocflib....
# 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...
# -*- coding: utf-8 -*- """ Created on Mon Jul 27 10:49:39 2020 @author: Arthur Donizeti Rodrigues Dias """ class Category: def __init__(self, categories): self.ledger=[] self.categories = categories self.listaDeposito=[] self.listaRetirada=[] self.total_entrada = 0 ...
""" :author: Damian Eads, 2009 :license: modified BSD """ import numpy as np from scipy import ndimage from skimage import draw def square(width, dtype=np.uint8): """Generates a flat, square-shaped structuring element. Every pixel along the perimeter has a chessboard distance no greater than radius (radi...
# -*- coding: utf-8 -*- """ Created on Sun Jun 25 12:50:46 2017 @author: Sergio Cristauro Manzano """ from ..DB.MySQL_INE import MySQLAccessINE as DBContext #Server #from self.db.MySQL import MySQLAccess as DBContext #Local class RepositoryPernoctacionesINE(): ###########################################...
"""Module realize wraps on facengine objects """ import os from typing import Optional, Union import FaceEngine as CoreFE # pylint: disable=E0611,E0401 from lunavl.sdk.estimators.face_estimators.ags import AGSEstimator from lunavl.sdk.estimators.face_estimators.basic_attributes import BasicAttributesEstimator from l...
""" db: pydblite (https://pydblite.readthedocs.io) This is being developed for the MF2C Project: http://www.mf2c-project.eu/ Copyright: Roi Sucasas Font, Atos Research and Innovation, 2017. This code is licensed under an Apache 2.0 license. Please, refer to the LICENSE.TXT file for more information Created on 09 feb...
# Ranorex Webtestit Page Object File from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from pageobjects.checkout_po import CheckoutPo # Additional data: {"img...
# Copyright (c) 2013, bobzz.zone@gmail.com and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt def execute(filters=None): columns, data = ["Item:link/Item:200","Total Qty:Float:100","Qty Percent:Percent:100","Total Sales...
from pandas import read_csv import _pickle as pickle from traceback import format_exc from .common import exists, preprocess_pandas_csv from .common import try_remove DEFAULT_FREQ = 1 def load_freq(freq_fpath, min_freq=1, preprocess=True, sep='\t', strip_pos=True, use_pickle=True): f = FreqDictionary(freq_fpat...
# -*- coding: utf-8 -*- """Utilities for aggregating data """ from dribdat.user.models import Activity, Resource, User from dribdat.user import isUserActive, projectProgressList from dribdat.database import db from dribdat.apifetch import * # TBR def GetProjectData(url): data = None if url.find('//gitlab.com'...
#!/usr/bin/env python3 import sys from pathlib import Path from collections import OrderedDict import unittest from debparse.deb_control import parse as debParse import psutil import sh dpkgS = sh.dpkg.bake("-S") dpkgs = sh.dpkg.bake("-s") thisFile = Path(__file__).absolute() thisDir = thisFile.parent.absolute() repo...
from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup(name='qvidianapi', version='0.1', description='A Nice Python API to Qvidian.com', long_description=readme(), url='https://github.com/Abdellbar/qvidianapi', author='Abdelbar Aglagan...
"""Repository rule for Python autoconfiguration. `python_configure` depends on the following environment variables: * `PYTHON_BIN_PATH`: location of python binary. * `PYTHON_LIB_PATH`: Location of python libraries. """ load( "//third_party/com_github_tensorflow_tensorflow/remote_config:common.bzl", "BAZEL_...
import locale import os import platform import uuid from contextlib import contextmanager import pytest from dvc.path_info import URLInfo from .base import Base class HDFS(Base, URLInfo): # pylint: disable=abstract-method @contextmanager def _hdfs(self): import pyarrow conn = pyarrow.hdfs...
from rest_framework import mixins, generics from rest_framework.response import Response from service_user.exports import get_user_instance_with_token_id from service_application.exports import get_app_instance_with_app_id from service_application.models import UsingApplicationModel from utils import log, ParameterKeys...
# Copyright 2015 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 typing import Union, List import torch from torch import nn as nn from torch.nn import functional as F from models.layers.create_act import get_act_layer from .trace_utils import _assert class BatchNormAct2d(nn.BatchNorm2d): """BatchNorm + Activation This module performs BatchNorm + Activation in a man...
def read(fn): verts=[] faces=[] with open(fn,"r") as f: t=f.readlines() for line in t: line=line.replace("\n","") line=line.split(" ") while "" in line: line.remove("") print([line]) if line[0]=="v": vert=[] for x i...
from setuptools import setup setup( name='service-standard-python', version='0.2', description='RVU Service Standard library for Python', url='git@github.com:uswitch/service-standard-python.git', author='Site Reliability Engineering', author_email='sre@rvu.co.uk', install_requires=['flask',...
from torch.utils.data import Dataset, DataLoader from torchvision import transforms from PIL import Image import torch.nn as nn import numpy as np import torch from pathlib import Path import collections import numbers import random import os class BirdDataset(Dataset): def __init__(self, root_dir, mode, transfo...
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that a failing postbuild step lets the build fail. """ from __future__ import print_function import TestGyp import sys if s...
#!/usr/bin/env python # This file is managed by 'repo_helper'. Don't edit it directly. # stdlib import sys # 3rd party from setuptools import setup sys.path.append('.') # this package from __pkginfo__ import * # pylint: disable=wildcard-import setup( description="Runs pytest in isolation.", extras_require=ext...
""" Pinger application. Periodically poll hosts to see if they are up. Log state in the document database, but report state changes to the message Q """ from asyncio import run, get_event_loop, create_task from aio_pika import ExchangeType, connect_robust from tentacruel.config import get_config from tentacruel.pi...
""" Constants specific to the SQL storage portion of the ORM. """ from collections import namedtuple import re # Valid query types (a set is used for speedy lookups). These are (currently) # considered SQL-specific; other storage systems may choose to use different # lookup types. QUERY_TERMS = set([ 'exact', 'ie...
import argparse import logging import os import time from tools.wpt.testfiles import get_git_cmd here = os.path.dirname(__file__) wpt_root = os.path.abspath(os.path.join(here, os.pardir, os.pardir)) logger = logging.getLogger() MYPY = False if MYPY: # MYPY is set to True when run under Mypy. from typing impo...
# Copyright 2021 Zilliz. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
"""Test the check command.""" # mypy: ignore-errors # flake8: noqa import argparse from typing import Tuple from unittest.mock import MagicMock, Mock, patch import pytest import dfetch from dfetch.commands.update import Update from dfetch.manifest.manifest import Manifest from dfetch.manifest.project import ProjectE...
import xml.etree.ElementTree as ET import json from urllib.request import urlopen data = urlopen('https://lenta.ru/rss').read().decode('utf8') root = ET.fromstring(data) date_header = [] for news in root.iter('item'): title = news.find('title').text pubDate = news.find('pubDate').text date_header.append(...
{ 'variables': { 'module_name%': 'node_printer', 'module_path%': './lib/' }, 'targets': [ { "target_name": "action_after_build", "type": "none", "dependencies": [ "<(module_name)" ], "copies": [ { "files": [ "<(PRODUCT_DIR)/<(module_name).node" ], "d...
''' ''' # 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");...
from analizer_pl.abstract.expression import Expression from analizer_pl.modules.expressions import C3D from analizer_pl.C3D.operations import operation from analizer_pl.reports.Nodo import Nodo from analizer_pl.abstract.global_env import GlobalEnvironment class Identifier(Expression): def __init__(self, id, isBloc...
# Automatically generated SST Python input import sst from mhlib import componentlist # Test timingDRAM with transactionQ = reorderTransactionQ and AddrMapper=sandyBridgeAddrMapper and pagepolicy=timeoutPagePolicy # Define the simulation components cpu_params = { "clock" : "3GHz", "do_write" : 1, "num_loa...
from django.test import TestCase from nautobot.circuits.filters import ( CircuitFilterSet, CircuitTerminationFilterSet, CircuitTypeFilterSet, ProviderFilterSet, ) from nautobot.circuits.models import Circuit, CircuitTermination, CircuitType, Provider from nautobot.dcim.models import Cable, Device, Devi...
from __future__ import absolute_import, division, print_function import numbers import numpy as np from functools import partial from itertools import chain import datashape from datashape import (DataShape, Option, Record, Unit, dshape, var, Fixed, Var, promote, object_) from datashape.predica...
# Generated by Django 2.2 on 2019-04-08 22:48 import django.contrib.postgres.fields.citext from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("beers", "0022_merge_common_endings"), ] operations = [ migration...
# Copyright 2019 The Kubeflow 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 law or agreed to in...
import torch from mmdet3d.models.builder import build_voxel_encoder def test_pillar_feature_net(): pillar_feature_net_cfg = dict( type='PillarFeatureNet', in_channels=5, feat_channels=[64], with_distance=False, voxel_size=(0.2, 0.2, 8), point_cloud_range=(-51.2, -5...
import os ci = input("Commit name : ") gitPush = [ "git", "git status", "git add .", "git commit -m \"{}\"".format(ci), "git push", ] for x in gitPush: os.system(x) #Written by Htet Phyo Lin. #If you have any errors. plz contact me " htetphyolin18@ucsmgy.edu.mm " .
import datetime as dt import cx_Oracle from typing import List from src.typeDefs.outage import IOutage from src.utils.stringUtils import removeRedundantRemarks, combineTagReasonRemarks def getLongTimeUnrevivedForcedOutages(conStr: str, startDt: dt.datetime, endDt: dt.datetime) -> List[IOutage]: """fetch forced ou...
''' Conversion of basis sets to Dalton format ''' from .. import lut, manip, sort, misc, printing def write_dalton(basis): '''Converts a basis set to Dalton format ''' s = '! Basis = {}\n\n'.format(basis['name']) basis = manip.make_general(basis, False, True) basis = sort.sort_basis(basis, Fals...
import torch from torch import nn from .parts import * __all__ = ["VGGUNet", "NestedUNet"] class VGGUNet(nn.Module): def __init__(self, num_classes, input_channels=3, leak_p=0.1, factor=1, **kwargs): super().__init__() nb_filter = [ 32 // factor, 64 // factor, ...
import os import numpy as np import pandas as pd from sklearn.externals import joblib from sklearn.linear_model import LogisticRegression import os import sys print os.getcwd() sys.path.append(os.getcwd()+"/SemanticLabelingAlgorithm/semantic_labeling/main") sys.path.append(os.getcwd()+"/..") from lib import search...
import torch import torch.nn as nn from torch.autograd import Variable from torch.optim.lr_scheduler import StepLR from torchvision import datasets import torchvision.transforms as transforms from self_attention_cv import TransformerEncoder import argparse import math import numpy as np from torchvision import datasets...
import numpy as np from mushroom_rl.algorithms.value.td import TD from mushroom_rl.utils.eligibility_trace import EligibilityTrace from mushroom_rl.utils.table import Table class QLambda(TD): """ Q(Lambda) algorithm. "Learning from Delayed Rewards". Watkins C.J.C.H.. 1989. """ def __init__(self,...
# Copyright 2020 The TensorFlow Probability 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 law o...
from dotenv import load_dotenv import os from array import array from PIL import Image, ImageDraw import sys import time from matplotlib import pyplot as plt import numpy as np # import namespaces from azure.cognitiveservices.vision.computervision import ComputerVisionClient from azure.cognitiveservices.vision.comput...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mailer_throttled.tests.south_settings') from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from django.conf.urls import url from . import views urlpatterns = [ # ex: / url(r'^$', views.review_list, name='review_list'), # ex: /review/5/ url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'), # ex: /book/ url(r'^book$', views.book_list, name='book_list'), ...
""" Datum Object Model """ from decimal import Decimal from typing import Any, Dict, Optional import numpy as np from pydantic import BaseModel, validator class Datum(BaseModel): r"""Facilitates the storage of quantum chemical results by labeling them with basic metadata. Attributes ---------- labe...
# Standard packages from netCDF4 import Dataset, num2date from datetime import datetime import numpy as np import pandas as pd #____________Selecting a season (DJF,DJFM,NDJFM,JJA) def sel_season(var,dates,season,timestep): #---------------------------------------------------------------------------------------- ...
import sys from operator import add from pyspark.sql import SparkSession from pyspark import SparkContext import pyspark from pyspark.ml.linalg import Vectors import numpy as np from sklearn.linear_model import LinearRegression from pyspark.sql.types import * from pyspark.sql import functions as func from pyspark.sql.f...
import json import pytest from healthcheck import app @pytest.fixture() def apigw_event(): """ Generates API GW Event""" return { "body": '{ "test": "body"}', "resource": "/{proxy+}", "requestContext": { "resourceId": "123456", "apiId": "1234567890", ...