text stringlengths 8 6.05M |
|---|
"""
Week 5, Day 3: Edit Distance
Given two words word1 and word2, find the minimum number of operations required to convert
word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "... |
#-*- encoding:utf-8 -*-
from hello import AwardGrade,db
db.session.add(AwardGrade(AGname='三等奖'))
db.session.add(AwardGrade(AGname='二等奖'))
db.session.add(AwardGrade(AGname='一等奖'))
db.session.add(AwardGrade(AGname='特等奖'))
db.session.commit()
|
# following PEP 386
__version__ = "2.1.1"
|
class Tweet(object):
__author = ""
__text = ""
__location = ""
#__longitude = ""
#__latitude = ""
__creation = ""
#def __init__(self, author, text, longitude, latitude):
def __init__(self, author, text, location, creation):
self.__author = author
self.__text =... |
import node_preprocess
import networkx as nx
import csv
import matplotlib.pyplot as plt
def getRightCore():
result = {}
with open ("./CoreNumbers") as f:
csv_file = csv.reader(f, delimiter=':')
for row in csv_file:
result[row[0]] = row[1]
return result
def getRightPeak():
... |
kor_score = [49, 79, 20, 100, 80]
math_score = [43, 59, 85, 30 ,90]
eng_score = [49, 79, 48, 60, 100]
midterm_score = [kor_score, math_score, eng_score]
student_scroe = [0,0,0,0,0]
i =0
for subjust in midterm_score:
for score in subjust:
print(score)
student_scroe[i] += score
i += 1
pri... |
from django.db import models
import random
from django import forms
class Wallet():
def __init__(self, request):
self.total_gold = 0
self.request = request
self.activites = []
if "total_gold" in request.session:
self.total_gold = request.session['total_gold']
i... |
from time import time
import kenlm
import sys
"""
usage: python language_model_test.py ../../lib/kenlm/models/ngram_lm.trie
"""
def main():
if len(sys.argv) < 2:
print("Usage: give path parameter")
else:
_, model_path = sys.argv
model = kenlm.Model(model_path)
input = ''
... |
import fourier
import pcf
import ioutils as io
from mathutils import *
import setup
#============================================================================
LOGS_DIR = "../fig10b-bnot-step-jitter/"
TARGET_DIR = "../targets/"
FILE_EXT = ".pdf"
#====================================================================... |
class Decoder:
def __init__(self):
self.dictionary= {
'01':'A', '1000':'B', '1010':'C', '100':'D', '0':'E',
'0010':'F', '110':'G', '0000':'H', '00':'I', '0111':'J',
'101':'K', '0100':'L', '11':'M', '10':'N', '111':'O',
'0110':'P', '1101':'Q', '010':'R', '000':... |
produtos = ('Leite', 3,
'Coca', 4,
'Calabresa', 15)
print(f'{"LISTAGEM DE PREÇO":^40}')
for n in range(0, len(produtos)):
if n % 2 == 0:
print(f'{produtos[n]:.<30}', end='R$')
else:
print(f'{produtos[n]:>6.2f}') |
def soma_hipotenusas(n):
print ("As hipotenusas são")
soma_hipotenusas = 0
a = 1
b = 1
while n > 1:
while b < n:
while n**2 != a**2 + b**2 and a < n:
a = a + 1
if n**2 == a**2 + b**2:
soma_hipotenusas = soma_hipotenusas + n ... |
def capacity_scaling(
G,
demand: str = "demand",
capacity: str = "capacity",
weight: str = "weight",
heap=...,
): ...
|
#!/usr/local/bin/python
import datetime
import json
import os
import sys
import traceback
import twitter
import urllib2
import xml.dom.minidom
import Config
import File
import FixText
import Job
import Secret
JSON_FIELDS = {
'title': '',
'titleList': [],
'listeners': '0',
'unique': '0',
'bitrate': '128'}
... |
from django.db import models
class CategoryManager(models.Manager):
"""
Adds number of items and number of subcategories to category objects
"""
def get_queryset(self):
return super().get_queryset().annotate(number_of_items=models.Count('items')).annotate(
number_of_subcategories=... |
#!/usr/bin/env python
#-*-coding: utf-8 -*-
"""
@version: 0.1
@author:linyl
@file: html_parser.py
@time: 2018/9/20 21:55
"""
import re
import urlparse
from bs4 import BeautifulSoup
class HtmlParser(object):
def parse(self, page_url, html_cont):
if page_url is None or html_cont is None:
return... |
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
a = torch.ones(1, 2, 3, 3).to(device)
print(a)
a = a + torch.zeros(a.size()).data.normal_(0, 0.1).to(device)
print(a.size(), a) |
# Django
from django.db import models
# Local Django
from appointments.variables import APPOINTMENT_STATUSES, PENDING
class Appointment(models.Model):
status = models.PositiveSmallIntegerField(
verbose_name='Status', choices=APPOINTMENT_STATUSES, default=PENDING
)
subject = models.TextField(verbo... |
# 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 os
import threading
import multiprocessing
from helper import *
from network import NetworkWrapper
from worker import Worker
from config import *
from time import sleep, time
load_model = False
if load_model == True:
FLAGS.experience_buffer_maxlen = 100
FLAGS.episodes = 600
#Reset the graph
tf.reset_... |
#!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies simple rules when using an explicit build target of 'all'.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32'... |
from rest_framework import serializers
from django.db.models import Q
from . import models
from artuium_server.users import serializers as users_serializers
from artuium_server.artwork import serializers as artwork_serializers
from artuium_server.exhibition import serializers as exhibition_serializers
class ReviewSer... |
#언패킹
a = [(1, 2), (3, 4), (5, 6)]
for i, j in a:
print("%d + %d = %d"%(i, j, i + j))
filmFestival = {
"최우수 작품상":"택시운전사",
"감독상":"아이 캔 스피크",
"남우주연상":"송강호",
"여우주연상":"나문희"
}
for prize in filmFestival:
print(prize)
for winner in filmFestival.values():
print(winner)
#key와 value를 묶어서 들고옴
for... |
import os
import shutil
import glob
# get current directory and list the files and folders
current_dir = os.getcwd()
list_of_files_and_folders = os.listdir(current_dir)
# Set of folders to be excluded
folders_list = {
'Folders',
'Image files',
'Excel Files',
'Docs and ppts',
'PDF fil... |
import SteamScraperEngine
import json
import os.path
url ="https://store.steampowered.com/search/results/?query&start=0&count=50&dynamic_data=&force_infinite=1&category1=998%2C994%2C21%2C10%2C997&filter=topsellers&snr=1_7_7_7000_7&infinite=1"
urlGenre = "https://store.steampowered.com/tag/browse/#global_492"
def make... |
import numpy as np
import hpgeom as hpg
import numbers
from .healSparseCoverage import HealSparseCoverage
from .utils import reduce_array, check_sentinel, _get_field_and_bitval, WIDE_NBIT, WIDE_MASK
from .utils import is_integer_value, _compute_bitshift
from .io_map import _read_map, _write_map, _write_moc
import warn... |
import cx_Oracle
import getpass
user = input("Username [%s]: " % getpass.getuser())
if not user:
user=getpass.getuser()
pw = getpass.getpass()
conString=''+user+'/' + pw +'@gwynne.cs.ualberta.ca:1521/CRS'
connection = cx_Oracle.connect(conString)
cursor = connection.cursor()
pid=101
title="Window"
place="Utah" ... |
# Generates the intent schema and sample utterances for WordBox based on 1,000 of the most common words in the English language
# Intent Schema
# {
# "intents": [
# {
# "slots": [
# {
# "name": "Word",
# "type": "AMAZON.LITERAL"
# }
# ],
# "intent": "GetSyno... |
from openerp.osv import osv, fields
from openerp import netsvc
class plan_carry(osv.osv):
_name= 'plan.carry'
_columns= {
'type': fields.selection([('vote','Voting'),('poll','Poll')],'Type'),
'group': fields.char('User Group'),
'start_date': fields.date('Start Date'),
'finish_da... |
name = input('Enter customer name\n')
print('How may items store have?')
number = int(input()) * len(name)
print('-------------------')
print('Welcome {name}!\nOur store have {number} items'.format(name = name, number = number)) |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
pmu = [2, 6, 10, 19, 20, 22, 23, 25, 29]
n = 3
df = 39
# test_buses = [1, 1, 1, 1]
test_buses = []
for i in range(n):
test_buses.append(1)
print(test_buses)
def create_test_buses(n, test_buses, pmu, df):
for k in range(n):
... |
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def naseberry():
return "Hello World!"
@app.route("/something")
def saySomething():
return render_template("ourfirsttemplate.html",
title="learning flask",
heading="time to learn flask",
... |
def is_board_full(board):
for lists in board:
for item in lists:
if item == " ":
return False
return True
def is_valid_move(board, location):
if location not in range(1, 10):
return False
row = (location - 1) // len(board)
col = (location - 1) % len(... |
import sys
from validatelib import *
if __name__ == '__main__':
result = ExecutionInfo('assigment example', './decrypt', ['task3.2_pwsmall.txt', 'task3.2_dict.txt'], TextFileInfo('output.txt', '^((user906;Bahnhof.*?user\d*;.*?)|(user\d*;.*?user906;Bahnhof))$')).run()
try:
solution = TextFileInf... |
# --------------------------------------------------------------------------------------------------
# AWS Settings
# --------------------------------------------------------------------------------------------------
# Kinesis
KINESIS_STREAM_NAME = 'IncomingDataStream'
# DynamoDB Table and Column Names
ST... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from analyse_immo.factory import Factory
from analyse_immo.charge import Charge
from analyse_immo.lot import Lot
from test.testcase_fileloader import TestCaseFileLoader
class TestCharge(TestCaseFileLoader):
def setUp(self):
supe... |
#!/usr/bin/env python
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 50)
import pygame
import socket
import sys
import math
pixels = []
brightness = 50
MAX_BRIGHTNESS = 250
MATRIX_START_ID = 33
LCDS = []
printer_text = None
class Neopixel():
def __init__(self, x, y):
self.x = x
self... |
HOST = "127.0.0.1"
HOST_PUB = "sonata4.local"
CLIENT_ID = "gateway2"
CLIENT_ID_PUB = "gateway2_pub"
RULES_FOLDER = "resources/json_rules/"
SUB_TOPIC = '#'
HB_TOPIC = '/heart_beat'
RULES_TOPIC = '/SM/rule'
IN_TOPICS_TOPIC = '/gateways/in_topics'
OUT_TOPICS_TOPIC = '/gateways/out_topics'
HB_TIMER = 5
MAX_MEM = 2000000
GA... |
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ephemeral.build_api import LibFunction
logger = logging.getLogger(__name__)
class JobTask(object):
def __init__(self, name: str, type: str, lib_function: 'LibFunction', parent: 'JobTask'):
self.name = name
self.type = ty... |
from pulp import *
import numpy as np
import random as rd
## Paramètres
n=3 #nombre de patients
p=3 #nombre de créneaux
pref= [[2,1,2],[1,2,3],[3,3,1]] #pref est la matrice des préférences des patients : pref[k][i] contient le rang assigné par le patient i au créneau k
## Programme linéaire
#problème d'indices... |
"""
Copyright 1999 Illinois Institute of Technology
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publis... |
#!/usr/bin/env python3
"""
- включать триггер и возвр его состиояние
- чек статус процесса на этипах: память и стейт, опц имя
"""
from time import sleep
from sys import stdout, stderr, argv, exit
pid = argv[1]
s = 0.05
k = 0.95
def rline1(path):
"""read 1st line from path."""
with o... |
import base64
import cv2
import zmq
import sys
import argparse
import multiprocessing as mp
#########################################################################################################################
# https://stackoverflow.com/questions/4290834/how-to-get-a-list-of-video-capture-devices-web-cameras-on-l... |
from ete2 import NCBITaxa
from joblib import Parallel, delayed
from os.path import join as pjoin
import os
from tqdm import tqdm
def mash(info):
genome = info
genome.compute_mash_hash()
def checkm(info):
genome = info
genome.compute_checkm()
def prokka(info):
genome = info
genome.prokka()
... |
import random
n = 10000000
Afehler = 0
fehler = 0
for i in range(n):
a = random.random()
b = random.random()
data_cls = random.random()
d = random.random()
if (a < 1 / 3 and not (b < 1 / 3 or data_cls < 1 / 3 or d < 1 / 3)):
Afehler += 1
if (a < 1 / 3 or b < 1 / 3 or data_cls < 1 / 3 or ... |
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Convolution1D, Flatten, Dense, \
Input, Lambda, Activation, Reshape, Multiply, Add, Concatenate
from tensorflow.keras import backend as K
def wavenetBlock(n_atrous_filters, atrous_filter_size, atrous_rate):
def f(input_):... |
import json
import time
from urllib import parse
import requests
from prettytable import PrettyTable
from config import config_data
class Query:
def __init__(self,session):
self.session = session
self.config = config_data
self.chezhan_code = self.chezhan()
self.from_city_name = se... |
import requests
def get_some_data_from_api():
url = "https://api.icndb.com/jokes/random?firstName=John&lastName=Doe"
# implement some code here
print(url)
pass
|
#!/usr/bin/env python
#
# Copyright (c) 2011 Polytechnic Institute of New York University
# Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#... |
# -*- coding: utf-8 -*-
'''
Created on 07-08-2013
@author: Krzysztof Langner
'''
from collections import defaultdict
import json
import os.path
PREVIEW_LOG_SIZE = 30000
def read_sessions(filename):
sessions = defaultdict(list)
try:
with open(filename, "r") as f:
for line in f:
... |
import z
import buy
stocks = z.getp("listofstocks")
from sortedcontainers import SortedSet
# shrinking outstanding shares and increasing marketcap with slight volume
sset = SortedSet()
for astock in stocks:
try:
if buy.getFrom("latestmc", astock, None) > 1500:
continue
yearagomc_size ... |
import picamera
import time
camera = picamera.PiCamera()
camera.resolution = (320, 160)
camera.rotation = 180
camera.start_preview()
time.sleep(5)
camera.capture('photo.jpg')
camera.stop_preview()
|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UrlTable(models.Model):
title = models.CharField(max_length=100, null=True, blank=True)
long_url = models.CharField(max_length=1000, null=True, blank=True)
short_hash= models.CharField(max_length=1000... |
#
# cogs/text/meme.py
#
# mawabot - Maware's selfbot
# Copyright (c) 2017 Ma-wa-re, Ammon Smith
#
# mawabot is available free of charge under the terms of the MIT
# License. You are free to redistribute and/or modify it under those
# terms. It is distributed in the hopes that it will be useful, but
# WITHOUT ANY WARRAN... |
# @see https://adventofcode.com/2015/day/1
instructions = ''
with open('day1_input.txt', 'r') as fp:
instructions = fp.readline()
# At what floor does Santa stop?
def last_floor(l: str):
floor = 0
for x in l:
if x == '(':
floor += 1
else:
floor -= 1
return floor
# At which instruction... |
"""
* \author Hugo Silva
* \version 1.0
* \date July 2014
*
* \section LICENSE
This program 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 3 of the License, ... |
#!/bin/python
# Description: Creates a trivial package file from a list of files
#
# The package file contains the source files concatenated, with headers that allows their
# easy extraction. The files starts with a number (long int) indicating the number of the individual
# files contained in the package. Following t... |
"""
Define fixtures to provide common functionality for Mimic testing
"""
from __future__ import absolute_import, division, unicode_literals
from mimic.test.helpers import json_request
from mimic.core import MimicCore
from mimic.resource import MimicRoot
from twisted.internet.task import Clock
class TenantAuthentic... |
print("-------------------对象所属的类之间没有继承关系------------------------")
# 调用同一个函数fly(), 传入不同的参数(对象),可以达成不同的功能
class Duck(object): # 鸭子类
def fly(self):
print("鸭子沿着地面飞起来了")
class Swan(object): # 天鹅类
def fly(self):
print("天鹅在空中翱翔")
cla... |
import sys
def getfib(num1, num2, i):
if i < 3:
return 1
if i == 3:
return num1 + num2
return getfib(num2, num1 + num2, i - 1)
def getfibindex(i):
return getfib(1, 1, i)
sys.setrecursionlimit(6000)
print(getfibindex(4782))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 27 08:49:43 2020
@author: Administrator
"""
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn import metrics
from sklearn.metrics.cluster import adjusted_rand_score as ari
from sklear... |
def printLine():
print("-"*30)
def printLine_2(n):
i = 0
while i<n:
printLine()
i+=1
num = int(input("请输入循环次数:"))
printLine_2(num) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 7 15:32:36 2017
@author: dgratz
"""
import matplotlib.pyplot as plt
'''
read in files for CL graphs adn sync graphs
'''
from plotBeat2beatCLGrid import b2bCL
from plotSynchronyMeasure import b2bSync
b2bSTimes,b2bST,b2bSV=b2bSync('D:/synchrony-dat... |
from django.shortcuts import get_object_or_404
from celery.decorators import task
from celery.utils.log import get_task_logger
from .calculations.calculation_driver import create_quick_look
from django.contrib.auth.models import User
logger = get_task_logger(__name__)
@task(name="quicklook.create_quicklook")
def gen... |
class Square:
side = 3
def __init__(self):
self.side = 0
def area(self):
return self.side * self.side
ob = Square()
print(Square.side)
print(Square.area(ob))
print(ob.side)
ob.side = 4
print(ob.area())
del ob.side # this statement determined that if i create a variable outside the cla... |
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('login', views.loginUser, name='loginUser'),
path('logout', views.logoutUser, name='logoutUser'),
path('form', views.get_incident_report, name='get_incident_report... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 30 09:50:05 2021
@author: aureoleday
"""
import numpy as np
def calc_lr(target,samples):
a = []
if samples.size == samples.shape[0]:
X = np.c_[np.ones(samples.shape[0]),samples]
a = (np.matrix(np.dot(X.T,X)).I).dot(X.T).do... |
import numpy as np
def cluster_results(clusters, pids_array):
clusters_pids = [[] for _ in range(np.amax(clusters) + 1)] ## here we create the arrays where the pids will be
## the index is going to be the number of the cluster
for element in range(len(clusters)):
clusters_pids[clusters[ele... |
import csv
import cv2
import numpy as np
from sklearn.utils import shuffle
from preprocess import preprocess # resize image module
lines = []
# Left and right camera input function
def multicamera(line, lines, correction):
line_l, line_r = [], []
line_l = line
line_r = line
line_l[3] = float(line[3])... |
import datetime
from models import Base
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Float
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import validates
class PaymentPlan(Base):
__table... |
try:
import cv2
import numpy as np
from matplotlib import pyplot as plt
except:
print ("please install the dependencies \n using command pip3 install requirements.txt")
image=cv2.imread("images/obama.jpg") #reading the image into opencv
image_bw=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
image_hsv=cv2.cv... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""Wrapper that samples a new task everytime the environment is reset."""
from mtenv import MTEnv
from mtenv.utils.types import ObsType
from mtenv.wrappers.multitask import MultiTask
class SampleRandomTask(MultiTask):
def __init__(self, env: ... |
# -*- python -*-
# Assignment: MathDojo
#
# HINT: To do this exercise, you will probably have to use 'return self'.
# If the method returns itself (an instance of itself), we can chain methods.
#
# PART I
#
# Create a Python class called MathDojo that has the methods:
# - add
# - subtract
# Have these 2 functi... |
from svg.path import parse_path
|
from pymel import core as pm
import maya.cmds as cmds
# TBS for the modern era
def tbs():
particles = check_selection()
if not particles: return
for p in particles:
print p, p.nodeType()
# check to see if particles are already TBS
if pm.objExists("{}.isBig".format(p)):
... |
import argparse
import json
from os.path import join
from typing import List
import numpy as np
import pandas as pd
from tqdm import tqdm
from docqa import trainer
from docqa.data_processing.document_splitter import MergeParagraphs, TopTfIdf, ShallowOpenWebRanker, FirstN
from docqa.data_processing.preprocessed_corpus... |
#-*- coding:utf8 -*-
# Copyright (c) 2020 barriery
# Python release: 3.7.0
# Create time: 2020-07-08
import json
with open("test.txt2") as f:
a = f.read()
print(json.dumps(json.loads(a)))
|
# Выведите разложение натурального числа n > 1 на простые множители. Простые множители должны быть упорядочены по возрастанию и разделены пробелами.
# Sample Input:
# 75
# Sample Output:
# 3 5 5
# import java.util.Scanner;
# class Main {
# public static void main(String[] args) {
# int n = 0;
# ... |
#!/usr/bin/env python3
import subprocess
cmd = "open"
arg = "-a"
prog = "intelliJ IDEA CE"
print('opening '+prog+'...')
subprocess.Popen([cmd, arg, prog])
|
import numpy as np
import tensorflow as tf
from draw import *
x = [1,2,3]
y = [[2,3,4]]
sess = tf.Session()
with tf.variable_scope(''):
y = tf.get_variable(name = 'sigh',initializer = tf.initializers.constant(3),shape = [1,2])
y2 = tf.get_variable(name = 'sigh2',initializer = tf.initializers.constant(3),shape =... |
min = int(input('enter the number'))
max = int(input('enter the number'))
for i in range(min,max+1):
print(i) |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class KuaishouItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
class KuxuanKolUserItem(scrap... |
import math
'''
This is an implementation of the Taylor's series metod of approximating
ordinary differenetial equations. Not quite as effective as the Runge Kutta
method.
'''
def T4():
# initial conditions x(0) = 1, step size of 1/100
x = 1
t = 0
h = 0.01
while t <= 1:
print("t = %2.3f\tx = %9.9f... |
import numpy as np
from numpy.random import Generator, PCG64
import matplotlib.pyplot as plt
import time
a = np.arange(100000)
r = Generator(PCG64())
start = time.time()
for x in a:
np.exp(r.standard_normal()*10000)
end = time.time()
print("duration :")
print((end - start)*1000)
print(" ms")
|
# Реализуйте стохастический градиентный спуск, то есть методы SGD (stochastic gradient descent) и update_mini_batch класса Neuron. Когда вы решите сдать задачу, вам нужно будет просто скопировать соответствующие функции (которые вы написали в ноутбуке ) сюда. Копируем без учёта отступов; шаблон в поле ввода ответа уже ... |
"""
Channel resource implementation.
"""
from typing import Optional, Union
from pyyoutube.error import PyYouTubeException, ErrorMessage, ErrorCode
from pyyoutube.resources.base_resource import Resource
from pyyoutube.models import Channel, ChannelListResponse
from pyyoutube.utils.params_checker import enf_comma_s... |
#!/system/bin/python
#Coder by jimmyromanticdevil
#Recoder by ./Mr.Java404
#Date & Time 10/07/2017 [06:09]
#Team N45HT (Exploiting and Creativity)
import urllib2
import urllib
import sys
import time
import random
import re
import os
os.system("clear")
#Warna
B = '\033[1m' #Bold
R = '\033[31m' #Red
G = '\033[32m... |
import random
a = int(random.random() * 100) + 1
print(a)
b = int(random.random() * 900) + 100
print(b)
c = int(random.random() * (ord("Z")-ord("A"))) + ord("A")
print(chr(c))
d = int(random.random() * 99 ) + 1
print(d)
if d%2==0:
print("True")
else:
print("false") |
import numpy as np
import sys
import math
from aresta import Aresta
from heapsort import heapSort
def makeSet(qtdeVertices):
conjunto = []
for i in range(qtdeVertices):
conjunto.append([])
conjunto[i].append(i)
return conjunto
def makeArestas(matriz,qtdeVertices):
arestas = []
for... |
import key_generator.key_generator as key
import threading
Sk = key.generate(num_of_atom=9,seed=1)
print(Sk.get_key())
|
from collections import Counter, defaultdict
def letter_frequency(text):
by_value = defaultdict(list)
for k, v in Counter(a.lower() for a in text if a.isalpha()).items():
by_value[v].append((k, v))
result = []
for key in sorted(by_value, reverse=True):
result.extend(sorted(by_value[key... |
"""add user banned
Revision ID: 4f28090745df
Revises: 1782e1af3cc2
Create Date: 2015-11-18 09:59:26.930530
"""
# revision identifiers, used by Alembic.
revision = '4f28090745df'
down_revision = '1782e1af3cc2'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic ... |
# Import the numpy package to compute the image and objective function
import numpy as np
# Import the superclass (also called base class), which is an abstract class,
# to implement the subclass AckleyFunction
from ObjectiveFunction import *
from ImageMetrics import *
# The subclass that inherits of ObjectiveFunct... |
# Author - Joshua Schoonmaker
# StarWarsName.py
# CIS 125 IWU
# Week 3 Star Wars Name Assignment
#
def main():
# Initial input requests
strFirstName = input("Please enter your first name: ")
strLastName = input("Please enter your last name: ")
strMaidenName = input("Please enter your mother... |
import random
from sys import argv
file_path = argv[1]
def open_and_read_file(file_path):
"""Takes file path as string; returns text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
text_string = open(file_path).read()
ret... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 08:49:07 2020
@author: scott
"""
# dataframe imports
import pandas as pd
# plotly
from plotly import subplots
from plotly import graph_objs as go
import plotly.express as px
# =============================================================================
# #### Impo... |
import itertools
class Game:
def __init__(self):
self.board = [[None] * 3 for _ in range(3)]
self.turns = itertools.cycle('OX')
self._switch_player()
def _switch_player(self):
self.current_player = next(self.turns)
def _has_winner(self):
def is_equal_row(row):
... |
import argparse
from PIL import Image
from PIL.ImageSequence import Iterator as gifiter
import numpy as np
import math
def psnr(im1, im2):
'''
Peak Signal to Noise Ratio, PSNR
im1, im2: path to original and SR
'''
im1,im2 = im1.convert('RGB'),im2.convert('RGB')
im1,im2 = np.array(im1,dtype=np.... |
import random
import pygame
from pygame.locals import *
class Base(object):
def __init__(self, screen_temp, x, y, image_name):
self.x = x
self.y = y
self.screen = screen_temp
# create a plane
self.image = pygame.image.load(image_name)
class Plane(Base):
def __init__(s... |
import csv
import boto3
import pprint
# asg_list = [
# 'AWOR-PDMESCIO01-ASG',
# 'AWOR-PDORAAPX01-asg',
# 'AWOR-PDQLKGEO01-asg',
# 'AWOR-PDQMSWEB02-asg',
# 'AWOR-QALABAPP01-asg',
# 'AWOR-TSDWHAPP01-asg',
# 'AWOR-TSOLAPDB01-asg',
# 'AWOR-TSOLAPPB01-asg',
# 'AWOR-TSPDMLAS01-asg',
# 'AWOR-TSSASAPP01-asg',
# 'AwOr-PdMovXfr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.