text
stringlengths
8
6.05M
import time, sys from random import randint # this will allow the user to enter in X and O into the grid spaces grid = {1:' ', 2:' ', 3:' ', 4:' ', 5:' ', 6:' ', 7:' ', 8:' ', 9:' '} # if player has three X's in a row haveWonX will become true triggering the if statement at the bottom of the code haveWonO = Fa...
import numpy as np from sklearn.metrics import roc_auc_score from scipy.signal import hilbert from scipy.ndimage.filters import gaussian_filter from scipy.stats import pearsonr class CorrCoeffIntervalOptimizer(object): def __init__(self, max_score_fraction=0.8, use_abs_for_threshold=True): self...
import sqlite3 conn = sqlite3.connect('pakdet.db') c2 = conn.cursor() for row in c2.execute("SELECT * FROM PAKDET"): print(row) conn.close()
from flask import request from werkzeug.urls import url_encode def apply_template_globals(app): @app.template_global() def modify_query(**new_values): args = request.args.copy() for key, value in new_values.items(): if key.endswith('_in_list'): old_list = args.get(...
#%% from sklearn.metrics import classification_report, confusion_matrix from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn import tree from IPython.display import Image import pandas as pd import numpy as np import pydotplus import os tennis_dat...
##encoding=utf-8 """ usage: cd to this directory, run cmd (crawl death record in year 2000): python dev01_taskplan.py 2 2000 """ from archives.database import client, task from archives.metadata import lastname_dict from archives.urlencoder import urlencoder from archives.htmlparser import htmlparser from...
# Author: ambiguoustexture # Date: 2020-03-11 file_result_w2v = './stuffs_92/result_w2v.txt' file_result_PC = './stuffs_92/result_PC.txt' with open(file_result_w2v) as result_w2v: count, total = 0, 0 for line in result_w2v: cols = line.split(' ') total += 1 if cols[3] == cols[4]: ...
#!/usr/bin/env python """ See cubeplt.py for 3d plotting of the cubes """ import numpy as np def make_pyvista_indices(indices): """ :param indices: (nface,3) triangles OR (nface,4) quads :return ii: vista type list """ sh = list(indices.shape) last = sh[-1] assert last in (3,4) sh...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import numpy as np import zipcodes from make_data import * from train_model import * from predict import * from decrease_price import * import pickle inputs1 = { 'price': [221900, 538000, ...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class EvtgenToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f01761...
import json import csv import numpy as np import matplotlib.pyplot as plt import os import argparse #parser for trails #use --trial trial_() to run it parser = argparse.ArgumentParser(description='Read Trial') parser.add_argument('--trial', type=str, help='Trial Number') args = parser.parse_args()...
"""inventoryproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/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') Cl...
from models.DiscordExtension import DiscordExtension from models.ExecutionContext import ExecutionContext from player import Player import asyncio import discord import logging class AliasExtension(DiscordExtension): def __init__(self, configRepo): self.configRepo = configRepo super().__init__() ...
from ..FeatureExtractor import FeatureExtractor from numpy import median as med from common_functions.plot_methods import plot_horizontal_line class medianextractor(plot_horizontal_line,FeatureExtractor): active = True extname = 'median' #extractor's name def extract(self): try: median = float(med(self.flux_da...
"""relaydomains unit tests.""" from django.core.files.base import ContentFile from django.test import TestCase from django.urls import reverse from modoboa.admin import factories as admin_factories, models as admin_models from modoboa.core.factories import UserFactory from modoboa.lib.test_utils import MapFilesTestCa...
import pykitti from .data import Downloader from .kitti_cameras_calibration_factory import KittyCamerasCalibrationFactory from .poses_dataset_adapter import PosesDatasetAdapter from .video_dataset_adapter import VideoDatasetAdapter from ..concat_dataset import ConcatDataset from ..data_transform_manager import DataTra...
from flask import Response from flask.blueprints import Blueprint import logging from flask_login import login_required, current_user from flask.templating import render_template from flask.globals import request from flask.helpers import flash, url_for, make_response from waitlist.blueprints.settings import add_menu_...
""" Created by Alex Wang On 2018-07-30 Model: https://github.com/yule-li/CosFace [Configurations]: lfw_pairs: data/pairs.txt embedding_size: 1024 model_def: models.inception_resnet_v1 save_model: False do_flip: False image_width: 112 lfw_dir: dataset/lfw-112x96 prewhiten: False lfw_nrof_folds: 10 image_heig...
"""NUI Galway CT5132/CT5148 Programming and Tools for AI (James McDermott) Skeleton/solution for Assignment 1: Numerical Integration By writing my name below and submitting this file, I/we declare that all additions to the provided skeleton file are my/our own work, and that I/we have not seen any work on this assign...
from django.urls import path from .views import QuestionsList,QuestionDetailView urlpatterns = [ path("",QuestionsList.as_view()), path("<int:pk>/",QuestionDetailView.as_view()), ]
from django.conf.urls.defaults import patterns, include, url from tastypie.api import Api from api import * from django.contrib import admin admin.autodiscover() v1_api = Api(api_name='v1') v1_api.register(UserResource()) v1_api.register(CurrentAccountResource()) urlpatterns = patterns('', url(r'^$', include('c...
"""possys URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.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 ...
#!/usr/bin/python -tt # # Copyright (c) 2011 Intel, Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; version 2 of the License # # This program is distributed in the hope that it will be us...
from django.shortcuts import render # Create your views here. from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from django.contrib.auth.models import User from rest_framework_simplejwt.tokens import RefreshToken from rest_fram...
import sys d =dict() for line in open(sys.argv[1]): sp = line.strip().split(" ") d[sp[2]] = d.get(sp[2], list()) d[sp[2]].append((int(sp[0]), sp[1])) for key in d.keys(): d[key] = sorted(d[key], key=lambda x:-x[0]) for i in range(0, max([len(x) for x in d.values()])): for key in d.keys(): ...
# https://splinter.readthedocs.io/en/latest/drivers/chrome.html from splinter import Browser from bs4 import BeautifulSoup executable_path = {'executable_path': 'chromedriver'} browser = Browser('chrome', **executable_path, headless=True) url = 'http://quotes.toscrape.com/' browser.visit(url) for x in range(1, 6): ...
import sys sys.path.append('C:\\Users\\nikit\\AppData\\Local\\Programs\\Python\\python38\\lib\\site-packages') import NBodyPlotter as nbp from NBodyPlotter import NBodySolver from NBodyPlotter import Body import matplotlib.pyplot as plt import numpy as np #Define scale values to keep close to unity mass_scale = 1e30 ...
# # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ Low-level USB transciever gateware -- control request components. """ import unittest import functools import operator from amaranth import Signal, Module, Ela...
# Copyright 2017 The Forseti Security 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 ap...
import save import yande_re import log import phttp import time import datetime class Download: def do_download(self,pic_size: {}, page, max_page, pic_type, path): # 默认'C:/Yandere/' wr = save.Save(path) yande = yande_re.Yande() lg = log.Log() resp = phttp.Http() wr....
# r mean read # a means adding # w means overwrite everything in the file # r+ means modify the file employee_file = open("employee.txt","r") print(employee_file.readable()) print(" ") print(employee_file.read()) print(" ") print(employee_file.readline()) print(" ") print(employee_file.readlines()) print(" ") for em...
import os import sys ## if you got module not found errors, uncomment these. PyCharm IDE does not need it. # add .. and . to path, depending on what cwd was when python process was created, one of these might help find librf sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('.')) #print...
from django import forms from .models import Article, Category choices = Category.objects.all().values_list('name', 'name') choice_list = [] for item in choices: choice_list.append(item) class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('title', 'title_tag', 'image'...
#!/usr/bin/env python3 # coding: utf-8 import math class MaxProbCut: def __init__(self,word_count_path,word_trans_path): self.word_dict = {} # 记录概率,1-gram self.word_dict_count = {} # 记录词频,1-gram self.trans_dict = {} # 记录概率,2-gram self.trans_dict_count = {} # 记录词频,2-gram ...
# -*- coding=utf-8 -*- import os import subprocess import sys import string import csv cloudfront_domain = "dusqglx8g3hsd.cloudfront.net" trailers_cloudfront_domain = 'd14q6vju7s12ir.cloudfront.net' s3_destination_bucket = 'adso-vod-workflow-template-destination-d25pp6byo9pp' PROFILE_STREAMS = ( { 'bit...
""" Functions for converting coordinates """ import utm from pyproj import CRS def utm_crs_from_latlon(lat, lon): """ Determines the UTM CRS from a given lat lon point :param lat: The latitude :type lat: float :param lon: The longitude :type lon: float :return: A coordinate system for the...
txt1 = 'A tale that was not right' txt2 = '이 또한 지나가리라.' print(txt1[24]) print(txt2[-2])
#!/usr/bin/env python # -*- coding: utf-8 -*- # # otra_app56.py # from Tkinter import * def Call(): # Definimos la funcion lab= Label(root, text = 'Usted presiono\nel boton') lab.pack() boton['bg'] = 'blue' # Al presionar queda azul boton['fg'] = 'white' # Si pasamos el Mouse qu...
#!/usr/bin/env python # # Copyright (c) 2007-2008, Corey Goldberg (corey@goldb.org) # # license: GNU LGPL # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of t...
''' inherit ParmEd' Structure class ''' from parmed import Structure as _Structure import parmed as pmd import numpy as np def load_file(*args, **kwd): p_struct = pmd.load_file(*args, **kwd) new_struct = Structure() new_struct.atoms = p_struct.atoms new_struct.residues = p_struct.residues new_stru...
import os, sys, csv import numpy as np data = [] with open("wifiscan_1.csv", "rt") as csvfile: reader = csv.reader(csvfile, delimiter=";") for row in reader: data.append(row[1:-1]) data = np.asarray(data).astype(np.float) print( data.shape ) #print data[0, :] mean = np.mean(data, axis=0) print( "mean=...
import subprocess import os import shutil from subprocess import call, check_output, Popen, PIPE import json from os.path import join as pjoin from micompy.common.tools.tool import Tool class BBmap(Tool): def __init__(self, executable = "bbmap.sh", jni=True , kmer = 13): Tool.__init__(self, name = "BBMap",...
#coding:utf-8 import cv2 as cv import numpy as np def video_demo(): capture = cv.VideoCapture(0) while(True): ret,frame = capture.read() frame = cv.flip(frame,1) cv.imshow('video',frame) c = cv.waitKey(50) if c == 27: break def get_image_info(image): p...
import logging import simpy class Restaurant: def __init__(self, env, id, kitchencount, x, y): self.id = id self.env = env self.name = "RE-%d" % id self.x = x self.y = y self.orderStore = simpy.FilterStore(env) self.kitchen = simpy.Resource(env, kitchencoun...
def solution(n): Fibo = [0, 1] for i in range(2, n + 1): Fibo.append(Fibo[i - 1] + Fibo[i - 2]) return Fibo[n] % 1234567
"""" Soumil Nitin Shah Bachelor in Electronic Engineering Master in Electrical Engineering Master in Computer Engineering Graduate Teaching/Research Assistant Python Developer soushah@my.bridgeport.edu """ import sqlite3 def my_database(): """ :return: Nothing """ # define the connection co...
class MyChatRole: def __init__(self, role_name: str, msg_header: str = None): self.__role_name = role_name self.__msg_header = role_name if msg_header is None else msg_header @property def role_name(self): return self.__role_name @property def msg_header(self): retu...
# keeping bot alive on repl.it https://www.codementor.io/@garethdwyer/building-a-discord-bot-with-python-and-repl-it-miblcwejz from flask import Flask, request from threading import Thread import json app = Flask('') @app.route('/') def home(): return "I'm alive" @app.route('/refresh', methods = ['POST']) def r...
''' Retrieve REST API endpoints for different services ''' from . import credentials def get(service_type, endpoint_type='publicURL'): """ Retrieve the service endpoint URL """ ks = credentials.keystone() return ks.service_catalog.url_for(service_type=service_type, ...
# Generated by Django 3.0.2 on 2020-02-01 14:40 import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('osmcal', '0013_remove_event_created_by'), ] operations = [ migr...
import os import sqlite3 import uuid import config def CreateDatasetExportDatabse(datasetId: str): filename = datasetId + ".sqlite" dbpath = os.path.join(config.ExportDatasetPath, filename) conn = sqlite3.connect(dbpath) cur = conn.cursor() create_table_schema = """CREATE TABLE IF NOT EXISTS DO...
# 1+11+111+1111+11111+...的和 def fun(n): sum = 0 x = 0 for i in range(1, n): x = x*10 +1 sum += x print(sum) fun(6)
import numpy as np def numpy_vstack_2d_default(array1, array2, default_value=np.nan): if len(array1) == 0: return array2 if len(array2) == 0: return array1 if np.ndim(array1) == 1: array1 = np.reshape(array1, (1,len(array1))) if np.ndim(array2) == 1: array2 = np.resh...
import sys import sdl2.ext RESOURCES = sdl2.ext.Resources(__file__, "resources") sdl2.ext.init() window = sdl2.ext.Window("Hello World!", size=(640, 480)) window.show() factory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE) sprite = factory.from_image(RESOURCES.get_path("hello.bmp")) spriterenderer = factory.create_s...
import pymongo from menu import Menu from models.post import Post from models.blog import Blog from database import Database Database.initialize() menu = Menu() menu.run_menu()
# -*- coding: utf-8 -*- try: import pycurl222 from cStringIO import StringIO curl = True except Exception, e: import urllib2 curl = False def request(url): """蜘蛛抓取""" if curl: return _curlRequest(url) else: return _urllibRequest(url) def _curlRequest(url): """curl下...
# dp[i]表示前i个石头先手能不能赢 # 如果i是平方数,显示先手必赢 # 如果dp[i - j*j]必输,那么此时先手也必赢 class Solution: def winnerSquareGame(self, n: int) -> bool: sq, dp = sqrt(n), [False] * (n+1) for i in range(0, n+1): if not dp[i]: for j in range(1, int(sq) + 1): if i + j*j <= n: ...
'''API wrapper class''' # pylint: disable=I0011,C0103 import json import os import pprint import requests class WeatherAPI(object): """docstring for WeatherAPI""" @staticmethod def get_weather(apikey, location): '''Wrapper function for getting weather by zipcode''' # OpenWeatherMap call ...
from __future__ import absolute_import, division, print_function from math import sqrt, log import pygame import random import copy import heapq #Feel free to add extra classes and functions class State: # State constructor to initialize grid, player, parent, current coordinate, and # options def __init__(...
import io import os from tqdm import tqdm class ProgressReportingReader(io.BufferedReader): def __init__(self, file_path, *, tqdm_instance=None): super().__init__(open(file_path, 'rb')) self._filename = os.path.basename(file_path) if tqdm_instance is None: self._owns_tqdm = T...
''' CSCI 677 Homework 2-b) Watershed Segmentor Dixith Reddy Gomari 3098766483 gomari@usc.edu References: Double click function: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_mouse_handling/py_mouse_handling.html ''' import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('img...
class Direction(): North = 0 East = 1 South = 2 West = 3 class Board(): def __init__(self, maxx, maxy, obstacles=list()): self.maxx = maxx self.maxy = maxy self.obstacles = dict() for x,y in obstacles: if x not in self.obstacles: self.obs...
# 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, software # d...
class A: def __init__(self, a): self._x = a self.y = self._x
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2015, Continuum Analytics, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------...
#!/proj/sot/ska3/flight/bin/python ############################################################################################# # # # run_glimmon_trend_data_update.py: update trend data with limits in glimmon database # # ...
import cv2 import numpy as np import matplotlib import matplotlib.pyplot as plt import math import pywt import pywt.data denoised_level = 3 def sgn(num): if(num > 0.0): return 1.0 elif(num == 0.0): return 0.0 else: return -1.0 # Construct Gabor filter def bu...
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from radius_curve import measure_curvature_real from curve_pixels import measure_curvature_pixels from prev_poly import fit_poly, search_around_poly from sliding_window import find_lane_pixels, fit_polynomial from GradientHe...
from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Ie() driver.get("https://pan.baidu.com/") driver.find_element_by_xpath("//*/div[@class='account-title']/a").click() driver.find_element_by_xpath("//*/input[@id='TANGRAM__PSP_4__userName']").clear() driver.find_element_by_xpa...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from paypal.pro.models import PayPalNVP class PayPalNVPAdmin(admin.ModelAdmin): list_display = ('user', 'ipaddress', 'method', 'flag', 'flag_code', 'created_at') list_filter = ('flag', 'cre...
import sched, time import requests import json import random temp = 70 hum = 50 s = sched.scheduler(time.time, time.sleep) print 'Start' def fakeData(data): data += random.randrange(-3,3) def send_info(sc): temp = fakeData(temp) hum = fakeData(hum) payload = {'temp': temp, 'hum': hum} r = requests.post("http...
#region Import Modules from fluid_properties import * from auxiliary_functions import * import numpy as np import pandas as pd import math from scipy import interpolate from pyXSteam.XSteam import XSteam import matplotlib.pyplot as plt import pprint #endregion case = {'material': ['air'], 'environment_conditions': [...
import torch from torch.utils import benchmark from .modules import MSA batch, seqlen, dmodel, h = 2, 9, 512, 8 x = torch.randn(batch, seqlen, dmodel) msa = MSA(dmodel, h) t_cpu = benchmark.Timer( stmt="with torch.no_grad(): msa.forward_einsum(x)", globals={"x": x, "msa": msa} ) print(t_cpu.timeit(100)) msa =...
def re_ordering(text): output = text.split() for x in text.split(): if x[0].isupper(): output.remove(x) output.insert(0, x) return " ".join(output) ''' There is a sentence which has a mistake in it's ordering. The part with a capital letter should be the first word. Plea...
from django.views.generic import TemplateView, FormView from django.core.urlresolvers import reverse from django.conf import settings from kazoo.client import KazooClient from bees.forms import CreateNodeForm, EditNodeForm, DeleteNodeForm ZK_CLIENT = KazooClient(hosts=settings.ZOOKEEPER_HOSTS) ZK_CLIENT.start() class...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from dataclasses import dataclass from string import Template from textwrap import indent DEFAULT_TEMPLATE = """ def make_exe(): dist = default_pyt...
# -*- coding: utf-8 -*- # !/usr/bin/env python """ ------------------------------------------------- File Name: proxy.py Description: 自动从大象代理获得代理IP Author: Dexter Chen Date:2017-09-16 ------------------------------------------------- """ import os import requests import utilities as ut import config def ...
import re import sys import json import codecs from ..feature_extractors import normalizer from ..feature_extractors import tokenizer input_filename = 'comments.json' output_filename = 'comment_text.txt' with codecs.open(input_filename, 'r', encoding='utf-8') as input_file: lines = input_file.readlines() body_co...
from fabric.api import run, task, sudo, settings, env from fabric.tasks import execute from fabric.contrib.console import confirm from fabric.contrib.files import exists from dateutil.parser import parse from appconfig import APPS from appconfig.config import App from appconfig.tasks.deployment import pip_freeze env....
from rest_framework import serializers from photos.models import Photo, Comment from users.serializers import UserSerializer, PhotoShowSerializer class PhotoSerializer(serializers.ModelSerializer): user = PhotoShowSerializer(read_only=True) class Meta: model = Photo fields = ['id', 'image', ...
import numpy as np import tensorflow as tf from sklearn import model_selection from tensorflow.keras.layers import Dense from tensorflow.keras import Sequential from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import EarlyStopping import warnings warnings.filterwarnings('ignore') data = n...
"""secret_messages Class for the Affine Cipher""" import string from ciphers import Cipher class AffineCipher(Cipher): """Class to encrypt/decrypt text with the Affine Cipher Keyword Arguments: Cipher = Top-level class that raises NotImplementedError if run Methods: __init__ encrypt de...
n = int(input()) string = input() curr_pos = sub_len = 0 length = [] temp = 0 for i in range(n): if string[i] == 'x': sub_len += 1 if string[i] != 'x' or i == n - 1: length.append(sub_len) sub_len = 0 # print(string[i], sub_len) print(sum([i-2 for i in length ...
from users import Users, Logs, DB_PATH from users import Interface if __name__ == "__main__": users = Users(db_path=DB_PATH) logs = Logs(db_path=DB_PATH) menu = Interface(users=users, logs=logs) print("\nAll Users:") print("pkey, user_email, pw, register_date, locked_until") for i ...
import os import cfg def calc_dice(test_names, results_dir): for p_name in test_names: # TODO: feature: ori data required to be process truth = str(cfg.seg_dir.joinpath(f'{p_name}_seg.mha')) predict = str(results_dir.joinpath(f'{p_name}_prd_bin.png')) output_xml = str(results_dir....
import logging class Response(object): """The object sent back to the callback Contains methods for calling senders and responders on Espresso """ def __init__(self, robot, msg, match): self.robot = robot self.msg = msg self.match = match def send(self, message, channel=N...
#coding: utf-8 print 'Bem vindo ao sistema de rotatividade de snapshots na aws' print '' print 'Opção 1 - Cadastrar volume para ser deletado' print 'Opção 2 - Listar volumes cadastrados atualmente' option = str(raw_input("Digite qual a opção desejada: 1 ou 2: ")) if option == '1': volumes = open("volumes.txt", "a...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-25 12:05:34 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learning # @Version : $Id$ ''' 文件存储格式如下: id,name,age,phone,job 1,Alex,22,13651054608,IT 2,Egon,23,13304320533,Tearcher 3,nezha,25,1333235322,IT 现在需要对这...
from flask_marshmallow import Marshmallow from .model import Book ma = Marshmallow() def configure(app): ma.init_app(app) class BookSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Book include_relationships = True load_instance = True
import requests import json import datetime class Guild: def __init__(self, playerName: str = None, playeruuid: str = None): self.playerName = playerName self.playeruuid = playeruuid if self.playerName == None and self.playeruuid == None: raise AttributeError('You need to fill i...
listt=[] def countd(a): for m in range(a,0,-1): listt.append(m) return listt b=countd(5) print(b) #2 print and return def printre(lis): for i in range(0,2): print(lis[0]) return lis[1] print(printre([2,5])) #3 First plus length sum=0 def first_len(lis): sum =lis[0...
def esrever(s): return s[:-1][::-1] + s[-1] if s else ''
#import mysql import sqlite3 """This program uses the Table and Query classes to generate the SQL to create the groceries database described in the Facade chapter.""" class Database(): def __init__(self, *args): #self._db = MySQLdb.connect(args[0], args[1], args[2]) self.host=args[0] self.us...
#Sidharth Peri #10/22/20 #Honor Code: i pledge in my honor that I have abided by the Stevens Honor System #A program that opens a text file formats the strings and then writes #the reformatted strings in a new text file def main(): print("This program takes a text file with lower case names and writes them into a ...
from math import sqrt n = int(input()) f = (((1 + sqrt(5)) / 2) ** n - ((1 - sqrt(5)) / 2) ** n) / sqrt(5) print('{:.1f}'.format(f))
class MetaOne(type): def __new__(meta, classname, supers, classdict): # Redefine type method print('In MetaOne.new:', classname) return type.__new__(meta, classname, supers, classdict) def __init__(cls, classname, supers, classdict): print('In MetaOne.init:', cls, classname) def toast(self): print...
""" PRACTICE Test 3, problem 4. Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, their colleagues and Muqing Zheng. October 2015. """ # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE. def main(): """ Calls the TEST functions in this module. """ test_doubler() def test_doubler(...
import unittest from katas.kyu_7.numbers_with_this_digit_inside import \ numbers_with_digit_inside class DigitInsideTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(numbers_with_digit_inside(5, 6), [0, 0, 0]) def test_equal_2(self): self.assertEqual(numbers_with_digi...
import torch import torch.nn as nn import torch.nn.functional as F class Planar(nn.Module): def __init__(self): super(Planar, self).__init__() self.h = nn.Tanh() def forward(self, z, u, w, b): """ Computes the following transformation: z' = z + u h( w^T z + b) ...
from django.contrib import admin from todo.models import StaffProfile admin.site.register(StaffProfile)