text
stringlengths
38
1.54M
import numpy as np def sigmoid(z): return 1 / (1+np.exp(-z)) def sigmoid_prime(z): return sigmoid(z)*(1-sigmoid(z)) class NeuralNetwork(object): def __init__(self, X, Y): self.alpha = 0.05 self.inputs = X self.Y = Y self.output = np.zeros(self.Y.shape) self.hlayer1_size = 10 self.weights1 = np.random....
from django.db import models from django.contrib import admin #ACTOR = MATERIAL #PELICULA = ENCABEZADO #ACTUACION = DESCRIPCION class Material(models.Model): nombre = models.CharField(max_length=100) unidad = models.CharField(max_length=30) precio = models.CharField(max_length=30) def __str__(s...
from load_data_ex1 import * from normalize_features import * from gradient_descent import * from plot_data_function import * from plot_boundary import * import matplotlib.pyplot as plt from plot_sigmoid import * from return_test_set import * from compute_cost import * import os figures_folder = os.path.join...
from django.shortcuts import render,redirect,HttpResponse from django.views import View import pymysql import math from .page import * db = pymysql.connect("localhost","root","root",database="yishuo",cursorclass=pymysql.cursors.DictCursor) class message(View): def get(self,request): page = request.GET.get(...
import os API_ID = os.getenv("API_ID") API_HASH = os.getenv("API_HASH") BOT_TOKEN = os.getenv("BOT_TOKEN")
from good_smell import AstSmell, LoggingTransformer import ast class YieldFrom(AstSmell): """Checks for yields inside for loops""" @property def transformer_class(self): return YieldFromTransformer @property def warning_message(self): return "Consider using yield from instead of ...
# ! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Miller" # Datetime: 2019/8/27 13:57 import datetime import time # print(time.strptime("2019-08-27 13:58:40.258622".rsplit(".", 1)[0], "%Y-%m-%d %X")) # #################################################################### # res = datetime.date(year=2019,...
########################################################### #author:sunny, date:3/24/2019 #function:access the test case sequence, and setUp,tearDown #are accessed by every test named by test at the beginning ########################################################### #startend.py #coding = utf-8 from selenium...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
locals() # Zwraca słownik z nazwami i wartościami lokalnych zmiennych # Remove definition of variable. # Delete part of the list and entries from dictionaries. del() var = 6 del(var) # var no more! list = ['a', 'b', 'c', 'd'] del(list[0]) # Delete first element dict = {'a': 1, 'b': 2, 'c': 3} del(dict['b']) # De...
import time from selenium import webdriver driver = webdriver.Chrome('path/to/chromedriver') # Optional argument, if not specified will search path. driver.get('https://platform.gisaid.org/epi3/frontend#2b8eee'); driver.refresh() #刷新页面 #driver.maximize_window() #填充用户名 密码 验证码 driver.find_element_by_id("elogin").send_...
"""注册""" import hashlib from homework.ftp_finally.conf import conf from homework.ftp_finally.conf import log_conf def signup(user, pwd): """注册,对密码进行md5加密。""" md5 = hashlib.md5('陈文波'.encode('utf-8')) with open(conf.user_table, 'a', encoding='utf-8') as f1: msg = user+'|' md5.update(pwd) ...
""" Requires crack propagation data for two datasets to be manually exported from the main application. """ import os import numpy as np import matplotlib.pyplot as plt import h5py # Path to the results of the 'export-crack-propagation' command. crackDataPath = 'PLACEHOLDER-PATH' datasetNames = ['PTFE-Epoxy.csv',...
#!/bin/python3 import netifaces as ni import psutil import os import sys def ip_get(interface:str)->str: i = 0 result = [] address_list = psutil.net_if_addrs() for nic in address_list.keys(): if (interface in ni.interfaces()[i]): ip = ni.ifaddresses(ni.interfaces()[i])[ni.AF_INET][...
''' You are given an amount denoted by value. You are also given an array of coins. The array contains the denominations of the give coins. You need to find the minimum number of coins to make the change for value using the coins of given denominations. Also, keep in mind that you have infinite supply of the coins....
from abc import ABCMeta, abstractmethod from asyncio import sleep from threading import RLock from enum import Enum from typing import Optional from . import mailbox_statistics, messages, queue from .. import dispatcher, invoker class MailBoxStatus(Enum): IDLE = 0 BUSY = 1 class AbstractMailbox(metaclass=A...
import random rock = "👊" paper = "✋" scissors = "✌️" choices = [rock, paper, scissors] player = int(input(f"What do you choose? type 1 for {rock}, 2 for {paper} or 3 for {scissors}\n")) print("You choose") if player < 1 or player > 3: print("Invalid") ai = random.randint(1 , 3) print("Artificial Intell...
""" Django settings for djcems project. Generated by 'django-admin startproject' using Django 1.8.6. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths...
from urllib import parse import itertools, json from . import parsers, utils def get_sitepage(url, cached_content=None): """ Ask for new sitepage content from url and return a site page """ if not cached_content: cached_content = utils.encoded_text_from_url(url) soup = parsers.get_site_soup(cache...
import numpy as np import matplotlib.pyplot as plt ## [byte] time_result = [0] * 256; number_count = [0] * 256; lines = [] count = 0 with open('result_0xff.txt') as f: lines = f.readlines() for line in lines: s = line.split() time_result[int(s[0][0:2],16)] += int(s[1]) number_count[int(s[0][0:2],16)] += 1 fina...
1. Let _to_ be ? ToObject(_target_). 1. If only one argument was passed, return _to_. 1. Let _sources_ be the List of argument values starting with the second argument. 1. For each element _nextSource_ of _sources_, in ascending index order, do 1. If _nextSource_ is n...
from datetime import date from starlette.templating import Jinja2Templates from backend.schemas.issues import Label, Severity, Status templates = Jinja2Templates(directory="frontend/components") templates.env.globals = { **templates.env.globals, "severity": Severity, "status": Status, "label": Label...
from .auth import SignupApi, InitialLoginApi, PassLoginApi, GetUserNotifIdApi, GetUsersNotifIdsApi, GetAllUsersApi from .portfolio import GetAllPortfoliosApi, GetPortfoliosApi, AddPortfolioItemApi, SetPortfolioBuyTarget, SetPortfolioSellTarget, PortfolioDeleteApi, GetSinglePortfolioApi from .change import GetChangesApi...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- """ 日本語Kivy解説書でHello World的な """ from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import Rectangle class Field(Widget): def __init__(self): super(Field, self).__init__() self.canvas.add(Rectangle(source='background.jpg...
from math import comb from helpers import analytics analytics.monitor() def main(): result = 0 for n in range(1,101): for r in range(n+1): if comb(n,r) > 1000000: result += 1 return result print(main(), analytics.lap(), analytics.maxMem())
# ****************************************** # © 2019 Amar Lokman Some Rights Reserved # ****************************************** # --------------------------------------------------------- # ADD MODULES # --------------------------------------------------------- import time import Adafruit_MCP3008 import d...
import threading from fsync.master import Master from fsync.slave import Slave from fsync import common import asyncio import os import shutil import time import logging def run_thread(runnable: common.Runnable): def run(): asyncio.run(runnable.run()) thread = threading.Thread(target=run) thread.daemon = Tru...
import pygame from pygame.locals import * from Puntos import * class Jugador(): def __init__(self): super(Jugador, self).__init__() def mover(self, move, numColum, tablero): if(move[0] + 1 == move[1] - 1): tablero[move[0] + 1] = "-" elif(move[0] + numColum == move[1] - nu...
from typing import Dict, List, Tuple import numpy as np from torch.utils.data.dataloader import DataLoader from message_passing_nn.data.data_preprocessor import DataPreprocessor from message_passing_nn.infrastructure.graph_dataset import GraphDataset from message_passing_nn.model.trainer import Trainer from message_p...
######################################################################## # test_req_task_imhistory.py # # Copyright (C) 2018 # Associated Universities, Inc. Washington DC, USA # # This script is free software; you can redistribute it and/or modify it # under the terms of the GNU Library General Public License as publis...
#โปรแกรมหยิบสินค้าใส่ตระกร้า print("++++++++++++++++++++++++++++++++++++++++++++++++++++++") print("โปรดหยิบสินค้าใส่ตระกร้า") print("++++++++++++++++++++++++++++++++++++++++++++++++++++++") a = input("หยิบสินค้าครั้งที่ 1 :") b = input("หยิบสินค้าครั้งที่ 2 :") c = input("หยิบสินค้าครั้งที่ 3 :") d = input("หยิบสินค้...
def Main(operation): if operation == 1: return operation + 1 elif operation == 2: return operation + 1 elif operation == 3: return operation + 1 elif operation == 4: return operation + 1 elif operation == 5: return operation + 1 elif operation == 6...
from node import node class network(): #Constructor for the network def __init__(self, arch, start_weights): self.neurons = [] # Two dimensional array to hold all the neurons self.eta = 0.01 #Standard learning rate self.dimensions = arch # What the dimensions of each layer will be ...
from pecan import conf import os from deuce.tests import FunctionalTest from deuce.drivers.metadatadriver import MetadataStorageDriver, GapError,\ OverlapError from deuce.drivers.sqlite import SqliteStorageDriver from mock import MagicMock class SqliteStorageDriverTest(FunctionalTest): def create_driver(se...
# -*- coding:utf-8 -*- #例5.20训练3:高级 a = 1 print 'Cheers! ' while a<3: c = a print a b = 1 while b<4: c += a print c if a==1 and c>=4: print 'Let\'s do this some more! ' else: if a==2 and c>=8: print 'Who do we appreciate?' b += 1 a += 1
def main(): # Sum all numbers between 10 and 1,000 a = 10 b = 1000 total_sum = 0 while b >= a: total_sum += a a += 1 print(total_sum) if __name__ == '__main__': main()
cores = {'azul': '\033[1;34m', 'vermelho': '\033[1;31m', 'amarelo': '\033[1;33m', 'limpa': '\033[m', 'branco': '\033[97m', 'magenta': '\033[1;35m', 'black': '\033[1;30;107m'} print(' {}MEDIDAS E CLASSIFICAÇÕES DE TRIANGULOS{}'.format(cores['magenta'], cores['limpa'])) ...
# Generated by Django 3.0.5 on 2020-04-30 15:43 from django.conf import settings from django.db import migrations import django.db.models.deletion import django_currentuser.db.models.fields import django_currentuser.middleware class Migration(migrations.Migration): initial = True dependencies = [ m...
import math def f(x): return (x**4/500.000)-(x**2/200.000)-(3/250.000) def g(x): return -(x**3/30.000)+(x/20.000)+(1/6.000) n = 0.00001 #szer. prostokąta miarowego lewo = 2 #lewa krawędź figury gora = f(10) #górna krawędź figury dol = g(10) # dolna krawędź figury p1 = 0 #pole górnego obszaru figury p2 = 0 #po...
#!/usr/bin/env/ python3.6 # HW #L5.1 Matrix class Matrix: import random from functools import reduce def __init__(self, *args) -> None: if len(args) == 1: matrix = args[0] # Check matrix consistency # If all rows have equal length -> True if len...
import pytest from .data import temperatures from .task import get_temperature_closest_to_zero def test_get_temperature_closest_to_zero(): assert 0.5 == get_temperature_closest_to_zero(temperatures) assert get_temperature_closest_to_zero([]) == 0 assert get_temperature_closest_to_zero([-1, 2, 4, 0.2, 5, ...
#Done by Carlos Amaral (21/07/2020) from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die #Create a D6 die = Die() #Make some rolls and store the results in a list. results = [] for roll_num in range(1000): result = die.roll() results.append(result) #Analyse the results...
import MySQLdb import pandas as pd import numpy as np from datetime import datetime,date import fwm_config as fwm_config #from create_deviceid_program_matrix_primetime import get_all_program_listing #from create_deviceid_program_matrix_primetime import read_all_device_info #from create_deviceid_program_matrix_primeti...
def caesar_encryption(str,step): outtext=[] crypttext=[] uppercase = ['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'] lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', '...
import unittest from modules.User import * from modules.Role import * from main import * from unittest.mock import patch, Mock class TestSum(unittest.TestCase): @patch('main.getRoles') def test_set_user_successful(self, MockRoles): """ Test that it set valid set of users """ #...
islem = input("İslemi Giriniz:") sayi1 = int(input("Sayi1: ")) sayi2 = int(input("Sayi2: ")) if islem =="1": sonuc = int(sayi1) + int(sayi2) print("Sonuc: ", str(sonuc)) elif islem== "2": sonuc = int(sayi1) - int(sayi2) print("Sonuc: ", str(sonuc)) elif islem== "3": sonuc = int(sayi1...
"""The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.""" primeArray = [1]*2000000 for x in range(1,2000000): if primeArray[x] == 1: iteration = 2 while iteration*(x+1) <= 2000000: primeArray[iteration*(x+1)-1] = 0 iterati...
# Generated by Django 2.1.7 on 2019-03-06 00:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('AppTwo', '0003_auto_20190305_1931'), ] operations = [ migrations.AlterField( model_name='user', name='Email', ...
from plone.uuid.interfaces import IUUIDGenerator from zope.interface import implementer import uuid @implementer(IUUIDGenerator) class UUID4Generator: """Default UUID implementation. Uses uuid.uuid4() """ def __call__(self): return uuid.uuid4().hex
#! /usr/bin/env python # -*-coding: utf-8-*- from math import sqrt, tan class Hyperboloide(): ''' classe définissant une hyperboloide a deux nappes dans l'espace caractérisée par [*] son origine (Vector) [*] ses coefficients a,b et c ([int/float, int/float, int/float]) [*] son absorption aux couleurs RGB ([int,...
from django.contrib import admin from stackapi import models# Edit 7 # Register your models here. from .models import Question admin.site.register(Question) admin.site.register(models.User)# Edit 6
import os import pygame class Action: """ 角色基本活动 """ def __init__(self, path: str, prefix: str, image_count: int, is_loop: bool): """ 初始角色行为相关行为 :param path: 路径 :param prefix: 文件名前缀 :param image_count: 图片数量 :param is_loop: 是否循环显示 """ sel...
import requests from bs4 import BeautifulSoup from bs4 import Tag from database import insert_general_table counter = 0 def normalize_name(name): if ' lasts' in name: name = name.replace(' lasts', '') if ' last' in name: name = name.replace(' last', '') if '(hard)*' in name: name =...
#!/bin/python3 import sys def minimumAbsoluteDifference(n, arr): arr.sort() min_diff = abs(arr[0] - arr[1]) for i in range(2,n): diff = abs(arr[i-1] - arr[i]) min_diff = min(min_diff, diff) return min_diff if __name__ == "__main__": n = int(input().strip()) arr = list(map(int,...
import scaa import numpy as np import pytest @pytest.fixture def dims(): # Data (n, p); latent representation (n, d) n = 50 p = 1000 d = 20 stoch_samples = 10 return n, p, d, stoch_samples @pytest.fixture def simulate(): return scaa.benchmark.simulate_pois(n=30, p=60, rank=1, eta_max=3) @pytest.fixture...
valor=float(input("coloque o valor dos jogos a serem comprado")) quantidade=float(input("coloque a quantidade de jogos")) frete=float(input("coloque o valor do frete")) total=quantidade*valor+frete print(total)
# -*- coding: utf-8 -*- """ Created on Wed Nov 14 09:03:47 2018 @author: Home """ from keras.models import Sequential from keras.layers.core import Flatten, Dense, Dropout from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D from keras.optimizers import SGD from keras.preprocessing.image ...
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.r...
"""Get details for a hardware device.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers from SoftLayer import utils @click.command() @click.argument('identifier') @click.option(...
import sys from contextlib import contextmanager from types import TracebackType from typing import Any, Callable, Generator, Optional, Type from PyQt5 import QtWidgets from qt_material import apply_stylesheet from nitrokeyapp import get_theme_path from nitrokeyapp.gui import GUI from nitrokeyapp.logger import init_l...
import sys from collections import deque # 입력 받기 n = int(sys.stdin.readline()) m = int(sys.stdin.readline()) # 결혼식에 초대할 사람 목록 answer = [] # 친구 관계 그래프 생성 friends = [[] for _ in range(n+1)] for _ in range(m): a, b = map(int, sys.stdin.readline().split()) friends[a].append(b) friends[b].append(a) # BFS def...
# Generated by Django 2.2.4 on 2019-08-16 15:27 import django.contrib.postgres.fields import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields import phonenumber_field.modelfields import uuid class Mig...
import bpy from io_export_blend_to_renderer import pbrt from bpy.types import NodeTree, Node, NodeSocket import nodeitems_utils from nodeitems_utils import NodeCategory, NodeItem, NodeItemCustom import shutil import os # Node sockets def Pbrt_SocketRGBA(socket): value = socket.default_value return "\"rgb "+ ...
from tkinter import * root = Tk() w1 =Message(root,text='这是一则消息') w1.pack() w2 =Message(root,text='这是一则常常常常消息')# message 自动换行 跟text一样 w2.pack() w3 =Spinbox(root,from_=0,to=10) w3.pack() w4 =Spinbox(root,values=("鸭子","鸡儿","山羊")) w4.pack() def create(): top = Toplevel() #窗口里面弹出...
from tcp_latency import measure_latency import numpy as np import threading import time import pickle import matplotlib.pyplot as plt ip_addresses = [("New York", "162.243.19.47"), ("Greater Noida", "117.55.243.14"), ("Guangzhou", "202.46.34.74"), ("Chitose, Japan", "210.228.48.238"), (...
from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render from authapp import Forms from authapp import models from authapp.Forms import LoginForm from authapp.models import registers def home(request): return render(request,'index.html') ...
from django.db import models from base.models import BaseModel from django.contrib.auth.models import AbstractBaseUser, AbstractUser, BaseUserManager class UserManager(BaseUserManager): def create_simple_user(self, **kwargs): """ Creates a user object. Returns: ...
#coding: UTF-8 """ Test auth related api, such as login/logout. """ import random import re from urllib import urlencode, quote from tests.common.common import USERNAME, PASSWORD, SEAFILE_BASE_URL from tests.common.utils import randstring, urljoin from tests.api.urls import ( AUTH_PING_URL, TOKEN_URL, DOWNLOAD_RE...
# ========================================================================= # # Logtistic Regression # # Input: (36x36 + 1 Bias) *5 Classes = 1296 # Softmax Output = 5 Probabilities # parameters = 3485 # About 40% Accuracy ...
#Tessa Pierce #2.8.13 #Normalize counts in the count matrix exported by remove_low_counts.py #count matrix: contig \t sd2c \t sd3c \t br1c \t br2c \t ab1c \t ab2c \t scn1c \t scn2c \t pes1c \t pes2c \t bb1c \t bb2c \n ##RPKM = reads per kilobase per million mapped reads import sys #import numpy as np from optparse ...
#-*-coding:utf-8 -*- __author__ = 'Administrator' from jqdatasdk import * import pandas as pd from jqdatasdk import * import os from datetime import datetime,timedelta #授权 auth('13811866763',"sam155") ''' 一次性获取聚宽的财务数据,包括balance,case_flow,income,indicator表 目录在finance文件下,各子文件为'valuation', 'balance', 'cash_flow', 'inc...
#Reverse string s1=raw_input("Enter a String : ") s1=s1+" " s2=" " print "reverse string is =", for i in range(len(s1)-1,-1,-1): k=s1[i] print k,
x = int(input()) z = int(input()) cont = 0 while cont < 1: if z <= x: z = int(input()) else: cont += 1 soma = 0 cont2 = 0 cont3 = 0 while cont2 < 1: soma = soma + x if soma > z: cont2 += 1 cont3 += 1 x += 1 print(cont3)
class PretrainedConfig(object): pretrained_config_archive_map = {} # type: Dict[str, str] model_type = "" # type: str def __init__(self, **kwargs): pass
with open("CW2016_03.in", "r") as f: line = f.readline() count = int(line) for i in range(count): word = f.readline().strip() prev = word[0] likes = False for char in word[1:]: if prev == char: likes = True prev = char ...
def saveJumpLabel(asm, labelIndex, labelName, labelAddr): lineCount = 0 for line in asm: line = line.replace(" ", "") if (line.count(":")): labelName.append(line[0:line.index(":")]) # append the label name labelIndex.append(lineCount) # append the label's index\ ...
# 76. Minimum Window Substring # Given two strings s and t of lengths m and n respectively, # return the minimum window substring # of s such that every character in t (including duplicates) is included in the window. # If there is no such substring, return the empty string "". # The testcases will be generated suc...
# encondding = utf - 8 #用于实现具体动作,比如输入数据框 from selenium import webdriver from config.VarConfig import ieDriverFilePath from config.VarConfig import chromeDriverFilePath from config.VarConfig import firefoxDriverFilePath from util.ObjiectMap import getElement,getElements from selenium.webdriver.support.ui import Select f...
import socket import sys try: host = sys.argv[1] port = 25565 except IndexError: print "[+] Usage %s <host> " % sys.argv[0] print "[i] Example: mc_ddos.py localhost" sys.exit() #rootbuffer = "1000bc02093132372e302e302e3163dd020900076d65726b333630" #other buffer switch if you want to #rootbuffer ...
''' Created on Oct 24, 2016 @author: Noor Jahan Mukammel Program: set_method: remove(el) * works like discard() * but if el is not a member of the set * a KeyError will be raised. ''' x = {"a","b","c","d","e"} print(x.remove("a")) # difference_update() function returns "None" prin...
import threading import hashlib import json import sys from datetime import datetime, timezone from random import randint from collections import namedtuple import blockchain Headers = namedtuple('Headers', [ 'index', 'time', 'nonce', 'tx', 'mrkl_root', 'curr_hash', 'prev_hash' ]) class ...
import httplib import urllib import base64 import json import sys import settings from syslogger import logger def get_tags(data, conf_threshold=settings.confidence_threshold): tag_str = "" for tag in data["tags"]: if float(tag["confidence"]) >= conf_threshold: if tag_str != "": ...
from urllib2 import urlopen import json import statsmodels.api as sm import pandas from datetime import datetime import time from sqlalchemy import create_engine #SQLAlchemy might need to be installed and PyMYSQL import calendar def create_connection(): engine = create_engine('mysql+pymysql://aashu:aashu@local...
# Generated by Django 3.0.7 on 2021-07-13 16:29 from django.db import migrations, models import phonenumber_field.modelfields class Migration(migrations.Migration): dependencies = [ ('foodcartapp', '0045_auto_20210201_1929'), ] operations = [ migrations.AlterField( model_nam...
import pytest from mock import patch, Mock from processing.image_publishing import ImgPublisher from external_api.dbx import RussDropBox from external_api.gcp_pubsub import ImgPathPubisher @pytest.fixture def publisher(): yield ImgPublisher( RussDropBox('',True, 100), None) def test_should_skip_thumbnail(mocker)...
import numpy number= input( 'Enter number x: ') # '2' 2 number2= input('Enter number y: ') print('0076491')
tree = ["chapter 1", ["section 1.1", ["paragraph 1.1.1", "paragraph 1.1.2", "paragraph 1.1.3",], "section 1.2", ["paragraph 1.2.1",]], "chapter 2", ["section 2.1", ["paragraph 2.1.1", "...
# uncompyle6 version 3.7.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.8.5 (default, Aug 12 2020, 00:00:00) # [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] # Embedded file name: c:\Jenkins\live\output\Live\win_64_static\Release\python-bundle\MIDI Remote Scripts\ableton\v2\control_surface\elements\slider.py # ...
from django.db import models # Create your models here. class type(models.Model): category = models.CharField(max_length=64,null=False) class website(models.Model): url = models.CharField(unique=True,max_length=255,null=False) ip = models.CharField(default="0.0.0.0",max_length=32) port = models.Inte...
#https://www.hackerrank.com/challenges/angry-professor t = int(input()) for i in range(t): n, k = map(int, input().split()) arrived_time = list(map(int, input().split())) if n - len(list(filter(lambda n: n > 0, arrived_time))) < k: print("YES") else: print("NO")
import requests import json import random import execjs import pymysql import redis class IdSpider(object): def __init__(self): super().__init__() self.db = pymysql.connect(host='rm-wz9wj90j9qzcfasz6.mysql.rds.aliyuncs.com', user='root', port=3306, password='qazwsx12!@', ...
# Question2 n = int(input()) nums = list(map(int, input().strip().split())) nums = sorted(nums, reverse=True) if len(nums) == 0: print(0) niuniu, sheep = 0, 0 for i in range(len(nums)): if i & 1 == 0: niuniu += nums[i] else: sheep += nums[i] print(niuniu - sheep)
import os from flask_assets import Environment, Bundle assets = Environment() css = Bundle(os.getenv('CSS')) assets.register('css_min', css) favicon = Bundle('favicon.js') assets.register('favicon', favicon) js = Bundle(os.getenv('JS')) assets.register('scripts', js)
import json class Cfg: def __init__(self): f = open('cfg.json', ) data = json.load(f) rabbit_params = data['rabbitmq'] flask_params = data['flask'] music_server_params = data['music_flask_server'] self.rabbit_host = rabbit_params['host'] self.rabbit_port =...
# TREE:: rеprеsеnts thе nоdеs cоnnеctеd by еdgеs. # - Оnе nоdе is mаrkеd аs Rооt nоdе. # - Еvеry nоdе except thе rооt is аssоciаtеd with оnе pаrеnt nоdе. # - Еаch nоdе cаn hаvе аn аrbiаtry numbеr оf child nоdеs. # # BINARY TREE :: A tree whose elements have max two children is called a binary tree. # Each element in a...
def list_of_depths(tree): if not tree: return [] lists = [] queue = Queue() current_depth = -1 current_tail = None node = tree node.depth = 0 while node: if node.depth == current_depth: current_tail.next = ListNode(node.data) current_tail = current_tail.next else: current_d...
from distutils.version import LooseVersion from django.contrib.contenttypes.models import ContentType from django.db import models from django.contrib.auth.models import Permission class TruncatingCharField(models.CharField): def get_prep_value(self, value): value = super(TruncatingCharField,sel...
"""Setup module""" from setuptools import setup, find_packages # To use a consistent encoding from codecs import open # pylint:disable=W0622 from os.path import abspath, dirname, join README = join(abspath(dirname(__file__)), 'README.md') try: import pypandoc DESCRIPTION = pypandoc.convert(README, 'rst') exc...
#!/bin/env python # import pandas as pd import pandas.io.data as web from qrzigzag import peak_valley_pivots, max_drawdown, compute_segment_returns, pivots_to_modes X = web.get_data_yahoo('GOOG')['Adj Close'] pivots = peak_valley_pivots(X, 0.2, -0.2) ts_pivots = pd.Series(X, index=X.index) ts_pivots = ts_pivots[pivots...
# Generated by Django 2.2 on 2019-04-26 09:09 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...