text
stringlengths
8
6.05M
# -*- coding: utf-8 -*- from os import path from glob import glob import sys import importlib class Bot(object): def __init__(self): self._cmd = '' self._listeners = [] def add_listener(self, listener): self._listeners.append(listener) def say(self, m): print(m) @prop...
import sys input_string_1 = "test"; input_string_2 = "tTtt"; #we make an assumption, and then try to disprove it is_permutation = True; #we hash the first string, then second string, and compare the frequency of letters in each if (len(input_string_1) != len(input_string_2)): is_permutation = False; else: #h...
def unlimited_arguments(*args): for argument in args: print(argument) unlimited_arguments(1,2,3,4) unlimited_arguments(*[1,2,3,4]) def unlimited_arguments2(*args, **keyword_args): print(keyword_args) for k, argument in keyword_args.items(): print(k, argument) unlimited_arguments(1,2,3,4) ...
from create_model import * from transform import load_weight_16 import numpy as np from keras import optimizers from keras import regularizers from keras import callbacks from keras.utils import to_categorical from keras.preprocessing.image import ImageDataGenerator if __name__ == "__main__": x = np.load("x.npy")...
from rest_framework.views import APIView from .myCreator import create import os from django.http import HttpResponse class ApplicationView(APIView): def get(self, request): params = dict(request.query_params) userId = request.user if type(userId) != 'str': userId = "AnonymousU...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('authentication', '0012_auto_20150716_0156'), ('relationships', '0005_comments'), ] operations = [ migrations.CreateM...
import cv2 import numpy as np import pyautogui import sudoku99 left = 731 top = 120 width = 82 def read_img(image): sudoku = np.zeros([9, 9], dtype=np.int) img_gray = np.array(image.convert('L')) for i in range(1, 10): template = cv2.imread('img/{}.png'.format(i), 0) h, w = template.shape...
# File: tv_shows_fxns.py # Author: Joel Okpara # Date: 3/28/2016 # Section: 04 # E-mail: joelo1@umbc.edu # Description: # This file contains python code that implements lab5 # (a TV show voting system) using functions to: # 1) Get a choice # 2) Find the name of the winner STOP = 0 # getVote() returns a valid choice f...
import win32gui import win32api import os def getwindow(Title="SpotifyMainWindow"): window_id = win32gui.FindWindow(Title, None) return window_id def song_info(): try: song_info = win32gui.GetWindowText(getwindow()) except: pass return song_info def artist(): try: temp = song_info() ...
# Напишите программу, которая реализует reducer для задачи WordCount в Hadoop Streaming. # Sample Input: # cogitare 1 # est 1 # est 1 # est 1 # militate 1 # potentia 1 # Scientia 1 # Vivere 1 # Vivere 1 # Sample Output: # cogitare 1 # est 3 # militate 1 # potentia 1 # Scientia 1 # Vivere ...
from karel.stanfordkarel import * """ File: MidpointKarel.py ---------------------- When you finish writing it, MidpointKarel should leave a beeper on the corner closest to the center of 1st Street (or either of the two central corners if 1st Street has an even number of corners). Karel can put down additional beepe...
import requests import time #多进程 if __name__ == '__main__': count=10 while True: if count<=0: break; response1=requests.get("http://localhost:8080/joke/task_get") task_key=response1.content.decode("utf-8") print(task_key) if task_key=="": count=c...
# -*- test-case-name: mimic.test.test_auth -*- """ Defines get token, impersonation """ from __future__ import absolute_import, division, unicode_literals import json import time import attr from twisted.python.urlpath import URLPath from mimic.canned_responses.auth import ( get_token, get_endpoints, f...
#!/usr/bin/python #coding=utf-8 from ipfunc import * import os re_strong = re.compile(".*strong class=.*") re_strongb = re.compile("strong.*strong") url_1 = 'http://ip.chinaz.com/?IP=' def Get_LocalInfo(): #Get Localhost Infomation LocalInfo = [] f = urllib2.urlopen(url_1).read() for i in re_strong.findall(f):...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 10/02/2018 5:06 PM # @Author : Lee # @File : SST.py # @Software: PyCharm class SST(object): def __init__(self, head=None, count=0): self.head = head self.count = count def size(self): return self.count def is_empty(s...
""" 什么是协程? 又称为微线程、纤程,英文名:Coroutine import asyncio async def main(): print("hello") await asyncio.sleep(1) print("world") asyncio.run(main()) 通过async/await语法进行声明,是编写异步应用的推荐方式 使用asunc修饰要运行的函数,在运行协程函数时,需要await。 可以用run或者creat_task启动微线程 """ import asyncio,time async def say_after(delay,what...
import numpy as np import cv2 # flag for imread 0 is grayscale, 1 is color, -1 is alpha channel #img = cv2.imread('lena.jpg', 1) # create image with numpy zeros method img = np.zeros([512, 512, 3], np.uint8) # draw a line img = cv2.line(img, (0, 0), (255, 255), (147, 96, 44), 10) # 44, 96, 147 img = cv2.arrowedLine...
import math def makeChange(cents): coins = {}; if cents/100 >= 1: coins["dollars"] = math.floor(cents/100); cents = cents % 100 if cents/50 >= 1: coins["half-dollars"] = math.floor(cents/50); cents = cents % 50 if cents/25 >= 1: coins["quarters"] = math.floor(cen...
#!/usr/bin/env python # -*- coding: utf-8 -*- import mysql.connector class Edition(): def __init__(self): self.id=0 self.name="" def all(self): try: conn = mysql.connector.connect(host="localhost",user="root",password="magicpswd", database="magic") cursor = conn.cursor() cursor.execute("""SELECT i...
# Copyright 2022 Pulser Development Team # # 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 i...
# Author: Lizhen Tan import numpy as np import pandas as pd import scipy.stats as stats import matplotlib.pyplot as plt '''required functions for main program''' def test_grades(grade_list): # take a grade_list as input, assign numeric values to the letter grades (i.e. A = 5, # B = 3, C = 1), then fit a line...
def battery_is_ok(temperature, soc, charge_rate): if temperature < 0 or temperature > 45: print('Temperature is out of range!') return False elif soc < 20 or soc > 80: print('State of Charge is out of range!') return False elif charge_rate > 0.8: print('Charge rate is out of range!') retu...
#!/usr/bin/env python # coding: utf-8 import os from . import DatasetDirectoryError def getDatasetDirectory(): DATASET_EXPLORER_ROOT = "DATASET_EXPLORER_ROOT" if DATASET_EXPLORER_ROOT not in os.environ: raise DatasetDirectoryError( f"The environment variable {DATASET_EXPLORER_ROOT} must b...
from os.path import join, exists, isdir from os import environ from .config import CONFIG KEY_VIMRC_PATH = 'vimrc_path' def find_vimrc_auto() -> str: cfgp = CONFIG.get(KEY_VIMRC_PATH, None) if cfgp is not None: return cfgp h = environ.get('HOME', None) if h is None: return None ...
from PIL import Image, ImageDraw, ImageFont import textwrap import os import json import base64 def makememe( text, location ): if len(os.listdir(location)) == 0: return for file in os.listdir(location): imgname = file img = location + "/" + imgname image = Image.open(img) draw = ...
A=int(input("A= ")) B=int(input("B= ")) if(A<B): for i in range(A,B): print(i) i=B-A print("N=",i)
# Generated by Django 3.1.2 on 2020-11-06 14:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Categories', fields=[ ...
import os import logging import fisheye class Settings(object): """docstring for Settings""" APP_ROOT = os.path.dirname(os.path.realpath(__file__)) # Number of allowed threads/process to run in parallel to process videos PROCESSINGS_THREADS_NUM = 3 # # Uploads settings # UPLOAD_FOLDER = os.path.join(...
#coding:gb2312 #创建数值列表和对列表进行一些简单的操作 for numbers in range(1,6):#range(1,6)只包含1,2,3,4,5,没有6 print(numbers) #range创建数字列表: numbers=list(range(1,6))#list()将数字转化成列表 print(numbers) even_numbers=list(range(2,14,2))#range(x,y,z)x,y表示数字范围,z表示步长即数字间的距离 print(even_numbers) #比较下列三种创建列表的方式 #第一种 squares=[] for number in range(1,1...
# Generated by Django 3.0.5 on 2020-04-29 21:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0006_auto_20200429_1345'), ] operations = [ migrations.AlterField( model_name='product', name='description',...
from django.contrib import messages from django.shortcuts import redirect, render from django.contrib.auth.decorators import login_required from .forms import extend_user_form, user_detail_form, todo_entery_form from django.contrib.auth.models import User from .models import enter_todo_items # indexview @login_requi...
from herd import Herd from weapon import Weapon from herd import Herd from dino import Dino class Robot: def __init__(self, name, weapon): self.name = name self.health = 200 self.weapon = weapon def attack(self): health = Dino.health() atk = Weapon.attack_power() ...
#! /usr/bin/python # coding=utf-8 import os import subprocess from scipy import misc from lib import * import argparse parser = argparse.ArgumentParser(description='Compute an exposure-fused image from multiple different exposures') parser.add_argument("source", help="Folder containing all the images to be fused toge...
n = int(input()) print(*[1, 1, n-2] if n % 3 == 0 else [1, 2, n - 3])
# implementation of card game - Memory import simplegui import random turns = 0 # helper function to initialize globals def new_game(): global dock, exposed, state, turns turns = 0 state = 0 cards = range(0,8) * 2 dock = [] for card in cards: dock.append(card) random.shuffle(dock) ...
import webbrowser # Base Classe Video class Video(): def __init__(self, title, duration, producer): self.title = title self.duration = duration self.producer = producer def show__trailer(self): webbrowser.open(self.trailer_youtube_url) #...
import time import math import argparse from typing import Optional, Tuple from functools import partial import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F class BertSelfAttention(nn.Module): def __init__(self, hidden_size, num_attention_heads, attention_probs_...
from app.utils.dotdict import DotDict from app.utils.extract_value import get_base_url_till_given_string import unittest class ExtractValue(unittest.TestCase): def test_get_base_url_till_given_string(self): request = DotDict({"base_url": "http://www.zooreach.com/category/fishes"}) string = 'catego...
from argparse import ArgumentTypeError import sys sys.path.append("..") from utils import connector def get_table(cfg, limit, offset): table = cfg.get('postgres', 'table') data = connector.postgres_to_dataframe(table=table) return data
__author__ = "Narwhale" # #递归 # def fib(n): # """斐波拉契""" # if n == 0: # return 1 # if n == 1: # return 1 # if n == 2: # return 2 # return fib(n-1)+fib(n-2) # # # f = fib(50) # print(f) # # #循环 # def fib(n): # """斐波拉契""" # a,b = 0,1 # while n > 0: # a,b ...
import datetime import io from time import sleep from PIL import Image as Img_pil from django.test import TestCase from project_apps.users.models import CustomUser as User from project_apps.plans.models import Plan, ThumbnailSize from project_apps.images.models import Image from rest_framework.reverse import revers...
n,a,d=map(int,input().split()) x=n*a%d print(int(x))
### IMPORT STATEMENTS ### import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np import pandas as pd import os import time import matplotlib.pyplot as plt import string from models import * from configs import cfg from nltk.translate.bleu_score import sent...
from django.urls import path, include from . import views urlpatterns = [ path('', views.log_and_reg), path('register', views.register), path('login', views.login), path('index', views.index), path('logout', views.logout), path('wall', views.wall), path('post_message', views.post_message),...
import tkinter as tk tela = tk.Tk() tela.geometry('500x250+500+400')
""" One of the most widely used formats for astronomical images is the Flexible Image Transport System. In a FITS file, the image is stored in a numerical array, which we can load into a NumPy array. FITS files also have headers which store metadata about the image. FITS files are a standard format and astronomers ha...
import _judger import hashlib import logging import os import socket import psutil from config import SERVER_LOG_PATH from exception import JudgeClientError # 服务器工具类 # 日志工具类:配置logging基本的设置 # 获得日志对象 logger = logging.getLogger(__name__) #设置服务器的日志路径,用于将日志写到文件中 handler = logging.FileHandler(SERVER_LOG_PATH) #时间+日志级别+日志信...
#!/usr/bin/env python from fabricate import * def input1(): pass # source file def gen(): run('sh','monad3-gen','--','gen') def lst(): run('sh','monad3-run','source','--','list') def output(): lst() array = [] with open('list', 'r') as f: for line in f: line = line.replac...
#!/usr/bin/python import itertools primes = [2, 3, 5, 7, 11, 13, 17] def tupToInt(num): n = 0 for i in num: n *= 10 n += i return n def property(num): num = str(num) for i in range(7): if int(num[i+1:i+4]) % primes[i] != 0: return False return True pans = l...
from django.conf.urls import url from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^$', views.index), # This line has changed! url(r'^books$', views.books,name='books'), url(r'^mining$', views.mining, name='mining'), url(r'^chart...
#-*- coding: utf-8 -*- from lxml import etree import os def get_indentation_level(row, level_indent=4): row = row.replace("\t", " "*level_indent) i = 0 while row[i] == " ": i += 1 return int(i / level_indent) def validate(rows): current_level = 0 for row in rows: level = g...
import csv import representativeValue as rv #representativeValue.pyをrnという名前で読み込む .pyは不要 import sys from operator import itemgetter ##########HEADER確認########## def check_header(fileName): filename = fileName with open(filename) as f: r = csv.reader(f, delimiter=',') rows = [l for l in r] cnt = 0 for row in r...
numbers=[2,3,1,6,4,8,9] numbers.clear() # bu clear o'z nomi bilan listni tozalaydi elementlaridan print(numbers)
import numpy as np import matplotlib.pyplot as plt import math def normal(mu,sigma,x): #normal distribution return 1/(math.pi*2)**0.5/sigma*np.exp(-(x-mu)**2/2/sigma**2) def eval(x): return normal(-4,1,x) + normal(4,1,x) #return 0.3*np.exp(-0.2*x**2)+0.7*np.exp(-0.2*(x-10)**2) def ref(x_star,x): #normal...
import dash_bootstrap_components as dbc from dash import html placeholder = html.Div( [ dbc.Placeholder(color="primary", className="me-1 mt-1 w-100"), dbc.Placeholder(color="secondary", className="me-1 mt-1 w-100"), dbc.Placeholder(color="success", className="me-1 mt-1 w-100"), dbc....
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^home/$', views.index, name="index"), url(r'^order_meal/(?P<meal_id>\d+?)$', views.index, name="order_meal"), ]
""" Test agent. First version of the minecraft agent, which will function in a 2D world (i.e. a slice of the 3D world) and solve a simple bridge problem. Modified from example_plugin found in the original SpockBot repository """ import logging import os import sys # custom plugins. can be placed anywhere that is acce...
import re with open('Scared.txt', mode='r') as word: words = (word.read()) print(words) a = re.findall('the', words) pattern = re.compile('She') print(a) b = pattern.findall(words) print(b) pattern1 = re.compile(r"([a-zA-Z]).([e])") c = pattern1.search(words) print(c) print(c.group(1)) # ...
import json from statistics import mode from operator import itemgetter import pandas as pd from django.shortcuts import render from itertools import groupby from django.views.decorators.csrf import csrf_exempt import requests # Create your views here. @csrf_exempt def index(request): link = "https://www.mo...
from datetime import date from typing import List import uvicorn from fastapi import FastAPI from fastapi import HTTPException from pydantic_aioredis import Model from pydantic_aioredis import RedisConfig from pydantic_aioredis import Store # Create models as you would create pydantic models i.e. using typings clas...
'''graphical user interface''' import gui # --- event handlers --- def greeting(evt): import wx, sys gui.alert('\n'.join([wx.version(), sys.version]), "gui2py hello world!") # --- gui2py designer generated code starts --- with gui.Window(title='gui2py minimal app', resizable=True, height='496px', ...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import io import math from dataclasses import dataclass from pathlib import PurePath from typing import Sequence import chevron from pants.backend.go.u...
from .add import add from .subtract import subtract
import pandas as pd import json # Reading in CSV files with our data and extracting only the columns we need credits = pd.read_csv("credits.csv") credits = credits [['id', 'cast', 'crew']] meta = pd.read_csv("movies_metadata.csv") meta = meta [['id', 'title', 'genres']] keywords = pd.read_csv("keywords.csv") # Our i...
from __future__ import division # floating point division import csv import random import math import numpy as np import matplotlib.pyplot as plt import dataloader as dtl import regressionalgorithms as algs def l2err(prediction,ytest): """ l2 error (i.e., root-mean-squared-error) """ return np.linalg.norm(np...
#!/usr/bin/env python3 import math import numpy as np import matplotlib.pyplot as plt from numpy.random import * import mnist_reader from itertools import * import numba import pickle import sys import argparse class ETA: def __init__(self, _n): self.n = _n self.i = 0 def bump(self): ...
from tkinter import * from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import threading import time import numpy as np from tkinter.messagebox import showinfo VALORES = [] teste = None tempoDeExecucao = 0 # Classe para criação de Threads class minhaThread(threading....
import sys import json import re from flask_cors import CORS from flask import Flask, request, jsonify from flask_restful import Resource, Api from json import dumps bad_words_txt = open('badwords.txt', 'r').read() bad_words_arr = bad_words_txt.splitlines() print(bad_words_arr) class REMOVE_BAD_WORDS(Resource): ...
x, x1, y, y1 = map(int, input().split(' ')) i = x * 60 + x1 f = y * 60 + y1 if (f > i): m = f - i else: m = (24 * 60) - i + f h = m // 60 m = m % 60 if h == 0 and m == 0: h = 24 m = 0 print('O JOGO DUROU {} HORA(S) E {} MINUTO(S)'.format(h, m))
import json from grant.utils.enums import ProposalStatus, CCRStatus import grant.utils.admin as admin from grant.utils import totp_2fa from grant.user.models import admin_user_schema from grant.proposal.models import proposal_schema, db, Proposal from grant.ccr.models import CCR from mock import patch from ..config im...
from .event import Event from .speaker import Speaker from .schedule import Conference, Room from .simpletz import SimpleTZ
from django.db import models # Create your models here. class Topic(models.Model): topic_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.topic_text class Question(models.Model): topic = models.ForeignKey(Topic, on_delet...
# Generated by Django 2.0.4 on 2018-05-13 20:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('music', '0005_remove_music_style'), ] operations = [ migrations.AddField( model_name='music', name='style', ...
import numpy as np import scipy.interpolate as intp from astropy.io import fits from astropy.io import ascii import sys import imageSubs as iS print 'subtracting average radial profile (this may take a while)' #load file names, target list and median psf files = ascii.read('NIRC2_sci_20020_1.txt') fileNames = np.arra...
from migrate import conn_commons class Order: @staticmethod def select_old_coupon(user_ids_str): sql = "select * from t_coupon_user where user_mark in %s" coupon_conn = conn_commons.Commons() return coupon_conn.select_old_data(sql % user_ids_str, None) @staticmethod ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import re from ripozo.resources.fields.common import StringField from ripozo_sqlalchemy import AlchemyManager, ScopedSessionHandler from common.models import engine, Po...
import logging import redis from flask import Flask, g from settings.config import DefaultConfig from settings.config import local as localconfig # Rename for clarity from shared import snippets from routes.authentication import authentication from routes.game import game from routes.generic import frontend from a...
# -*- coding: utf-8 -*- # flake8: noqa from __future__ import unicode_literals from django.db import migrations, models import django_extensions.db.fields.json class Migration(migrations.Migration): dependencies = [ ('webplatformcompat', '0020_populate_references'), ] operations = [ mig...
''' Preprocess data Loading, Standardizing and Filtering the raw data to dimish false positive labels ''' import pandas as pd import glob from .config import config import os import random def load_data(data_dir): ''' data_dir: path to .csv files. Optionall can be a path to a specific .csv file. nsamples...
#!/usr/env/bin/python3 import os newfile=open("list.py","w+") #print (newfile.mode) #print (newfile.name) #print (newfile.softspace) #print (newfile.seek)
from bs4 import BeautifulSoup import requests url = 'http://www.winequality.com' r = requests.get(url) html_doc = r.text print(html_doc) soup = BeautifulSoup(html_doc) print(soup.prtify) print(soup.title) tags = soup.find_all('a') for link in tags: print(link.get('bref')) url1 = 'http://www.analyticsindi...
import logging from jenkins.models import Job, Build, Artifact from jenkins.utils import generate_job_name def import_build_for_job(job_pk, build_number): """ Import a build for a job. """ job = Job.objects.get(pk=job_pk) logging.info("Located job %s\n" % job) client = job.server.get_client(...
""" Health handler module. The `HealthHandler` provides an interface to manipulate a Pokemon's health whilst respecting the various hooks and calls required. The handler is instantiated as a property on a pokemon typeclass, with the pokemon passed as an argument. It looks for the health properties in the character's d...
""" Fluid Logo Incompressible fluid simulation with obstacles and buoyancy. """ from phi.flow import * # from phi.torch.flow import * # from phi.tf.flow import * # from phi.jax.flow import * DOMAIN = dict(x=128, y=128, bounds=Box(x=100, y=100)) OBSTACLE_GEOMETRIES = [Box(x=(15 + x * 7, 15 + (x + 1) * 7), y=(41, 83)) ...
""" roll_dice Roll dice for multiple players. Author: Jack Jiang (z5129432) Version: v01 Date: 28/08/2017 """ from random import seed from os import system from input_players import input_players from roll_dice import roll_dice def play(): player_list = input_players() now_rounds = 1 while Tr...
# This script goes thhrough various useful functions from the os module as well as other useful built-in libraries import os filename = os.path.join(os.environ.get("HOME"), "test.txt") # example filename that we will use for this walkthrough # listing all the files and folders inside the specified directory print(os.l...
import random from model.contact import Contact from model.group import Group import allure def test_add_contact_in_group(app, db, orm, check_ui): with allure.step("If there are no groups create a group"): if len(orm.get_group_list()) == 0: app.group.create(Group(name="Group for adding contacts...
from datetime import datetime, timedelta from django.contrib.gis.geos import Point from django.test import TestCase from elections.models import Election from elections.tests.factories import ( ElectionFactory, ElectionWithStatusFactory, ModerationHistoryFactory, ModerationStatusFactory, related_st...
import pandas as pd import numpy as np from IPython.display import display def display_all(df): with pd.option_context("display.max_rows", 1000, "display.max_columns", 1000, "display.max_colwidth", 1000): display(df) def add_datepart(df, fldname, drop=True): """ The add_datepart...
# Generated by Django 2.1.5 on 2019-01-26 21:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Models', '0001_initial'), ] operations = [ migrations.AlterField( model_name='visit', name='date', field...
declare @date_from datetime declare @date_to datetime declare @report_type smallint = 0 declare @firm_id int = null declare @company_id int = null declare @partner_id int = null declare @region_id int = nul
import itertools from nltk.corpus import wordnet #import enchant import anagrind import cfg # src file with globals ############parsing#################### def parse_clue(fullclue): cluewords = fullclue.split() for wd in cluewords: if(cfg.charade_dict.has_key(wd)): print(wd, " could indica...
class ListNode: def __init__(self, x): self.val = x self.next = None def reorder(head): l={} if head == None: return None i=0 while True: l[i] = head i+=1 head=head.next if head == None: break n=i-1 if n == 0: r...
import boto3 import json import os import sys import time from datetime import datetime import decimal import uuid class Pekl(object): def __init__(self, bucket_name, region_name=None): self.bucket_name = bucket_name if region_name is not None: self.region = region_name else: ...
from collections import Counter from sklearn.base import BaseEstimator import numpy as np class KNN(BaseEstimator): def __init__(self, K): self.data = [] self.K = K def fit(self, data, ids): self.data.extend(zip(data, ids)) def predict(self, predData): result = [] ...
import sys import os sys.path.append("..") from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QMainWindow , QApplication,QWidget, QMessageBox os.system(r'pyuic5 -o uiclass.py ui\login.ui') from uiclass import Ui_MainWindow from PyQt5.QtCore import pyqtSlot import db class Mywindow(QMainWindow,U...
from django.http import Http404, HttpResponseRedirect, JsonResponse from django.shortcuts import render, get_object_or_404 from django.urls import reverse from .models import Question, Choice # get questions def index(request): context = { 'questions': Question.objects.order_by('-pub_date')[:5] } ...
""" ゼロから学ぶスパイキングニューラルネットワーク - Spiking Neural Networks from Scratch Copyright (c) 2020 HiroshiARAKI. All Rights Reserved. """ import numpy as np import matplotlib.pyplot as plt class Izhikevich: def __init__(self, a, b, c, d): """ Izhikevich neuron model :param a: uのスケーリング係数 :para...
#!bin/python3 import sys """ Execute Query of form (1 x y) or (2 x y) SeqList , Querytype 1 or 2, x_val , y_val, lastAns,n SeqList - Sequence nxn on which the Query has to be run Query - Query either 1 or 2 based on which index has to be calculated x_val - x value part of the query e....
for batch in range(649): print '/home/mattmann/data/exp5/image_catalog/deploy/data/archive/chunks/' + str(batch) + '/filelist_chunk_' + str(batch) + '.txt'