text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- """ Created on Fri Jun 1 18:44:29 2018 @author: Micha """ import numpy as np class tictacToe: def __init__(self,alt_agent): self.board=np.zeros((3,3)) #-1 Alt Agent, 0 empty, 1 Agent self.lastReward = 0 self.gameOver = False self.terminal = False sel...
import math, copy, time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class GlobalAttention(nn.Module): def __init__(self, dim, attn_type="dot"): super(GlobalAttention, self).__init__() self.dim = dim self.attn_type = attn_type assert (self.att...
#!/usr/bin/env python from mininet.topo import Topo from mininet.net import Mininet from mininet.link import TCLink from mininet.log import setLogLevel from mininet.cli import CLI from mininet.clean import cleanup from helper.util import print_error, print_warning, print_success from helper.util import get_git_revisi...
import argparse import json import logging from pathlib import Path from transformers.tokenization_bert import BertTokenizer from farm.data_handler.data_silo import StreamingDataSilo, DataSilo from farm.data_handler.processor import BertStyleLMProcessor from farm.modeling.adaptive_model import AdaptiveModel from farm...
import yaml import numpy as np from scipy.linalg import block_diag from scipy.linalg import sqrtm from scipy.linalg import inv from scipy.stats.distributions import chi2 import math class ParametersClass: # ----------- Switches (options) --------------- SWITCH_REDUCE_TESTING = None SWITCH_VIRT_UPDATE_Z =...
import requests import re url = "https://study-ccna.com/classes-of-ip-addresses/" collected_data = requests.get(url) txt_data = collected_data.text #print(txt_data) ip = r'[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}' ip_address = re.findall(ip,txt_data) ip_address =list(set(ip_address)) i = 1 for each in ip_addr...
### coderbyte ''' Challenge Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u...
import sys import math import re line1 = [] line2 = [] line3 = [] line4 = [] line5 = [] count = 1 Abc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] charmap = {} line = '' # Auto-generated code below aims at helping you pars...
import json import sys sys.dont_write_bytecode = True import numpy as np import datetime import random import math import core def run(debug): base = "BTC" base = "ETH" #base = "LTC" quote = "USDT" historymins = 60*24*30*2 #60*24*30*4 interval = 60 dtend = datetime.datetime.strptime('201...
import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates # http://www.rcc-acis.org/docs_webservices.html # weather station IDs: # Rogers Farm #1: 2001 # LINCOLN AIRPORT: 14939 siteList = ['2001','14939'] startDate = '2019-01-01' endDate = '2019-12-31' def weatherdf (siteList,startD...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import math data=pd.read_csv('lda_data.csv') X_train,X_test,Y_train,Y_test=train_test_split(data,data['Y'],test_size=0.35,random_state=0) print(X_train.shape) print(Y_train.sh...
#!/usr/bin/dev/ python3 """ This Module contains the merge_sort algorithm for lists. """ __author__ = "Nicholas Cook" __email__ = "nick.james.cook@gmail.com" __status__ = "Prototype" def merge_sort(list, base_list = True): """ return sorted ascending list Call check_element_types, check list length, if length ...
#!/usr/bin/env python #coding:utf-8 import os from app import app from flask import Flask, request, redirect, url_for, render_template, abort, session, escape, send_from_directory, flash from werkzeug import secure_filename import subprocess import thread import traceback import sys reload(sys) sys.setdefaultencodin...
def definePlayer(player, id): # Pseudo-definitions opponent_history = [] history = [] score = [] opponent_score = [] getting_team_name = True #if statement from Prisoner's Dilemma Code if player != id: return 'INVALID SELECTION' #========================================...
# from tensorflow.keras.datasets.fashion_mnist from tensorflow.examples.tutorials.mnist import input_data import warnings import tensorflow as tf warnings.filterwarnings('ignore') class LeNetRaw: def __init__(self): pass def weights_init(self, shape): """ shape size: [height, width, n...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# Generated by Django 3.1 on 2020-09-13 02:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('partisan', '0001_initial'), ] operations = [ migrations.AddField( model_name='tweet', name='created_at', f...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=undefined-variable # Crazy hack, because of appengine. import os import sys def _fix_sys_path_for_appengine(pretest_filename): infra_b...
from django.contrib import admin from .models import Bond admin.site.register(Bond) admin.site.site_url = "/bonds"
#!/usr/bin/env python from __future__ import print_function import argparse import subprocess __author__ = "Begon Jean-Michel <jm.begon@gmail.com>" __copyright__ = "3-clause BSD License" __LH__ = "localhost" # TODO do something more portable __CT_FOLDER__ = "~/clustertools_data/" if __name__ == '__main__': ...
# This is a solution to https://open.kattis.com/problems/blokovi # Given N blocks with a certain mass and length=2 # Find the largest horizontal distance we can reach by stacking them # NOTICE: We will be stacking them with the largest block on top # If we use the top block to rebalance to the left, we can have a # sm...
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ # 计数排序 colors = [0, 0, 0] for i in range(len(nums)): assert 0 <= nums[i] <= 2 colors[nu...
from django.contrib.auth import views as auth_views from django.contrib.auth.models import User from django.urls import resolve, reverse from django.test import TestCase class PasswordChangeIntoAccountTests(TestCase): def setUp(self): self.user = User.objects.create_user( username='to...
import pygame import constants class Tile: def __init__(self, y, x, width, height, status): self.y = y self.x = x self.width = width self.height = height self.font = pygame.font.SysFont('Arial', 25) self.status = status self.color = Tile.define_color_by_stat...
import socket import sys import threading import os import re import settings #make object socket def file_exists(file_route): if not os.path.exists(file_route): print("File tidak ditemukan") return False return True def specify_receiver(): return input("Masukkan username tujuan (ketikkan ...
# coding=utf-8 from __future__ import absolute_import __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The bioprint Project - Released under terms of the AGPLv3 License" import unittest import os imp...
from turtle import Turtle class Score(Turtle): def __init__(self): super().__init__() self.color('white') self.hideturtle() self.up() self.goto(0, 260) self.l_point = 0 self.r_point = 0 self.print_score() def point_to_l_player(self): sel...
from os import system, name from time import sleep from Enlistment import Enlistment from Admin import Admin from Student import Student from User import User from Class import Class def clear(): if name == 'nt': # windows _ = system('cls') elif name == 'posix': # mac and linux _ = system('...
from sklearn import cluster, datasets from matplotlib import pyplot import numpy as np k = 5 iris = datasets.load_iris() X_iris = iris.data # X_iris = np.array([98, 80 , 78, 10, 5, 20, 46, 55, 60]) y_iris = iris.target # print(X_iris) k_means = cluster.KMeans(n_clusters=k) k_means.fit(X_iris) labels = k_means.la...
#------------------------------------------------------------------------------- # Name: Tannin # Purpose: To store hashes encrypted with Tea.lock in a disintegrated fashion so as to decrease malicious accessibility of stored hashes while maintaining ease of use. # # Author: Jordan Gloor # # Creat...
from fastapi import APIRouter, HTTPException import pymongo from config.db import db from models.user import User router = APIRouter() @router.post("/login") def login_handler(user: User): user = dict(user) try: credentials = db.user.find_one({"username": user["username"]}) if not credentia...
from django.urls import path from .views import * urlpatterns = [ path('resume/',ResumeView.as_view()), path('personalinfo/<int:resume_id>/',PersonalinfoView.as_view(),name='personalinfo'), path('education/<int:resume_id>/',EducationView.as_view(),name='education'), path('experience/<int:resume_id>/',Exper...
# 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...
# Generated by Django 2.1.5 on 2019-09-20 09:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0009_auto_20190606_1403'), ('designs', '0005_auto_20190920_1601'), ] operations = [ mig...
# coding=utf-8 """Dibujando 2 texturas en un mismo Fragment Shader""" import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import grafica.transformations as tr import grafica.basic_shapes a...
import chainer class MonotonicLinear(chainer.Chain): """Linear layer with a constraint: weight > 0""" def __init__(self, monotone_input, marginal_input, monotone_output, marginal_output): super().__init__() with self.init_scope(): weight_initializer = chainer.initializers.LeCunNor...
# -*- -*- coding: utf-8 -*- -*- -*- # @Author : Gaopangpang # @Project Name : Lagou # @File : __init__.py # @Time : 2021/3/26 9:56 # @Email : 719453296@qq.com # -*- -*- -*- -*- -*- -*- -*- -*- -*-
import sys sys.stdin = open('../input.txt', 'r') N = int(input()) time_list = [tuple(map(int, input().split())) for _ in range(N)] time_list = sorted(time_list, key=lambda x: (x[1], x[0])) cnt = 1 start_time, end_time = time_list[0] for next_start_time, next_end_time in time_list[1:]: if next_start_time >= end_ti...
import requests from datetime import datetime from MyHTMLParser import MyHTMLParser import feedparser # appropriately set these url WEB_HOOK_URL_CS_IT = "" WEB_HOOK_URL_CS_LG = "" WEB_HOOK_URL_DIS_NN = "" WEB_HOOK_URL_STAT_MECH = "" WEB_HOOK_URL_STAT_ML = "" WEB_HOOK_URL_MATH_PR = "" HOOK_DICTIONARY = { "cs.IT": ...
import numpy as np from random import randint from gym.envs.mujoco import HalfCheetahEnv, InvertedPendulumEnv, ReacherEnv from gym.spaces import Dict from copy import deepcopy import rlkit.torch.pytorch_util as ptu from rlkit.torch.gen_exp_traj_algorithm import ExpertTrajGeneratorAlgorithm from rlkit.core import log...
from unittest import TestCase from celery.tests.case import MagicMock from mock import Mock, patch, PropertyMock from datawinners.accountmanagement.mobile_number_validater import MobileNumberValidater, validation_message_dict from datawinners.accountmanagement.models import Organization from mangrove.datastore.databa...
""" This script serves as the API layer between backend WOLFGAME class and the clients, which I assume will be cellphone """ from flask import Flask from flask import render_template, request, session, redirect, jsonify from flask_cors import CORS import wolf import uuid app = Flask(__name__, template_folder='templat...
# Copyright(c) 2016, Oracle and/or its affiliates. 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 sqlite3 import foursquare client = foursquare.Foursquare( client_id='JZ0P123UOI1WX2UA5GBKJ5R15EG5SXPJPQI43QBW12IX1BBT', client_secret='PFPZXOCWBJZULOP4KNPLX2USVTL34PPI1EVH15SIIC4QSZQQ' ) # returns a list of triple tuples with the following format: # (name, latitude, longitude) def get_venue_info(): db ...
import cv2 import numpy as np # original image # -1 loads as-is so if it will be 3 or 4 channel as the original def rotate(frame , i): (h,w) = frame.shape[:2] c = (w/2,h/2) mat = cv2.getRotationMatrix2D(c,i,1) dst = cv2.warpAffine(frame,mat,(w,h)) return dst pos = cv2.imread("pos.jpg") neg = cv2.imread("neg.jpg"...
import pytest from selenium import webdriver from PageObjects.page_DealApproval import PageDealApproval from TestDatas.common_datas import CommonDatas as cd from PageObjects.page_login import PageLogin from PageObjects.page_index import PageIndex ''' Deal Approval ''' driver = None @pytest.fixture(scope='class') d...
from torch import nn import torch class LabelSmoothSoftmaxCE(nn.Module): def __init__(self, lb_pos=0.9, lb_neg=0.005, reduction='mean', lb_ignore=255, ): super(LabelSmoothSoftmaxCE, self).__init__() se...
import requests import datetime class BotHandler: def __init__(self, token): self.token = token self.api_url = "https://api.telegram.org/bot{}/".format(token) self.proxies = { 'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050' } def get_updates(self, offset=None, timeout=60): ...
#%% LOAD import os from scipy.io import loadmat, savemat import matplotlib.pyplot as plt import numpy as np #%% 2.) Cos os.chdir(r"D:\thesis-scripts\Neural networks\ResNet50\Experiment images\Conv big\l1") l1 = os.listdir() os.chdir(r"D:\thesis-scripts\Neural networks\ResNet50\Experiment images\Conv big\l2") l2 = os...
import itertools import heapq amino_mass = [57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137, 147, 156, 163, 186] class Peptide: def __init__(self, name, mass, score): self.name = name self.mass = mass self.score = score def substrings(iterable): n = len(iterable) ...
__author__ = 'kayzhao' __METADATA__ = { "src_name": 'MeSH', "src_url": 'https://www.nlm.nih.gov/mesh/', "version": "2017", "field": "mesh", "license": "", "license_url": "" } from config import * # data directory data/mesh DATA_DIR_MESH = os.path.join(DATA_DIR, "mesh") # downloaded from: htt...
# A. match_ends # Given a list of strings, return the count of the number of # strings where the string length is 2 or more and the first # and last chars of the string are the same. # Note: python does not have a ++ operator, but += works. def match_ends(*words): counter = 0 new_words = [list(i) for i in wor...
import export_elements import pyodbc import sys from parameters import SERVER from parameters import db from parameters import driver from parameters import Original_url from parameters import table def get_data(): # output: list of (repitition of the elements,HTML elements from table) try: ...
def repeatedString(s, n): a = set(s) le = len(a) if le == 1 and 'a' in a: return n repeated_num = n // len(s) rem_letters = n % len(s) return ((s.count('a' )* repeated_num)+ s[:rem_letters].count('a'))
from numbers_processor import NumbersProcessor from entity import Entity from nltk.corpus import stopwords class TextProcessing: names_and_entities_dict = {} # name : (how many docs, how many times in corpus, ) def __init__(self): self.stop_words = {} my_stopwords = stopwords.words('english'...
import graficas def start(update, context): update.message.reply_text("Saludos, Estrellita!") saludo = "saludo.txt" f = open(saludo, encoding='utf8').read() update.message.reply_text(f) def stars(update, context): graficas.allstars() chatid = update.message.chat.id try: ...
import numpy as np class NaiveBayes: ''' Naive Bayes classifier for music lyrics. Given a set of lyrics, learn to classify which genre a song corresponds to. We make the assumption that all genres share the same prior distribution. ''' def __init__(self, data, genres): self.data = data ...
import shutil, os from file_utils import files_with_ext, create_dir import sys from random import shuffle xmls = files_with_ext(sys.argv[1],'.xml') imagesPath = sys.argv[2] #print(xmls[0]) xmls = [xml.split('/')[-1].split('.xml')[0] for xml in xmls] xmls = [xml for xml in xmls if os.path.exists(os.path.join(imagesP...
#循环 for for循环语法: # for item in 某个数据类型:(数据类型包含:字符串 列表 元组 字典 集合等) #代码块 #in? 成员运算符 in # for 循环的循环次数 由数据的元素个数决定 # s = 'hello' # l =[1,2,3] # d ={"age":18,"name":"哈哈"} #字典类型的数据 是遍历访问key # for item in s: #for循环遍历s里面的元素 然后赋值给item # print("hhh") # for a in s: # print(a) #题目 #请利用for循环,完成列表里面的所有数据的相...
from abc import ABCMeta, abstractmethod class Animal(metaclass = ABCMeta): @abstractmethod def som(self): pass class Cachorro(Animal): def som(self): print('au au au') class Gato(Animal): def som(self): print('miau miau') class Factory(object): def produzir_som(self, obje...
""" This module provides methods for checking webpage type. @ author: Ziming Sheng @ date: 2019-07-25 """ import collections import re from urllib import parse from lxml import etree from lxml.html import clean, defs import numpy import pyximport pyximport.install(pyimport=True) from cyGaussian import ...
from django.conf.urls import url from tickets.views import ( tickets_new_bug, tickets_new_feature, tickets_view_one, tickets_view_all, tickets_edit, tickets_delete, upvote_add, upvote_remove, admin_ticket_status) urlpatterns = [ url(r"^$", tickets_view_all, name="tickets_view_all"), url(r...
#!/usr/bin/python #coding=utf-8 import os import shutil import sys, getopt import platform if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["help","input=","output="]) except getopt.GetoptError: print "usage: %s -i <input path> -o <output path>"%(sys.argv[0]) sys...
__author__ = 'kmanda1' import numpy as np import predictorGenerator as helper import pandas as pd def compute_portvals(start_date, end_date, orders_file, start_val): """Compute daily portfolio value given a sequence of orders in a CSV file. File contains - list orders Load historical data Execute th...
# Filename: backup_ver1.py import os import time # 1. The files and directories to be backed up are specified in a list. source = ['C:\\Users\\Hugo\\Pictures', 'G:\\kankan'] # 2. The backup must be stored in a main backup directory targetDir = 'E:\\Backup' # 3. The files are backed up into a zip file. #...
import json def labels(repos=None, labels=None): if not repos: repos = json.load('agile/labels.json') if not labels: labels = json.load('agile/labels.json') # loop through repos and get all labels for repo in repos: pass
"""Модуль настроек проекта.""" import os from dotenv import find_dotenv, load_dotenv load_dotenv(find_dotenv()) class Config: APP_NAME = os.getenv('APP_NAME', 'Junior') DEBUG = os.getenv('DEBUG', False) CSRF_ENABLED = os.getenv('CSRF_ENABLED', True) WTF_CSRF_SECRET_KEY = os.getenv('WTF_CSRF_SECRET_...
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # 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 # ...
import random continue_playing = 'y' guess = input('Guess a number from 1 through 10: ') while continue_playing == 'y': random_number = random.randint(1, 10) while int(guess) != random_number: guess = input('Guess a number from 1 through 10: ') continue_playing = input('You guessed right! Want to continu...
#https://code-maven.com/list-comprehension-vs-generator-expression """ A Generator Expression is doing basically the same thing as a List Comprehension does, but the GE does it lazily. The difference is quite similar to the difference between range and xrange. A List Comprehension, just like the plain range function,...
# -*- coding: utf-8 -*- import scrapy from scrapy.selector import Selector from scrapy_selenium import SeleniumRequest from selenium.webdriver.common.keys import Keys class ExampleSpider(scrapy.Spider): name = 'example' def start_requests(self): yield SeleniumRequest( url = 'https://www.du...
#!/usr/bin/env python3 """ This module provides a class that stores the configuration of the overall build. """ from collections import OrderedDict from pathlib import Path from typing import Dict, List from dbd.component_config import ComponentConfig class Configuration: """ A class that holds information ...
# coding: utf-8 import hashlib from django.shortcuts import render, render_to_response from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import User, auth from django.views.decorators.csrf import csrf_exempt from models import DevUser from token import get_token from tasks impor...
""" help calculating frequency of a signal """ import numpy as np import traceback class Signal: """ an advanced signal library """ def __init__(self, values, sampling_rate): """ :param values: values of the signal """ self.values = values self.sampling_rate = ...
# remove all leading zeros' from an IP address import re ip_pattern = r'(\d{1,3}.){3}\d{1,3}' ip_list = ['002.1.1.111','01,01,01,011','090,0,0,1','999,,001,100'] for ip in ip_list: re_result = re.match(ip_pattern,ip) if re_result: result = re_result.group() for _ in range(2): if re...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('flowstands', '0005_flowstand_customer'), ] operations = [ migrations.AddField( ...
"""Functions for registering OpenAPI specs with a Connexion app instance.""" from json import load import logging import os from shutil import copyfile from typing import (List, Dict) from connexion import App from yaml import safe_dump from pro_tes.config.config_parser import get_conf # Get logger instance logger...
import os import json path = 'item' config = {} for fn in os.listdir(path): if os.path.isfile(os.path.join(path, fn)): if fn[-5:] == '.json': #print(fn) with open(os.path.join(path, fn), 'r') as fp: obj = json.load(fp) obj['asset'] = [] config[...
from measure import measure from measurehills import measure_hills from cavegen import generateGrid def generate_data(N, settings): results = [] r, n, T, M = settings for i in range(N): results.append(measure(generateGrid(r, n, T, M))) return results def simulate_on_r(N, rvals, nTM): res...
import os import pathlib import numpy as np import tensorflow.compat.v1 as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file def get_single_col_by_input_type(input_type, column_definition): l = [tup[0] for tup in column_definition if tup[2] == input_type] if len(l) != ...
from database import db from models.profession import Profession class Vacancy(db.Model): id = db.Column(db.Integer, primary_key=True) profession = db.relationship("Profession", uselist=False) number = db.Column(db.Integer) section_id = db.Column(db.Integer, db.ForeignKey('section.id'), nullabl...
#-*- coding : utf-8 -*- class Conversion( object ): def __init__(self): pass def stringToBytes(self,str): if str is not None: return bytes(str,encoding="utf8") def bytesToString(self,byt): if byt is not None: return str(byt,encoding="utf8")...
class Settings: """A class to store all settings for the game""" def __init__(self): """Initialize the game's settings""" # Screen Settings self.screen_width= 1200 self.screen_height= 800 self.bg_color= (230,230,230) #Ship settings self.ship_speed=1.5 ...
class Node: def __init__(self, val): self.val = val self.next = None node1 = Node(1) node2 = Node(2) node3 = Node(3) class LinkedList: def __init__(self): self.head = None def printVal(self): currentNode = self.head while currentNode: print(curren...
from .OmokBoard import * from .BoardViewer import * import threading class Omok: size = 0 length = 0 omokBoard = None boardViewer = None def __init__(self, length = 15, size = 40): self.size = size self.length = length self.initOmokBoard() if size != -...
import torch import re from vncorenlp import VnCoreNLP from transformers import AutoModel, AutoTokenizer import pandas as pd data = pd.read_csv("logvideo_20201013.csv") rdrsegmenter = VnCoreNLP("./vncorenlp/VnCoreNLP-1.1.1.jar", annotators="wseg", max_heap_size='-Xmx500m') phobert = AutoModel.from_pretrained("vina...
import pickle class KNN_regression: def __init__(self): self.knn=pickle.load(open('model/knn.pickle','rb')) self.scale=pickle.load(open('model/scaler.pickle','rb')) def predict(self,x): t2=self.scale.transform(x.reshape((1,-1))) prediction=self.knn.predict(t2)[0] return prediction
arr = [i for i in input().split()] arr[0] = int(arr[0]) arr[2] = int(arr[2]) def summ(a, b): return a + b def mul(a, b): return a * b def div(a, b): if b == 0: print("Divide by zero!!") return -1 else: return a / b def subtract(a, b): return a - b operations = { ...
#!/usr/bin/python2.4 # Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0.txt # # Unless required by applicable law or ...
#Heather Stafford #5/21/18 #quiz6.py file = open('engmix.txt') """ #Program #1 letter1 = input('Enter a letter: ') for line in file: if line.count(letter1) >= 4: print(line.strip()) #Program #2 word = '' for line in file: if len(line) >= 9: if line[0] == line[4] and line[0] == line[8]: ...
from django.shortcuts import render from .articles import getArticles def home(request): articles = [getHtml(a) for a in getArticles(10)] context = { 'title' : 'HOME', 'articles' : articles } return render(request, 'interest_site/home.html', context) def about(request): context = ...
DEBUG = True def app (env, start_response): start_response ("200 OK", [("Content-Type", "text/plain")]) return ['pong']
from xml.dom import NamespaceErr from lxml import etree from datetime import datetime from dojo.models import Finding def truncate_str(value: str, maxlen: int): if len(value) > maxlen: return value[:maxlen - 12] + " (truncated)" return value # This parser is written for Veracode Detailed XML reports...
import math n,w,h = map(int, input().split()) limit = int(math.sqrt((w**2)+(h**2))) for i in range(n): print("DA") if(limit >= int(input())) else print("NE")
from .models import Empresa from rest_framework import serializers class EmpresaSerializer(serializers.ModelSerializer): class Meta: model = Empresa fields = ('id', 'nombre', 'id_externo', 'nombre_corto', 'color')
from create_flask_api.project import ProjectSpecs from .mixins import FeatureMixin from create_flask_api.assets.file_paths.heroku_paths import heroku_paths from create_flask_api.assets.questions.heroku_questions import heroku_questions from create_flask_api.assets.corrections.heroku_fix import heroku_fix class Heroku...
"This is for study purpose" defaultdict >> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) >>> for k, v in s: ... d[k].append(v) ... >>> d.items() [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] >> s = 'mississippi' >>> d = defaultdict(int) >>> for k in s:...
import unittest # 定义加法函数 def add(x, y): return x + y class Test1(unittest.TestCase): def test_func1(self): # 应用:多用于判断是否相等 # 语法:assertEqual(预期结果, 实际结果) # 注意:断言异常类型 AssertionError result = add(13, 14) self.assertEqual(27, result) if __name__ == '__main__': unitte...
# coding=utf-8 # coding: utf-8 import random import codecs from tkinter import * import winsound import time # klasa Nagroda (z niej dziedziczone będą treści nagórd i wartości, które one przyjmują) class Nagroda: # ładowanie bazy pytań o nazwie pytania.txt file_name = "pytania.txt" przeszkoda_1 = [] ...
from sqlalchemy.sql import func from config import db class Dojo(db.Model): __tablename__ = "dojos" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(45)) city = db.Column(db.String(45)) state = db.Column(db.String(45)) created_on = db.Column(db.DateTime, server_default=f...