text stringlengths 38 1.54M |
|---|
# Generated by Django 3.2.5 on 2021-07-30 11:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('project', '0003_auto_20210728_2029'),
]
operations = [
migrations.RemoveField(
model_name='tag'... |
"""
You are given an array of non-negative integers that represents a two-dimensional elevation map where each element is unit-width wall and the integer is the height. Suppose it will rain and all spots between two walls get filled up.
Compute how many units of water remain trapped on the map in O(N) time and O(1) sp... |
#!/usr/bin/env python3
def text_file_aligning(file, align, lineLength):
"""Splits text file into lines with given length and align these lines
as given.
Parameters:
file - path to .txt file. String.
align - type of aligning. One-symbol string.
r - right
l - left
... |
from django.http import HttpResponseRedirect
def redirect_to_referer_or(request, default):
if referer := request.META.get("HTTP_REFERER") is not None:
return HttpResponseRedirect(referer)
else:
return default
|
def ordena(t):
return -1*t[0], -1*t[1], -1*t[2], t[3]
paises = []
N = int(input())
for n in range(N):
entry = input().split(' ')
paises.append([int(entry[1]), int(entry[2]), int(entry[3]), entry[0]])
paises = sorted(paises, key=ordena)
for i in range(N):
print(paises[i][3], paises[i][0], paises[i][1], paises[i]... |
class Position:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
@property
def position(self):
"""Get position tuple
Returns:
tuple: (x, y)
"""
return self.x, self.y
def __str__(self) -> str:
return f"<{self.x}, {self.y}... |
#!/usr/bin/env python3
"""
Machine Learning - Mean squared error, R-squared, Residual Plot
Video:
https://www.youtube.com/watch?v=CbESY3v80zg
Regressors:
https://scikit-learn.org/stable/supervised_learning.html#supervised-learning
How to chose the right algorithm?
By measuring mean squared error of regressor!
"""
... |
import pandas as pd
import json
from routers.Unicorn_Exception import UnicornException
from utils import Deseq
from utils import heatmap
from utils import ploty_vp as vp
# '''
# This file is controller that connect deseq and plotly classes to deseq router.
# '''
#
# '''
# params :
# * locations - arra... |
# template for "Stopwatch: The Game"
# try to stop the watch on a whole second
import simplegui
# define global variables
time = 0
success = 0
total = 0
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
D = t % 10
C = (t // 10) %... |
from sklearn import manifold
from scipy.sparse.csgraph import connected_components
def get_auto_isomap_gdist(data):
number_connected_components = 100
num_neigh = 1
while number_connected_components > 1:
embedding = manifold.Isomap(n_neighbors=num_neigh)
embedding.fit_transform(data)
... |
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
class DAG(nx.DiGraph):
def __init__(self, edges=None):
super(DAG, self).__init__(edges)
# 检查是否出现cycles
cycles = []
try:
cycles = list(nx.find_cycle(self))
except nx.NetworkXNoCycle:
... |
from time import sleep
import pytest
from meiga import BoolResult, isFailure, isSuccess
from petisco import DomainEvent
from tests.modules.extra.rabbitmq.mother.domain_event_user_created_mother import (
DomainEventUserCreatedMother,
)
from tests.modules.extra.rabbitmq.mother.message_subscriber_mother import (
... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 23rd 22:37:21 2020
@author: Christian
******************************************************************************
These functions allow users to compare xy curves.
******************************************************************************
"""
... |
import csv
from django.http import HttpResponse
from django.utils.translation import ugettext_lazy as _
from efenua.decorators import action
def make_export_as_csv(fields=None, exclude=None, header=True):
"""
This function returns an export csv action
'fields' and 'exclude' work like in django Mo... |
import pygame
import random
import math
ancho_celda = 50
columnas = filas = 10
width = columnas * ancho_celda
height = filas * ancho_celda
class snake:
bbody = []
dirx = 0
diry = 1
cap = pygame.Vector2(math.ceil(columnas/2), math.ceil(filas/2))
def move(self):
for i in range( len(self.bbo... |
import unittest
from RSSFeed import RSSobject, ViceRSS
class RSSTester(unittest.TestCase):
def setUp(self):
self.RSS = RSSobject('http://feeds.bbci.co.uk/news/rss.xml')
def rss_raw_page_test(self):
assert '<?xml' in self.RSS.raw
#def rss_soup_page_test(self):
# assert 'BBC' in sel... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Address',
fields=[
... |
import urlparse
def assign(service, arg):
if service == 'www':
return True, arg
def audit(arg):
url = urlparse.urlparse(arg).netloc
a = ('bak','backup','www','web','wwwroot','beifen','ftp','website','back','backupdata','temp','htdocs','database','data','user','admin','test','conf','config'... |
from ksc.utils import translate_and_import
def test_fold():
ks_str = """
(edef add Integer (Tuple Integer Integer))
(edef sub Integer (Tuple Integer Integer))
(edef mul Integer (Tuple Integer Integer))
(edef div Integer (Tuple Integer Integer))
(edef eq Bool (Tuple Integer Integer))
(def mod (Integer) ((x : Integ... |
# This version of train_funcs.py is modified based on the theano_alexnet project. See the original project here:
# https://github.com/uoguelph-mlrg/theano_alexnet, and its copy right:
# Copyright (c) 2014, Weiguang Ding, Ruoyan Wang, Fei Mao and Graham Taylor
# All rights reserved.
import glob
import time
import os
i... |
#!/usr/bin/env python
#
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), "..", "python"))
from KVAN import fuargs, ymlconfig, topdir
@fuargs.action
def show(yml):
print("top_dir: ", topdir.get_topdir())
conf = ymlconfig.Config()
conf.parse(yml)
conf.pprint()
if __name__ == ... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
import itertools
import operator
import unittest
from unittest.mock import Mock
class ChainTests(unittest.TestCase):
def test_chain_with_no_iterables_returns_stoped_iterator(self):
self.assertTupleEqual(tup... |
# Generated by Django 2.1.1 on 2019-03-17 13:44
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('chefs_apprentice', '0005_recipe_visible'),
]
ope... |
from tkinter import *
import random
# Making a list of possible colours.
colours = ['Brown', 'Purple', 'White', 'Orange', 'Yellow', 'Black', 'Pink', 'Green', 'Blue', 'Red']
score = 0
# We give intial value of time to be 30 seconds to take in account for the time left
time = 30
# Creating a function to initate t... |
import cv2
import numpy as np
face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade=cv2.CascadeClassifier('haarcascade_eye.xml')
cap=cv2.VideoCapture(0)
while True:
ret,img=cap.read()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray,1... |
from django.shortcuts import render
# Create your views here.
import json
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
# Create your views here.
from django.urls import reverse
from linux.models import Teacher
def index(request):
teacher1 = Teac... |
# Resume Generator
# imported necessary library
import tkinter
from tkinter import *
import tkinter as tk
import tkinter.messagebox as mbox
from PIL import Image, ImageTk
from fpdf import FPDF
import webbrowser
# main window created
window = Tk()
window.geometry("1000x700")
window.title("Resume Generator")
# defin... |
import numpy as np
import pandas as pd
from sklearn.naive_bayes import BernoulliNB
from sklearn.naive_bayes import GaussianNB
import random
import math
def preprocess(data, test):
box_size = 20
original_size = 28
if not test:
streched_data = np.empty((data.shape[0], box_size*box_size+1))
else:
... |
"""
Page Templating with Python 🌐🐍
GitHub :: PCabralSoftware - 2K18 - Twitter :: @pedrogcabral
"""
# https://scrimba.com/c/cbBpPsk
from browser import document
from browser import html
from browser.template import Template
import os
pageName = "Python 🐍"
articleContent = open('/static/webprogram/python/ne... |
import aiohttp_jinja2
from aiohttp import web
from .config import HOSTNAME, BROKEFILE
@aiohttp_jinja2.template('index.html')
async def index(request):
return {"hostname": HOSTNAME}
async def health(request):
return web.Response(text="It's cool, it's cool.\n")
async def breakit(request):
open(BROKEFILE,"... |
'''
Title : Introduction to Sets
Subdomain : Sets
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
'''
def average(array):
# your code goes here
array = set(array)
return sum(array)/len(array)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().spli... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 23:12:28 2019
@author: yoelr
"""
import biosteam as bst
from biorefineries.cellulosic import units
from biorefineries.cellulosic import streams as s
from .integrated_bioprocess import create_integrated_bioprocess_saccharification_and_cofermentation_system
from .coferm... |
import yaml
import os
import time
import math
from cloth import cloth
import nga_text
class user_manager:
userList = {}
def load(self):
if os.path.exists('resource/user.yaml'):
with open('resource/user.yaml', 'r', encoding='utf-8') as f:
data = yaml.load(f.read(), Loader=y... |
import random
b = random.randint(1,20)
a = [random.randint(-10,10) for i in range (0,b)]
print(a)
k=0
for j in range(0,b-1):
if a[j]==a[j+1]==0:
k+=1
print(a)
if k>0:
print("Имеются два нуля подряд")
|
#!/usr/bin/python3
def weight_average(my_list=[]):
if len(my_list) == 0:
return 0
a = []
for i in my_list:
if len(i) == 0:
a.append((0, 0))
if len(i) == 1:
a.append((i[0], 0))
else:
a.append(i)
score = 0
weight = 0
for x in a:... |
import unittest
import solution as s
tests = [
["Mexico",["Mexico", "Me"]],
["Melania",["Melania", "Me"]],
["Melissa",["Melissa", "Me"]],
["Me",["Me"]],
["", [""]],
["I", ["I"]],
]
class TestBasic(unittest.TestCase):
def test_solution(self):
for test in tests:
self.a... |
import json
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils.importlib import import_module
from app.myblog.models import Article, Classification, Tag, Knowledge
class TestSimplePage(TestCase):
def test_index(self):
resp = s... |
from interfacebuilder.misc import *
import spglib
class interactive_plot:
def plot_results(self, jitter=0.05):
""" Plots results interactively.
Generates a matplotlib interface that allows to select the reconstructed stacks and save them to a file.
Args:
jitter (float,... |
#!/usr/bin/env python
import logging
import os
import StringIO
from ConfigParser import ConfigParser, SafeConfigParser
from ConfigParser import NoOptionError
from autopyfactory.apfexceptions import ConfigFailure
from autopyfactory.configloader import Config, ConfigManager
from autopyfactory.interfaces import ConfigI... |
# Validating Roman Numerals
#######################################################################################################################
#
# You are given a string, and you have to validate whether it's a valid Roman numeral. If it is valid, print True.
# Otherwise, print False. Try to create a regular ... |
class Solution(object):
def smallestRange(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
if any(len(num) == 0 for num in nums):
return False
heap = [(num[0], i, 0) for i, num in enumerate(nums)]
heapq.heapify(heap)
max... |
# -*- coding: utf-8 -*-
from time import sleep
from unittest import TestCase
from appium import webdriver
from UIAutomation.Utils import get_ios_udid, start_ios_appium, stop_ios_appium
from UIAutomation.Page.Mobile.iOS.CardListPage import CardList
from UIAutomation.Page.Mobile.iOS.LoginPage import LoginPage
'''
该... |
import shelve
shelfFile = shelve.open('mydata')
dogs = ['Jamie', 'Tucker', 'Max']
shelfFile['dogs'] = dogs
shelfFile.close() |
import numpy as np
import cv2 as cv
import glob
off = []
images = [cv.imread(file,1) for file in glob.glob(
r'C:\Users\Juho\Python_Files\ORing\Training\*.jpg')]
for img in images:
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
blur = cv.bilateralFilter(gray,9,220,55)
_,thres = cv.threshold(blur,100,255,c... |
import urllib2
import sqlite3
import random
import time
import datetime
random.seed() #uses system time to seed
def CraigsListCars():
s_site = 'craigslist_cars'
s_url = 'https://philadelphia.craigslist.org/search/cta?s='
art = CL_GetArticleList(s_url)
print('number of articles: '+str(len(art)))
cars = Get_Articl... |
def bonecoForca():
kbca = ''
for i in range(1,3,1):
kbca = kbca + ' ' * 50 + '*' * 20 + '\n'
for i in range(1,3,1):
kbca = kbca + ' ' * 50 + '*' * 2 + ' ' * 16 + '*' * 2 + '\n'
contAst1 = 2
contEsp1 = 16
for i in range(1,3,1):
kbca = kbca + ' ' * 50 + '*' * 2 + ' ' * ... |
#! python3
# "Predicts" stock price using csv datasheet and support vector regression
import csv
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVR
prices = []
dates = []
tesla_file = 'TSLA.csv'
def parse_csv(filename):
'''
read in csv data, s
'''
with open(filename, 'r')... |
from collections import Counter
import sys
llfile=open("/home/pilatus/WORK/pred-clust/data/ES/es-en-langlinks-no-escapes.txt", "r")
srlfile=open("/home/pilatus/WORK/pred-clust/data/ES/en-articles-no-quotes.txt", "r")
lls = llfile.readlines()
arts = srlfile.readlines()
print " lang-linked files: ", len(lls)
print " s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from posts.managers import AuthorManager, ArticleManager
# Create your models here.
class Author(models.Model):
"""
author: chen
create_date: 2017/03/26
"""
MALE = 'M'
... |
"""
@version: python3.5
@author: jsdiuf
@contact: weichun713@foxmail.com
@time: 2018-8-15 10:07
"""
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dic1, dic2 = {}, {}
ret = []
... |
#
# 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020)
# 14.25 간단한 회귀모델을 만들자, 395쪽
#
import pandas as pd
import seaborn as sns # 시각화를 위하여 Seaborn 라이브러리를 이용함
import matplotlib.pyplot as plt
import numpy as np
life = pd.read_csv('d:/data/life_expectancy.csv')
life.dropna(inplace = True)
X = life[['Alcohol', 'Percentage expenditure',... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Unit tests for {0}
#
# Pablo Munoz (c) 2019
# pablo.bmf@gmail.com
#
import unittest
import numpy as np
from BaseTestCase import BaseTestCase
TEST_NAME = '{0}'
class TestCase(BaseTestCase):
# def test_NEW_TEST(self):
# assert 2 + 2 == 4
#
pass
if _... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("EcalSelectiveReadoutValid")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
)
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring('to_be_replaced')
)
import FWCore.Modules.p... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import glob
import cv2
import os
#Training set
print("Loading training set...")
train_labels=[]
train_images=[]
for dir_path in glob.glob("/datasets/ee285s-public/fruits-360/Training/*"):
label=dir_path.split("/")[-1]
for image_path in g... |
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, override_settings
BASE_DEFAULT = {
"TENANT_MODEL": "shared_public.Tenant",
"DOMAIN_MODEL": "shared_public.Domain",
"URLCONF": "",
}
class AppConfigTestCa... |
import unittest
from labyrinthe.labyrinthe import Labyrinthe, creer_labyrinthe_depuis_chaine
#from labyrinthe import labyrinthe
from labyrinthe.obstacle.mur import Mur
from labyrinthe.obstacle.porte import Porte
from labyrinthe.obstacle.sortie import Sortie
from labyrinthe.obstacle.libre import Libre
from labyrinthe.r... |
from layer import *
import tensorflow as tf
import keras
from keras.layers import Input, Dense, Dropout
from keras.models import Model
from keras import regularizers
from keras import constraints
from keras import backend as K
class Softgum_app:
def __init__(self, x, is_training, batch_size, feature_num, dropout_v... |
from django.db import models
from django.contrib.auth.models import User
from pagedown.widgets import AdminPagedownWidget
from datetime import datetime
from django.utils.text import slugify
import datetime
# Note, if you add another field when you already have fields filled
# make sure to run makemigrations and migrate... |
"""ADMIN URL configuration."""
# Django
from django.contrib import admin
from django.urls import include, path
# Views
from admin_alimentos import views
app_name = "admin_alimentos"
urlpatterns = [
path('registrar-alimento/', views.RegistrarAlimento.as_view(), name='registrar_alimento'),
path('ver-alimento/'... |
#!/usr/bin/python3
#server side
import socket
import re
import sys
import threading
def handle_client(client_socket):
request = client_socket.recv(1024).decode('utf-8')
print("<> Odebrano: {}".format(request))
client_socket.send("ACK!".encode('utf-8'))
client_socket.close()
return True
if... |
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
self.re = []
self.dfs(candidates, target, 0, [])
return self.re
def dfs(self, candidates, target, start, val):
if target == 0 and ... |
import pickle
from preprocessing import PreProcessing
from joblib import load
class Predictor:
def __init__(self):
#self.model = pickle.load(open('finalized_model.sav', 'rb'))
self.model = load('models/finalized_model.joblib')
self.preprocesing = PreProcessing()
self.input = self.pr... |
# Build a statement to count records using the sex column for Men ('M') age 36: stmt
stmt = select([func.count(census.columns.sex)]).where(
and_(census.columns.sex == 'M',
census.columns.age == 36)
)
# Execute the select statement and use the scalar() fetch method to save the record count
to_delete = conn... |
import cv2
import numpy as np
import imutils
# A box is a tuple (category,(x,y,w,h)) where category is the category of the
# object, x and y represent the top-left corner, w is the width and h is the height.
def detectBox(image,box,function):
mask = np.zeros(image.shape[:2], dtype="uint8")
(category,(x,y,w,h))... |
from collections import deque
from itertools import repeat, islice, count
from .util import (
SaveLoad, to_list, fill, load,
state_size_dataset, level_dataset
)
from .scanner import Scanner
class ParserBase(SaveLoad):
"""Base parser class.
Attributes
----------
classes : `dict`
Parse... |
############################################################################
# Copyright (c) 2016, Johan Mabille and Sylvain Corlay #
# #
# Distributed under the terms of the BSD 3-Clause License. #
# ... |
def main () :
print ("Este es un programita :3")
print ("Estamos en la mitad UwU")
print ("Terminamos ÒwÓ")
main() |
class Solution:
def reverseWords(self, s: str) -> str:
# 去掉空格
s = s.split()
# 反转
s = reversed(s)
# 加入空格,返回字符串
return " ".join(s) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.EncryptedPaymentCredential import EncryptedPaymentCredential
class PaymentCredential(object):
def __init__(self):
self._expiration_timestamp = None
self._iden... |
"""
https://leetcode.com/problems/find-largest-value-in-each-tree-row/
You need to find the largest value in each row of a binary tree.
"""
from binary_tree.TreeNode import *
from typing import *
class Solution:
def largestValues(self, root: TreeNode) -> List[int]:
"""
There are several ways to ... |
from django.contrib import admin
from .models import Watchdog
@admin.register(Watchdog)
class WatchdogAdmin(admin.ModelAdmin):
list_display = ("observer", "number")
|
#定义一个名为Dog的类,Python中首字母大写的名称指定为类
class dog():
"""一次模拟小狗的简单尝试"""
#类中的函数成为方法_inti_
def _init_(self,name,age_):
"""初始化属性name和age"""
self.name=name
self.age=age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title()+" is now sitting.")
def roll_over(self):
"... |
# -*- coding: UTF-8 -*-
from Action import *
# 连接游戏服务器
class ConnectAction(BaseAction):
def __init__(self, client, timeout=0):
self.server_ip = ''
self.server_port = 0
self.client = client
self.time_out = timeout # 超时时间, 0-不超时, 单位: 秒
self.action_name = '连接游戏服务器' # 任务名称
... |
class Parameters:
#Constructor
# state_dim define the state dimension
# particles define the particles number
# time define the simulation time
def __init__(self, state_dim, particles, time):
self.state_dim = state_dim
self.particles = particles
self.time = time |
"""
Defines the base (inheritable) class that describes a digital elevation model. This inherits from
the model class and various bundled elevation models (such as the USGS/NOAA DEM) inherit from this
class.
:copyright: Southern California Earthquake Center
:author: David Gill <davidgil@usc.edu>
:created: July 19... |
import os
import config
import dialog_flow
import Webex_Teams as teams
from flask import Flask, jsonify
from flask import request
from flask import make_response
app = Flask(__name__)
baseurl = "https://api.ciscospark.com/v1"
bot_auth_token = config.bot_token
bot_id = config.spark_bot_id
headers = {"Content-Type":... |
"""
test_parallel_tools
-------------------
Testing function for the functions of the module parallel_tools.
"""
import numpy as np
from matrix_splitting import distribute_tasks, reshape_limits,\
generate_split_array, split_parallel
def test():
## Parameters
n, memlim, limits = 1250, 300, (250, 1500)
... |
import os
import numpy as np
import time
import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.data import Dataset as BaseDataset
import time
from utils import train, losses, metrics
from sklearn.model_selection import train_test_split
from dataset.dataset import M... |
import sys
from sympy import *
from typing import Any, List
from multiprocessing import *
import os
# Parse input string into a list of all parentheses and atoms (int or str),
# exclude whitespaces.
def normalize_str(string: str) -> List[str]:
str_norm = []
last_c = None
for c in string:
if c.isal... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.dual import eig
from scipy.special import comb
from scipy import linspace, pi, exp
from scipy.signal import convolve
__all__ = ['daub', 'qmf', 'cascade', 'morlet', 'ricker', 'cwt']
def daub(p):
"""
The coefficient... |
def find_max_fib(digits):
import math
factorStart = int(math.floor(math.pow(10, digits)) - 1)
minFactor = 0
maxVal = 0
for x in range(factorStart, 1, -1):
for y in range(factorStart, 1, -1):
val = x*y
if is_palindrome(val) and val > maxVal:
print(f"New... |
import argparse
from os import listdir, rename
from os.path import join
parser = argparse.ArgumentParser(description='This script removes annoying track numbers and whatnot from the names of music files in the given directory')
parser.add_argument('music_dir', help='Directory containing files')
parser.add_argument('dr... |
largura = int(input("Digite a largura do retangulo: "))
altura = int(input("Digite à altura do retangulo: "))
aux = altura
branco = " "
simb = "#"
linhaVazia = simb + (branco * (largura-2)) + simb
linhaCheia = simb * largura
while altura > 0:
if altura == 1 or altura == aux:
print(linhaCheia... |
def power(a,b):
if b == 0:
return 1
if b == 1:
return a
if b > 1:
if b % 2 == 0:
return power(a * a, b / 2)
return power(a * a, b / 2) * a
# return power (a, b-1)*a
# return power(a*a, b/2)
print(power(2, 5))
|
from importlib.util import find_spec
from logging import getLogger
from typing import Any, Dict, List # NOQA
from kedro.io import DataCatalog
from kedro.pipeline import Pipeline
from kedro.pipeline.node import Node
from .mlflow_utils import hook_impl, mlflow_log_artifacts
log = getLogger(__name__)
class MLflowArt... |
import glob
import re
import time
import gc
import sys
import os
print("Ready!")
text = True
sql = False
if len(sys.argv) > 2:
if "--no-txt" in sys.argv:
text = False
print("NO TXT")
if "--no-sql" in sys.argv:
sql = False
print("NO SQL")
input()
path = os.getcwd()
# files ... |
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div([
html.Div(id='target'),
dcc.Dropdown(
id='dropdown',
options=[
{'label': 'Video 1', 'value': 'video1'},
... |
import json, os, sys, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tango_with_django_project.settings")
from django.contrib.auth.models import User
with open("creds.json","r") as cred:
data = json.loads(cred.read())
u = User(username=data['django_superuser']['name'])
u.set_password(data['django_superuser... |
import random
# Generate the result of rolling n dice with m sides
def roll(num_dice: int, num_sides: int) -> []:
random.seed()
dice = []
for i in range(0, num_dice):
result = random.randint(1, num_sides)
dice.append(result)
return dice
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-05-10 08:05
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
d... |
from tkinter import *
from tkinter.ttk import *
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class Gui:
def __init__(self, window):
"""Construct and runs GUI"""
self.label = Label(window, text='CRIME V/S WEATHER ANALYSIS IN CHRISTCHURCH')
self.label.grid(row=0, ... |
import time
import pprint
from boto3 import client
def inspect_slot(slottype) :
c = client('lex-models', region_name="eu-west-1")
response = c.get_slot_type(
name=slottype
)
return response
if __name__=="__main__" :
print pprint.pformat(inspect_slot("democustomer"))
|
import networkx as nx
import random as rd
## 'triangle_proportion' decides the probability of having triangle for a node with degree larger than 1.
class newman_clustering_configuration(object):
def __init__(self, deg_seq, triangle_proportion):
self.deg_seq = deg_seq
self.triangle_proportion = triangle_proporti... |
from collections import defaultdict
class Solution:
def characterReplacement(self, s, k):
count = defaultdict(int)
res = max_count = left = 0
for right in range(len(s)):
count[s[right]] = count.get(s[right], 0) + 1
max_count = max(max_count, count[s[right]])
... |
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
"""
这个代码我一直都是超时的,也不知道为什么
后来才发现,当我判断三个数是否重复的时候,时间就必然会超时
这里我们直接通过排除相同的数字,来直接去除重复的可能性(这一点很重要)
这样的话就可以减少确认重复的时间
还有很多小细节可以减少时间,这个算法的重点就... |
# Can refer to Percentile_Rank.py for testing
dataset = []
n = 5
# Getting data inputs
for index in range(n):
dataset.append(int(input(f"data {index+1}: ")))
# Getting winzorisation level
winzs_lv = int(input("Winzorisation level: "))
# Defining a function to winzorise dataset
def winzor(data, x):
min_perc... |
import numpy as np
import scipy.io as sio
def load_data():
data = sio.loadmat("data.mat")['data'][0][0]
test = data[0] # 4 x test_size
train = data[1] # 4 x train_size
valid = data[2] # 4 x valid_size
vocab = data[3] # 1 x vocab_size
test_size = test.shape[1]
train_size = train.shape[1... |
# SPDX-License-Identifier: EUPL-1.2
# Copyright (C) 2022 Dimpact
"""
HTML assertion utilities.
Taken from https://github.com/open-formulieren/open-forms.git
"""
from lxml.html.clean import Cleaner
def strip_all_attributes(document: str):
"""
Reduce an HTML document to just the tags, stripping any attributes.... |
res = 0
lis1 = []
num = input("Enter number ele: ")
for i in range(num):
val = input("Enter a element: ")
lis1.append(val)
print lis1
for index in lis1:
if index <= 0:
min1 = min(lis1)
lis1.remove(min1)
min2 = min(lis1)
lis1.remove(min2)
res += min1 * min2
else:
max1 = max(lis1)
lis1.remove(max1)
ma... |
def poly(a, b, c):
def pol(x):
return a * x ** 2 + b * x + c
return pol
res1 = poly(1, 2, 3)
z = res1(4)
print(z)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.