content
stringlengths
5
1.05M
import pytest from mantisshrimp.imports import nn @pytest.fixture(scope="module") def simple_backbone(): class SimpleBackbone(nn.Module): def __init__(self): super().__init__() self.c1 = nn.Conv2d(3, 8, 3, 2) self.c2 = nn.Conv2d(8, 16, 3, 2) self.out_channel...
# -*- coding: utf-8 -*- """ Provide tools to calculate Local Parameter Importance ===================================================== """ import numpy import pandas as pd from orion.analysis.base import flatten_numpy, to_numpy, train_regressor from orion.core.worker.transformer import build_required_space def make...
import json import pandas as pd files = ['jsonfile/search_subjects.json', 'jsonfile/search_subjects (1).json', 'jsonfile/search_subjects (2).json', 'jsonfile/search_subjects (3).json'] for file in files: f = open(file, 'r', encoding='utf-8') ps = json.load(f) numl = [] for p in ps['subjects']: ...
########################################################################## # # Copyright (c) 2017, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
# # Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. # import sys import logging import greengrasssdk # Setup logging to stdout logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) client = greengrasssdk.client('iot-data') def uptime_handler(e...
import hashlib import base64 import ecdsa from connaisseur.exceptions import InvalidPublicKey def verify_signature(public_base64: str, signature_base64: str, message: str): """ Verifies the given bas64-encoded signature with the base64-encoded public key and serialized message. The message should not con...
""" author: Florian Krach & Calypso Herrera code for parallel training """ # ===================================================================================================================== import numpy as np import os, sys import pandas as pd import json import socket import matplotlib import copy from sklearn...
import torch from .Module import Module from .utils import clear class Reshape(Module): def __init__(self, *args): super(Reshape, self).__init__() if len(args) == 0 and isinstance(args[0], torch.Size): self.size = args[0] else: self.size = torch.Size(args) ...
from vis_dataclasses import load_image_file_zipped from pathlib import Path from typing import Tuple from dataclasses import dataclass from PIL import Image import pygame import numpy as np import rasterio as rio def pil_image_to_surface(im): return pygame.image.fromstring(im.tobytes(), im.size, im.mode) def wr...
""" Time Complexity: O(1) Space Complexity: O(1) """ """ Time Complexity: O(n) Space Complexity: O(1) """ def sum_n_natural_numbers(n: int) -> int: """"n: 1 + 2 + 3 + ... + n""" result = 0 for i in range(1, n + 1): result += i return result print(sum_n_natural_numbers(10)) print(sum_n_natural_...
import tensorflow as tf import numpy as np import math import time import os import glob import cv2 import datetime import scipy as sp from model_v2 import ESPCN from utils import ( input_setup, checkpoint_dir, read_data, checkimage, imsave, imread, load_data, preprocess, modcrop ) ...
# Support for python2 from __future__ import print_function # Import ctypes from ctypes import * # Importing Numpy (math, arrays, etc...) import numpy as np # Import platform to detect OS from sys import platform, exit # Import os utils from os import path # Import thermo from . import thermo from . import cubic c_len...
""" Author: RedFantom License: GNU GPLv3 Copyright (c) 2017-2018 RedFantom """ import sys from unittest import TestCase from ttkthemes import ThemedTk from tkinter import ttk def printf(string, end="\n"): sys.__stdout__.write(string + end) sys.__stdout__.flush() class TestThemedWidgets(TestCase): """ ...
# -*- coding: utf-8 -*- """ # Deep Learning - Recurrent Neural Networks Implementation of a simple LSTM network that tries to estimate the google stock prices given a sequence of data. """ import numpy as np import pandas as pd import matplotlib.pyplot as plt """## 1. Import your datasets train and test """ train ...
from .subcmd import SubCmd class ResumeCmd(SubCmd): def add_parser(self, subparser): self.parser = subparser.add_parser('resume', help='Resume a previously stopped job') self.parser.add_argument( 'id', help='ID of crawler job' ) def execute(self, args): ...
# 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 agreed to in writing, ...
'''' Given an array of integers nums and an integer k, determine whether there are two distinct indices i and j in the array where nums[i] = nums[j] and the absolute difference between i and j is less than or equal to k. Example For nums = [0, 1, 2, 3, 5, 2] and k = 3, the output should be containsCloseNums(nums, k) ...
import spotipy from spotipy.oauth2 import SpotifyOAuth import os from secret import * os.environ["SPOTIPY_CLIENT_ID"] = clientId os.environ["SPOTIPY_CLIENT_SECRET"] = clientSecret os.environ["SPOTIPY_REDIRECT_URI"] = "https://open.spotify.com/" scope = "user-library-read" username = '1146603936' auth_user = SpotifyO...
import os import storage def _readConfig(f): try: return storage.json.load(f) except IOError: return [] dir_path = os.path.dirname(os.path.realpath(__file__)) defaultConfig = _readConfig(dir_path + '/config_default.json') userConfig = _readConfig(dir_path + '/config.json') overrides = {} # Fi...
""" Welcome to CARLA manual control. Use ARROWS or WASD keys for control. W : throttle S : brake A/D : steer left/right Q : toggle reverse Space : hand-brake P : toggle autopilot M : toggle manual transmission ,/. ...
import logging from tweesky.parser.html_parser import HtmlParser from tweesky.parser.spotify_parser import SpotifyTrack, SpotifyAlbum, SpotifyArtist, SpotifyEpisode, SpotifyPlaylist, \ SpotifyShow def get_parser(url=None, html=None): if 'open.spotify.com' in url: return get_spotify_handler(url) e...
import pandas as pd tweets_df = pd.read_csv('tweets.csv') # Extract the created_at column from df: tweet_time tweet_time = tweets_df['created_at'] # Extract the clock time: tweet_clock_time tweet_clock_time = [entry[11:19] for entry in tweet_time if entry[17:19] == '19'] # Print the extracted times print(tweet_cloc...
import os from importlib import import_module def get_all_features(module=None): all_values = [] files = ['features/'+module+'/'+name for name in os.listdir('./features/'+module)] for fname in files: if fname.endswith('.pyc'): os.remove(fname) for filename in files: if '.p...
"""handles feature extraction""" # rewrite of https://github.com/leelabcnbc/tang-paper-2017/blob/master/tang_2017/feature_extraction.py from torchvision.models import vgg16, vgg16_bn, vgg19, vgg19_bn from leelabtoolbox.feature_extraction.cnn import (cnnsizehelper, generic_network_definitions) from leelabtoolbox.prepro...
from DataUtil import * if __name__ == '__main__': image_paths = getAllImageData() print(len(image_paths['naip_2013'])) print(len(image_paths['naip_2017'])) print(len(image_paths['nlcd_2013'])) print(len(image_paths['nlcd_2016'])) print(len(image_paths['landsat_2013'])) print(len(image_paths...
#!/usr/bin/python # -*- coding: utf-8 -*- from time import strftime from django.contrib import admin from django.contrib.admin import AdminSite from book.models import book from django.utils.translation import ugettext_lazy as _ class bookAdmin(admin.ModelAdmin): # title = models.CharField("分类名称",max_length=100,d...
from django.shortcuts import render from django.http import HttpResponse from blog.models import Post # Create your views here. # index view def index(request): all_posts = Post.objects.all() posts_data = { # we'll access all post with 'posts' name. 'posts': all_posts } return rende...
import numpy as np import pandas as pd import timeit import itertools from typing import List, IO from numpy import int8, int64, ndarray from numpy import uint8 # type: ignore[attr-defined] import binascii loops = 1000 t = 0.0 # type:float # read 10 lines as bytes: 15us (winner) def readfile1(): # type: () -> Lis...
# coding=utf-8 from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not edit class KlNatuursteentegelGebruiksklasse(KeuzelijstField): """Mogelijke waarden voor de ...
from django.http import HttpResponse from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging class pluginManagerGlobal: @staticmethod def globalPlug(request, eventInQuest, response = None): if response == None: hookReturn = eventInQuest.send(sender=None, request=request) ...
from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from exchangeapi.routers.routers import router as api_router from exchangeapi.db.mongodb_utils import connect_to_mongo, close_mongo_connection app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins="*", ...
""" This module contains the Poller logic """ import asyncio import logging import os import signal from typing import Dict from suzieq.poller.worker.inventory.inventory import Inventory from suzieq.poller.worker.services.service_manager import ServiceManager from suzieq.poller.worker.writers.output_worker_manager \ ...
#!/usr/bin/env python3 """ Sultanov Andriy MIT License 2020 """ def main(): # Creating a new library instance library = Library() # Adding a new book library.add_book("Macbeth", "Macbeth.txt", "Shakespeare, William", 1606) # Created a new Category Author Shakespeare, William # Created a new C...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import subprocess from builtins import bytes, range from os.path import abspath, dirname from os.path import join as join_path from random import randint from CryptoAttacks.Block.gcm import * from CryptoAttacks.Utils import log def...
#JO-KEN-PO import time import random lista = ("PEDRA","PAPEL","TESOURA") pcopcao = random.randint(0,2) print('''Suas opções: [ 0 ] PEDRA [ 1 ] PAPEL [ 2 ] TESOURA''') opcao = int(input('Qual a sua jogada? ')) time.sleep(1) print("JO") time.sleep(1) print("KEN") time.sleep(1) print("PO!") time.sleep(1) print('-='*15) p...
#!/usr/bin/env python3 """Create an Aruco markers for testing. It can create a single marker or a pair for easy testing. """ __author__ = "Steve Geyer" __copyright__ = "Copyright 2019, Steve Geyer" __credits__ = ["Steve Geyer"] __license__ = "BSD 3-Clause License" __version__ = "1.0.0" __status__ = "Development" im...
from PolyEdit3D.Widgets.PlyToolPanel import PlyViewportToolPanel, PlyBtnSetWireView, PlyBtnDrawPlaneByVector from PolyEdit3D.GL.Renderer import PlyRenderer, PlyViewportCamera from PolyEdit3D.GL.Elements import PlySceneAxisDots, PlySceneAxisLines, PlySceneGrid from PolyEdit3D.GL.GeometryEngine import GeometryEngine, Ply...
class Solution: @staticmethod def search_matrix(matrix, target): return Solution.upper_right_solution(matrix, target) pass @staticmethod def simple_solution(matrix, target): for row in matrix: for item in row: if item == target: re...
from django.shortcuts import render, redirect from django.urls import reverse from django.views.generic import CreateView from django.contrib import messages from django.contrib.auth import login from django.contrib.auth.decorators import login_required from django.views.generic.detail import DetailView from .models im...
class Node: def __init__(self, data): "constructor to initiate this object" # store data self.val = data # store reference (next item) self.next = None return def has_value(self, value): "method to compare the value with the node data" if sel...
import re nombres = ["Sandra López", "Antonio Gómez", "María López", "Jara Martín", "Lara Pérez"] [print(nombre, end="\n") for nombre in nombres if re.match(".ara", nombre)]
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\paul\Dropbox\Python\projects\Shape_Calculator\application\pyqt_ui\uiFormTabs.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fro...
# Copyright (c) 2016, Ethan White # All rights reserved. # # 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...
""" Helpers for working with URLs in arXiv Flask applications. This module provides :func:`external_url_handler`, which is attached to Flask application instances by :class:`arxiv.base.Base`. This leverage's Flask's built-in hook for :class:`flask.BuildError` exception handlers, described in the :func:`flask.url_for` ...
""" Entradas Lectura de la factura-->float-->L Costo kilovatio-->float-->CK Salidas Monto total de la factura-->float-->MT """ L=float(input("Ingrese la lectura de su factura: ")) CK=float(input("ingrese el costo del kilovatio: ")) MT=(L*CK) print("Monto total de su factura: "+str(MT))
import numpy as np from grad_check import test_gradient import deepart def gen_test_target_data(net, targets): input_shape = deepart.get_data_blob(net).data.shape target_data_list = [] for target_i, (target_img_path, target_blob_names, is_gram, _) in enumerate(targets): # Copy image into input b...
from django.shortcuts import redirect # In Django, middleware is a lightweight plugin that processes during request and response execution. Middleware is used to perform a function in the application. The functions can be a security, session, csrf protection, authentication etc. Django provides various built-in middle...
import model3 as M import tensorflow as tf import numpy as np import network import datareader BSIZE = 128*4 EPOCH = 30 # data_reader = datareader.DataReader('imglist_iccv.txt', BSIZE) tf.keras.backend.set_learning_phase(True) def loss_func(out, label): lb = tf.convert_to_tensor(label) out = tf.nn.log_softmax(ou...
"""Implementation of classic arcade game Pong.""" LINK = "http://www.codeskulptor.org/#user47_2HxT8SEaWe_8.py" import simplegui import random # Constants WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_LENGTH = 80 PAD_VEL = 4 # helper functions def add_vec(first_vector, second_vector, dimensions = 2, wr...
# -*- coding: utf-8 -*- # !/usr/bin/env python # Copyright 2021 zhangt2333. All Rights Reserved. # Author-Github: github.com/zhangt2333 # main.py 2021/9/13 14:00 import spider username = "账号" password = "统一认证密码" sleep_time = 1.0 if __name__ == '__main__': spider.main(username, password, sleep_time)
import logging from telegram import ParseMode from telegram.ext import ExtBot from telegram.ext import Defaults from telegram.utils.request import Request from bot import database from bot.bot import StickerBot from bot.utils import log from config import config as CONFIG logger = logging.getLogger(__name__) sticke...
import plotly.express as px import pandas as pd import datetime class SolutionVisualizer: def __init__(self): pass def print_solution(self, solution): if(solution is None): print("No solution was found!") return KT = max(solution.keys()) K = KT[0] ...
""" Linear INterpolation Functions. theta refers to the full set of parameters for an adaptive linear interpolation model, [n, y0, x1, y1, x2, y2, ..., x_n, y_n, y_n+1], where n is the greatest allowed value of ceil(n). The reason for the interleaving of x and y is it avoids the need to know n. """ import numpy as np...
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import datetime import dateutil.tz from specfile.changelog import Changelog, ChangelogEntry from specfile.sections import Section def test_parse(): changelog = Changelog.parse( Section( "changelog", [...
from typing import Union import torch.nn as nn import torch.utils.data from mighty.trainer.gradient import TrainerGrad from mighty.utils.common import find_layers from mighty.utils.data import DataLoader from torch.optim.lr_scheduler import _LRScheduler, ReduceLROnPlateau from utils.layers import BinaryDecoratorSoft,...
from setuptools import setup from setuptools import find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( VERSION = '0.0.0' setup( name='auditdb', version=V...
import os import sys import random def read_write_1(infile,ofile): with open(ofile, 'w') as out_f: with open(infile,'r',errors='ignore') as in_f: lines = in_f.readlines() random.shuffle(lines) for line in lines: line_split = line.split(' ', 1) ...
#!/usr/bin/env python3 import logging import common if __name__ == "__main__": # setup args and logging args = common.setup_args(domain=common.ArgMod.REQUIRED, llist=common.ArgMod.REQUIRED) common.setup_logging(args.verbose) fqdn_listname = "{}@{}".format(args.llist, args.domain) logging.info("...
from pathlib import Path from zeep.exceptions import Fault ROOT_DIR: Path = Path(__file__).parent CUCM_LATEST_VERSION: str = "14.0" USERNAME_MAGIC_KEY: str = "73q0eWFaIE2JJw8FMNeX" URL_MAGIC_KEY: str = "8Cu16DGzNvunSsDNOTrO" DUMMY_KEY: str = "xlGoVnofkKjNSgnwA9Z7" DISABLE_SERIALIZER = False DISABLE_CHECK_TAGS = Fals...
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: atomix/value/value.proto # plugin: python-betterproto from dataclasses import dataclass from typing import AsyncGenerator, Optional import betterproto from atomix.proto import headers class EventResponseType(betterproto.Enum): UPDATED = 0 @...
import importlib import os from functools import lru_cache from urllib.parse import urlparse from django.core.exceptions import ValidationError, ObjectDoesNotExist from django.utils.translation import ugettext_lazy as _ from orchestra import plugins from orchestra.contrib.databases.models import Database, DatabaseUse...
#!/usr/bin/env python # coding=utf-8 from functools import wraps from flask import abort from flask.ext.login import current_user from .models import Permission def permission_required(permission): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): if not current_user.c...
import os import re from setuptools import find_packages, setup with open( os.path.join(os.path.dirname(__file__), 'src', 'apialchemy', '__init__.py') ) as v_file: VERSION = ( re.compile(r""".*__version__ = ["']([^\n]*)['"]""", re.S) .match(v_file.read()) .group(1) ) with open(os....
import datetime import os import json import logging from datetime import timedelta from logging.config import fileConfig from logging.handlers import RotatingFileHandler from flask import Flask, Response, request from flask_mongoengine import MongoEngine from flask_cors import CORS from flask_jwt_extended import JWTMa...
import nipype.pipeline as pe from nipype.interfaces.utility import Function # ToDo: not use a mutable argument for sg_args def _check_if_iterable(to_iter, arg): if not isinstance(arg, list): arg = [arg] * len(to_iter) return arg fix_iterable = pe.Node(Function(input_names=['to_iter', 'arg'], outpu...
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. """ Tests constant folding with globals. """ import dace import numpy as np from dace.frontend.python import astutils from dace.frontend.python.newast import (GlobalResolver, ConditionalCodeResolver, ...
from django.db import models class Contato(models.Model): nome = models.CharField(max_length=50) endereco = models.CharField(max_length=200) email = models.EmailField(max_length=100) data_nascimento = models.DateField() telefone = models.CharField(max_length=20) def __str__(self): ret...
#!/usr/bin/env python3 import csv import gzip import sys import utils # Trawls through the RU-IRA dataset and counts basic statistics within a # specified time window. if __name__=='__main__': fn = sys.argv[1] start_ts = utils.extract_ts_s(sys.argv[2], fmt=utils.DCW_TS_FORMAT) end_ts = utils.extr...
import numpy as np import matplotlib.pyplot as plt import sys, os sys.path.append("../../../toolbox") from toolbox import plot as ph import helpers from pathlib import Path sys.path.append("../../../gempy") from gempy.assets import topology as tp import scipy.stats data_folder = Path("D:/datasets/paper_topology/03_gul...
from django.test import TestCase, Client from django.urls import reverse from guardian.shortcuts import assign_perm from guardian.utils import get_anonymous_user from rnapuzzles.models import CustomUser, Group as CustomGroup class GroupView(TestCase): def setUp(self): self.user_without = CustomUser.objec...
#!/usr/bin/env python # A simple recurrent neural network that learns a simple sequential data set. __author__ = 'Tom Schaul, tom@idsia.ch and Daan Wierstra' from datasets import AnBnCnDataSet #@UnresolvedImport from pybrain.supervised import BackpropTrainer from pybrain.structure import FullConnection, RecurrentNetw...
from django.utils import timezone from django.db import models class BaseModel(models.Model): c_at = models.DateTimeField(default=timezone.now) u_at = models.DateTimeField(auto_now=True) class Meta: abstract = True
'''Bradley adaptive thresholding. Credit goes to http://stackoverflow.com/a/33092928/4414003 where user @rayryeng wrote an implementation much more efficient than mine. To see my original code, visit that link.''' import numpy as np from PIL import Image import time def bradley_threshold(image, s=None, t=None): # C...
import os from functools import partial from pydantic import validator, AnyHttpUrl, Field from wunderkafka.time import now from wunderkafka import SRConfig, ConsumerConfig, SecurityProtocol, AvroConsumer # If you are the fan of 12 factors, you may want to config via env variables class OverridenSRConfig(SRConfig): ...
from .model_connector import ModelConnector class GRPCConnector(ModelConnector): @staticmethod def check_import(): import grpc import tensorflow as tf import tensorflow_serving def __init__(self, arg, name=''): super().__init__(arg) # warmup import grpc ...
from datetime import datetime import hashlib import json import random import re import time from urllib.parse import quote, parse_qs, urlencode import uuid def urlencode_plus(s): if type(s) == str: return quote(s) elif type(s) == dict: return urlencode(s) else: raise TypeError("ur...
import argparse import logging import unittest from . import arguments parser = arguments.test_parser() args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.INFO) else: logging.basicConfig() if args.test: from . import tests if args.test is not True: tests = unittest...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 14 10:23:45 2022 @author: frederikhartmann """ # ##################################### # ############# Imports ############### # ##################################### # Data manipulation import torch import os # Debugging import pdb import seabo...
import pytest from ..openapi_data_generator.OptionalCombinationGenerator import generate_all_possible_objects from ..openapi_data_generator.ObjectGenerator import ObjectsGenerator from compare_objects import compare_objects from openapi_schema_generator import OpenApiSchemaValidator, OpenApiSchemaGenerator src_path = ...
# -*- coding: utf-8 -*- import sys yVvnDsmDHFJwtkzTXrdPQxkddnKDxtdeyzGKftNynOBsbgmefQcpyMNEkJSiTvyFhdMOkDJqLKVqlQDQvtxHdEYtwpeYKKdhrkXdqeTQJsqLafHvcGgPyhJUWsHyxfoI = 'dCjAzhVjYAMNLNAYdScOtNXXEAuhZgtgPBRZliyRCZlnAYDPQVCrRyKddQIvYCFYDtjeMGUtzIOGLWIGddKIwOmcTdzLuutsazCRJplsOXAmOUzzpUsSTQCCmCJFtKIb' lbFNowPVchqhHrFMyyHnRmI...
from __future__ import annotations import hashlib import io import os import stat from pathlib import Path def read_file(filepath: Path) -> bytes: """Return the contents of a file as bytes. If the file is a symlink, read its contents instead of its target. """ if filepath.is_symlink(): retur...
"""Generate call_functions_batch.sh - in : from/to date - out: shell script for calling cloud functions """ import datetime import json import sys def main(): args = sys.argv oldest_dt = datetime.datetime.strptime(args[1], '%Y-%m-%d') latest_dt = datetime.datetime.strptime(args[2], '%Y-%m-%d') ...
import os from pickle import dump, load from PyQt5.QtCore import Qt, pyqtSignal, QSize from PyQt5.QtGui import QIcon, QStandardItem, QStandardItemModel, QPixmap, QLinearGradient from PyQt5.QtWidgets import (QAbstractItemView, QPushButton, QFileDialog, QLineEdit, QDialog, QLabel, QFormLayout, ...
import os import time import tensorflow as tf from tensorflow.keras.initializers import RandomNormal from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense, BatchNormalization, \ LeakyReLU, Conv2DTranspose, Conv2D, Dropout, Flatten, Reshape import scipy as sp import numpy as np from LkGA...
from django.test import TestCase from django.contrib.auth.models import User from .models import healthservices,neighbourhood import datetime as dt # Create your tests here. class neighbourhoodTestClass(TestCase): def setUp(self): self.kataret = neighbourhood(neighbourhood='kataret') def test_instance...
import pytest import numpy as np from ..posrich import posrich import pkg_resources PATH = pkg_resources.resource_filename(__name__, 'test_data/') def test_posrich(): "Test positional enrichment" # load data X_list = open(PATH+'multiple.txt').read().splitlines() X_err = 'AGT2HT9' # test posrich ...
import FWCore.ParameterSet.Config as cms from RecoLocalTracker.SiStripZeroSuppression.DefaultAlgorithms_cff import * siStripZeroSuppression = cms.EDProducer("SiStripZeroSuppression", Algorithms = DefaultAlgorithms, RawDigiProducersList = cms.VInputTag( cms.InputTag('siStripDigis','VirginRaw'), ...
#!/usr/bin/env python #=============================================================================== # Copyright (c) 2014 Geoscience Australia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: ...
#!/usr/bin/env python import django, sys, glob, os sys.path.append('../../server/') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dva.settings") django.setup() from dvaui.view_shared import handle_uploaded_file from dvaapp.tasks import perform_import, perform_frame_download from django.core.files.uploadedfile import...
x = int(input(" ")) y = 5*x-400 print(y) if y < 100: print('1') elif y == 100: print('0') elif y > 100: print('-1')
from __future__ import division, print_function, unicode_literals import argparse import json import random import time from io import open import os import numpy as np import torch from torch.optim import Adam from convlab2.policy.mdrg.multiwoz.utils import util from convlab2.policy.mdrg.multiwoz.model import Model...
from django.db import models class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() # slug = models.SlugField() # class Meta: # verbose_name = _("") # verbose_name_plural = _("s") def __str__(self): return self.title # def get...
# Generated by Django 3.0.5 on 2020-05-19 21:16 from django.db import migrations, models import django.db.models.deletion import exercises.helper import exercises.validators class Migration(migrations.Migration): dependencies = [ ('exercises', '0012_auto_20200514_2227'), ] operations = [ ...
from .api.client import ApiClient from .api.external_task import ExternalTaskApi class CamundaClient: """ A client for communicating with a Camunda server. """ def __init__(self, *args, **kwargs): self.api = ApiClient(*args, **kwargs) @property def external_task(self): return...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: POGOProtos/Data/Logs/ActionLogEntry.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...
from threading import Lock from typing import Any import requests class SessionCore: """ SessionCore is a singleton class. """ _has_instance = None _lock = Lock() def __new__(cls: Any) -> "SessionCore": if not cls._has_instance: with cls._lock: if not cls...
import tensorflow as tf import numpy as np from tensorflow.contrib import rnn, layers class DQL(object): def __init__(self, input_len, nb_state_token, nb_action_token): self.input_len = input_len self.nb_state_token = nb_state_token self.n...
string = "Practice Problems to Drill List Comprehension in Your Head." count = 0 for i in range(len(string)): if string[i] == ' ': count += 1 print(count) my_space = len([space for space in string if ' ' in space]) print(my_space)
def hello_world(): return "Hello from Python CI Template!" if __name__ == "__main__": print(hello_world())
from keras.utils import Sequence import numpy as np import cv2 #from script.cloud_images_segmentation_utillity_script import build_masks from script.my_util import build_masks class DataGenerator(Sequence): def __init__(self, images, imageName_to_imageIdx_dict, dataframe, batch_size, n_channels, target_...