text
stringlengths
8
6.05M
__all__ = ["add", "multi"] print("add module imported")
__author__ = 'Anton Vakhrushev'
"""Plot saliency maps """ import tensorflow as tf import numpy as np import keras.backend as K from keras.layers import Input, Lambda, Conv2D from keras.applications import inception_v3 from scipy.ndimage import imread, zoom from scipy.misc import imresize import matplotlib.pyplot as plt def get_saliency(image,model):...
# Generated by Django 3.2.7 on 2021-09-03 16:28 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main_app', '0004_photo'), ] operations = [ migrations.RenameField( model_name='photo', old_name='cat', new_name=...
def calc(num1,num2): """This function adds two numbers""" print("the total is",num1+num2) while(1): try: print("Enter first number\n") x=int(input()) break continue except Exception as e: print("Enter correct value") print(e) print("Enter second number\...
from django.conf.urls import url from django.contrib import admin from .views import ( addStockCode, showStockInfo, ) urlpatterns = [ url(r'^addStockCode/$', addStockCode, name='addStockCode'), url(r'^showStockInfo/$', showStockInfo, name='showStockInfo'), ]
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ import itertools def read(n): s = "" for k, v in itertools.groupby(str(n)): s += str(len(list(v))) + k print s return s ...
import math class Solution: def checkPerfectNumber(self, num): """ :type num: int :rtype: bool """ if num <= 1: return False root = int(math.sqrt(num)) divisors = [1] i = 2 while i <= root: if num%i == 0: ...
n=int(input('Enter the value of n')) sum=0 for i in range(1,n+1): sum+=i print('Sum=',sum)
from ActionsAnalysis import * import numpy as np import time for fileName in ['new/dummy_eliiradariamoshelenaido_pu1.0_single_100_norm']: for epochs in ['100','200']: aa = ActionsAnalysis(expDir = fileName) print 'loading' #~ try: #~ aa.l...
# -*- coding: utf-8 -*- # Author: kelvinBen # Github: https://github.com/kelvinBen/HistoricalArticlesToPdf
# -*- coding: utf-8 -*- """This is the entry point of the program.""" def detect_language(text, languages): """Returns the detected language of given text.""" counter = 0 select_lang = None for language in languages: num_of_words = len([word for word in language['common_words'] if word in text...
import numpy as np from GeoToolkit.Mag import Simulator, DataIO, MathUtils, Mag # from SimPEG import PF, Utils, Mesh, Maps import ipywidgets as widgets from matplotlib.patches import Rectangle import matplotlib.pyplot as plt from scipy.interpolate import griddata, interp1d from scipy.interpolate import NearestNDInterp...
# %% import numpy as np import csv import time import threading from keras import models, backend from keras.utils import to_categorical test_data = [] test_labels = [] def evaluate(model='123.h5', valve=15000): network = models.load_model(model) with open('test_data.csv', 'r', newline='') as csvfile: ...
#!/usr/bin/env python3 # coding: utf-8 # pylint: disable=C0103,C0111,R0201,E1101 # Romain Vincent, GetWatuAsk """Routes for the app.""" import datetime as dt import smtplib from flask import Flask, redirect, url_for, request, render_template, session import data_query as db app = Flask(__name__, static_url_path='/s...
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2020 Kari Kujansuu # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) an...
import doctest def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite("kspalculator.techtree")) return tests
from etl import ETLPipeline from etl_for_summary import ETLPipelineSummary import pandas as pd def run_etl_Rome_summary_without_extraction(): etl = ETLPipelineSummary("Dataset_summary\ROM\\","") etl.run_without_extraction() def run_etl_Rome_summary(): etl = ETLPipelineSummary("Dataset_summary\ROM\\","htt...
from django import forms from django.contrib.auth.forms import UserCreationForm from .models import User, Contact, PlayerMore, CoachMore from django.forms import widgets class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required. Add a vaild email address') class M...
name_to_abbrev = {'arizonadiamondbacks': 'ARI', 'atlantabraves': 'ATL', 'baltimoreorioles': 'BAL', 'bostonredsox': 'BOS', 'chicagowhitesox': 'CHW', 'chicagocubs': 'CHC', 'cincinnatireds': 'CIN', 'clevelandindians': 'CLE', 'coloradorockies': 'COL', 'detroittigers': 'DET', 'houstonastros': 'HOU', 'kansascityroyals': 'K...
import csv import sys ip_dict = {} # {ip address: email} name = {} # {ip address: name} file = 'test.csv' # data has fields ip,name,email # populate ip_dict and name dictionaries with open(file,'r') as inputFile: data = csv.DictReader(inputFile, delimiter = ',') # skip header row next(data) # populate ip dictio...
# -*- coding: utf-8 -*- # @Author: jpch89 # @Time: 18-8-24 下午5:09 class A: # def go(self): # return object() def __call__(self): return object() class B: def run(self): return object() def func(): return object() def main(call_able): call_able() # 想在 main 中调用传入的...
#__init__.py # use this file # from [file name] import [function name] # so, main.py writedown ' from MMmodule import call_cmd_normal # and, use any function!! #from MMlib_system import call_cmd_normal,call_cmd_pipe
# Generated by Django 2.1.3 on 2018-11-23 08:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.AlterField( model_name='author', name='name', field=...
""" smorest_sfs.modules.projects.resource ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 项目的资源模块 """ from typing import Any, Dict, List from flask.views import MethodView from flask_sqlalchemy import BaseQuery from loguru import logger from flask_jwt_extended import current_user from smorest_sfs.extensions.ap...
def main(): # dados da Penny nome = "Penny" sexo = "feminino" altura = 167 peso = 52 idade = 25 cabelo = "loiro" escolaridade = "medio" compativel = sexo == 'feminino' and (peso >= 45 and peso <= 65) and (altura >= 155 and altura <= 170) and (25 <= idade <= 35) and cabelo =...
""" Aprimore o desafio anterior, mostrando no final: A - A soma de todos os valores pares digitados. B - A soma dos valores da terceira coluna. C - O maior valor da segunda linha. """ matriz = [[], [], []] valor = 0 soma = soma3 = maior1 = 0 for i in range(0, 3): for j in range(0, 3): valor = int(input(f'...
import pygame import util import physics from display import Display import random import colors import time class Game: def __init__(self): pygame.init() self.spawning_interval = util.spawning_interval # If this is true, we have just a blank screen and the ball. For playing # around with the physics...
from csv import DictReader from datetime import date from datetime import datetime from decimal import Decimal from freezegun import freeze_time from io import BytesIO from io import StringIO from onegov.core.orm.abstract import MoveDirection from onegov.swissvotes.collections import SwissVoteCollection from onegov.swi...
from django.contrib import admin from authors.apps.reports.models import ReportArticle # Register your models here. admin.site.register(ReportArticle)
#!/usr/bin/python2 #-*- coding:utf-8 -*- import MySQLdb import logging from pprint import pprint from datetime import timedelta from datetime import datetime logger = logging.getLogger(__name__) def get_conn(host,user,passwd,db): try: conn = MySQLdb.connect(host=host,user=user,passwd=passwd,db=db) exc...
import os.path from jinja2 import Environment, FileSystemLoader import py.path def generate_static(tmpl_path, out_path): jinja_env = Environment(loader=FileSystemLoader(str(tmpl_path))) site_path = tmpl_path.join('site') if os.path.exists(str(out_path)): out_path.remove() out_path.mkdir() ...
from openspending.ui.test import helpers as h h.skip("Not yet implemented.")
class Book: def __init__(self, book_id, book_name, details, author): self.book_id = book_id self.book_name = book_name self.details = details self.author = author
import os import utils import nltk from loguru import logger from pathlib import Path class Glove(): def __init__(self, dataset_name) -> None: input_file_path = 'input/' + dataset_name + '/raw.txt' if not os.path.isfile(input_file_path): raise Exception('Could not find ' + input_file_pa...
import numpy as np import matplotlib.pyplot as plt x=[] y=[] bigx=[] bigy=[] def func1(r1,r2,d): global x,y x=list(np.arange(r1,r2,d)) y=list(range(len(x))) for i in range(len(x)): z=[] s=0.5 for j in range(70): s=x[i]*s*(1-s) if j>=50: ...
import webapp2 import os import jinja2 import json import datetime import time import urllib import urllib2 import soundcloud import sys import random import math from google.appengine.ext import db from google.appengine.api import memcache, urlfetch from google.appengine.api.urlfetch import fetch from secret import cl...
def findall(pattern, string_to_search_in: str): """ Yields all the positions of the pattern p in the string s. """ i = string_to_search_in.find(pattern) while i != -1: yield i i = string_to_search_in.find(pattern, i + 1)
'''Use this for development''' from .base import * from decouple import config import dj_database_url ALLOWED_HOSTS += ['127.0.0.1'] DEBUG = True WSGI_APPLICATION = 'home.wsgi.dev.application' DATABASES = { 'default': dj_database_url.config(default=config('DATABASE_URL')) } CORS_ORIGIN_WHITELIST = ( 'http:...
import unittest import time from BSTestRunner import BSTestRunner ''' # @Author : minpanpan # @content : python自带的unittest测试框架 # @File : run.py # @Software: PyCharm suite = unittest.TestSuite()#创建测试套件 all_cases = unittest.defaultTestLoader.discover('.','test_*.py') #找到某个目录下所有的以test开头的Python文件里面的...
import io, os, argparse, random, statistics, codecs if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input', type = str, help = 'input to language folder (e.g. persian)') parser.add_argument('--output', type = str, help = 'output file for descriptive statistics') parser.add_ar...
# coding: utf-8 """ Lilt REST API The Lilt REST API enables programmatic access to the full-range of Lilt backend services including: * Training of and translating with interactive, adaptive machine translation * Large-scale translation memory * The Lexicon (a large-scale termbase) * Programmatic cont...
''' To-do : If points <=1024, add random noise for points >2048, split into two in both cases, make sure the labels and indices are also taken care ''' from airplane_kd_helpers import * import glob import numpy as np import os class_names = { "02691156":"Airplane_02691156", "02773838":"Bag_02773838", "02954340":"Cap...
# -*- coding: utf-8 -*- from tkinter import * from getFiles import get_file_size import picture_factory RESULT_DELETE = -2 RESULT_SKIP = -1 RESULT_RENAME = 1 RESULT_REPLACE = 2 class Preview: def set_photos(self, new_photo1=None, new_photo2=None, size=None): if size: self.__size = s...
import json import os import sys DEFAULT_OPTION_FILE = 'option.json' ERROR_FORMAT = '\n* ERROR: [%s] [%s]\n' class Option: def __init__(self): self.option = '' self.source_path = '' def get_option(self): return self.option def set_option(self): if not os...
print "hello" """ Material from James' Discussion * Open Office Hours *Every* Tuesday at the NYC Python Meetup * Python has particular libraries that add tremendous values * Python is: * Readable * Highly restrictable * Coordinating a number of pieces * Exceptionally performant * A model for OOP in Python ...
""" Given an array of points where points[i] = (xi,yi) represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0,0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., √((x1 - x2)2 + (y1 - y2)2)). You may return the answer in any order. The answe...
from datetime import timedelta, datetime import numpy as np class Video: title ="" url = "" description = "" #feature viewCount = 0 likeCount = 0 dislikeCount = 0 commentCount = 0 thumbnailUrl = "" publishedAt = datetime.now postedTime = timedelta(days=1) #calculation ...
from sense_hat import SenseHat, ACTION_PRESSED from time import sleep import requests import json red = [255, 0, 0] green = [0, 255, 0] sense = SenseHat(); redMatrix = [red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red, red...
from collections import deque class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def __str__(self): return 'TreeNode({!r})'.format(self.val) def __repr__(self): return self.__str__() def from_list(lst): """ Co...
""" foxtail/appointments/views.py """ from django.shortcuts import redirect, render from django.views.generic import TemplateView, UpdateView from .models import Appointment def AppointmentWaiverUploadView(request, token): appointment = Appointment.verify_waiver_upload_token(token) # Get the relevant Appointme...
from pkg_resources import resource_filename # @UnresolvedImport from tornado.web import RequestHandler import cairosvg import json import os class ColoursHandler(RequestHandler): ''' returns a .png for an svg template ''' def get_template_path(self): ''' overrides the template path to use this modul...
# -*- coding: utf-8 -*- # @Author: vivekpatel99 # @Date: 2018-10-06 15:44:29 # @Last Modified by: vivekpatel99 # @Last Modified time: 2018-10-06 15:44:29 """ This script intializes the logger and contains all the info and functions for logger """ import logging # ------------------------------------------------...
#!/usr/bin/python #\file slider_style1.py #\brief Test styles of slider. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Apr.15, 2021 import sys from PyQt4 import QtCore,QtGui #from PyQt5 import QtCore,QtWidgets #QtGui= QtWidgets def Print(*s): for ss in s: print ss, print '' try: ...
""" Time/Space Complexity = O(N) """ class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ if not nums or not k: return nums k = k % len(nums) out = [0]*len(nums)...
import re from ctypes import ( c_int, c_long, c_longlong, c_uint, c_ulong, c_ulonglong, c_float, c_double, c_char, c_char_p, ) from twitter.common.lang import Compatibility class ScanfResult(object): def __init__(self): self._dict = {} self._list = [] def groups(self): """ ...
#!/usr/bin/env python3 # Created by: Crestel Ong # Created on: Sept 2021 # This programs calculates the perimeter of a hexagon # user inputs the length of one side import constants def main(): # main function print("We will be calculating the perimiter of a hexagon.") # input print("") side...
from functools import reduce from function import * from utils import * from splines_interpolation import spline_intepolation_coefs, spline_interpolation def generate_grid(n, x_start, x_end, y_start, y_end): x = find_equally_spaced(x_start, x_end, n) y = find_equally_spaced(y_start, y_end, n) return (x, ...
class PurchasedGood: def __init__(self, price, category = "General", tax = 0.07): self.price = price self.category = category self.tax = tax def calculate_total(self): total = round(self.price+(self.price*self.tax), 2) return total good_1 = PurchasedGood(5.00) print(good_1...
#.-*- coding:utf-8 .-*- import sys import pika def Main(): connection=pika.BlockingConnection(pika.ConnectionParameters("localhost")) channel=connection.channel() routing_key=sys.argv[1] if len(sys.argv)>1 else "test" message=sys.argv[2:] if len(sys.argv)>2 else "test words" message_str=" ".join(me...
from espnffl import FFLeague lg = FFLeague('BTownsFinest', 1083362)
import unittest import numpy as np import pyqg class LayeredModelTester(unittest.TestCase): def setUp(self): self.m = pyqg.LayeredModel( nz = 3, U = [.1,.05,.0], V = [.1,.05,.0], rho= [.1,.3,.5], H = [....
from django.conf import settings from django.urls import reverse from allauth.account.adapter import DefaultAccountAdapter from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class AccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request): return getattr(settings, "AC...
from adapters.adapter_with_battery import AdapterWithBattery from devices.sensor.smoke import SmokeSensor class GasSensorAdapter(AdapterWithBattery): def __init__(self, devices): super().__init__(devices) self.devices.append(SmokeSensor(devices, 'gas', 'gas'))
import pandas as pd DIR = "/data/damoncrockett/flickr_data/" TAGS = DIR + "raw/autotags/" ASTRO = DIR+"astrophotography/" DATA = ASTRO + "astro_tag_exif.csv" df = pd.read_csv(DATA) ids = list(df['id']) import os import glob counter = -1 for file in glob.glob(os.path.join(TAGS,"*")): tmp = pd.read_table(file,s...
import pymysql from Database import Database database = Database() _host = database.gethost() _port = database.getport() _sql_user = database.getuser() _sql_password = database.getpassword() _database = database.getdatabase() # get username:string,password:string,useremail:string, return id def register(login_name,...
#encoding:utf-8 import urllib import urllib2 import re import thread import time URL = 'http://www.qiushibaike.com/hot/page/' class Qsbk: """docstring for Qsbk""" def __init__(self): self.pageIndex = 1 self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' self.headers = { 'User-Agent' : self.user...
# Generated by Django 2.2.4 on 2019-12-01 16:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('school', '0010_auto_20191201_1353'), ] operations = [ migrations.AlterField( model_name='career', name='time', ...
# -*- coding: utf-8 -*- # 同餘式求解 # 任意模的同餘式的求解 from .NTLChineseRemainderTheorem import CHNRemainderTheorem from .NTLCongruenceSimplification import congruenceSimplification from .NTLExceptions import SolutionError from .NTLGreatestCommonDivisor import greatestCommonDivisor from .NTLPrimeFactorisatio...
from sqlalchemy import create_engine, Integer, ForeignKey from sqlalchemy import Column, String, Boolean, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.sql import func class IssuesDb(): def __init__(self, db_type, user_name, ...
# 함수명: print_book_title, 매개변수: 없음, 리턴값: 없음 # 기능: 파이썬 교재명을 화면에 출력 def print_book_title() : print('파이썬 정복') # 함수명: print_book_publisher, 매개변수: 없음, 리턴값: 없음 # 기능: 파이썬 교재의 출판사명을 화면에 출력 def print_book_publisher() : print('한빛미디어') # print_book_title() 함수를 3회 호출하고 print_book_title() print_book_title() print_book_title...
import os print gv.InstrumentMgr ##print [h.name() for h in gv.InstrumentMgr._instrumentHandles] ## print os. print os.path.isfile('dummy.py') print os.path.exists('dummy.py') ## print gv.InstrumentMgr.loadInstrument(name=None, server=None, moduleFileOrDir='dummy.py', args=[], kwargs={}, new=False, forceReload=False)
# Tasks # Clean the data by replacing any missing values and removing duplicate rows. # In this dataset, each customer is identified by a unique customer ID. # The most recent version of a duplicated record should be retained. # Explore the data by calculating summary and descriptive statistics for # the feat...
class Process: identifier = None title = None abstract = None language = None inputs = {} outputs = {} __inputs_defs__ = {} __outputs_defs__ = {} def __init__(self, identifier, title = None, abstract = None, inputs = None, outputs = N...
from onegov.core.orm.types import UTCDateTime from sedate import to_timezone from sqlalchemy import Column from sqlalchemy import String from sqlalchemy import Text from sqlalchemy.dialects.postgresql import HSTORE from sqlalchemy.ext.mutable import MutableDict class OccurrenceMixin: """ Contains all attributes e...
# 19 May 2021 from datetime import datetime from datetime import timedelta # user input request format in 20 Dec 1978 date_input = input("Please enter you DOB in the format DD Mmm YYYY: ie. 20 Dec 1978") # cast to a datetime object date_object = datetime.strptime(date_input, '%d %b %Y') # output some confirmation...
# Generated by Django 3.0.2 on 2020-03-28 14:38 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('account', '0006_auto_202...
import numpy as np from sklearn.datasets import load_iris from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC, SVC from sklearn.neighbors import KNeighborsClassifier from sklearn...
#this file should come after the bgprocess to show the questions in the time defined in trigger from the tempdata.csv temporary file #it should not open more than once for the same question #it should open a prompt ask the question, retrieve info and add it to the major diary.txt file. #And then clean the datatemp f...
import numpy as np from cs285.infrastructure import pytorch_util as ptu from .base_policy import BasePolicy from torch import nn import torch import pickle def create_linear_layer(W, b) -> nn.Linear: out_features, in_features = W.shape linear_layer = nn.Linear( in_features, out_features, ...
from onegov.core.templates import render_macro from onegov.landsgemeinde.layouts import DefaultLayout from onegov.landsgemeinde.models import AgendaItem from onegov.landsgemeinde.models import Assembly from onegov.landsgemeinde.models import Votum from re import sub def update_ticker(request, assembly, agenda_item=No...
import os from day_6 import main current_dir = os.path.dirname(os.path.abspath(__file__)) test_input_file = os.path.join(current_dir, 'test_input.txt') def test_transform_input(): expected_list = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"], ["a"], ["b"]] returned_dict = main.transform_input(test_inpu...
import math, random import numpy as np def sample_from_gaussian_mixture(batchsize, n_dim, n_labels): if n_dim % 2 != 0: raise Exception("n_dim must be a multiple of 2.") def sample(x, y, label, n_labels): shift = 1.4 r = 2.0 * np.pi / float(n_labels) * float(label) new_x = x * math.cos(r) - y * math.sin(r) ...
# -*- coding: UTF-8 -*- import sys, os sys.dont_write_bytecode = True import shutil def listFile(dir, nameList) : assert(os.path.isdir(dir)) for f in os.listdir(dir) : p = os.path.join(dir,f) if os.path.isfile(p) and f.endswith('.sc') : nameList.append(p[2:].replace('\\', '/')) elif os.path.isdir(p) : l...
''' Problem Statement Given an unsorted array of numbers, find the top ‘K’ frequently occurring numbers in it. Example 1: Input: [1, 3, 5, 12, 11, 12, 11], K = 2 Output: [12, 11] Explanation: Both '11' and '12' apeared twice. Example 2: Input: [5, 12, 11, 3, 11], K = 2 Output: [11, 5] or [11, 12] or [11, 3] Explan...
# -*- coding: utf-8 -*- import requests import time import json import os def currentblock(akey): # pulls current block number from API try: response = requests.get('https://api.polygonscan.com/api?module=proxy&action=eth_blockNumber&apikey=' + akey) data = int(response.json()['result'][2:], 1...
# The Python list object is the most general sequence provided by the language. Lists arepositionally ordered collections of arbitrarily typed objects, and they have no fixed size.They are also mutable—unlike strings, lists can be modified in place by assignment tooffsets as well as a variety of list method calls. Acco...
# Generated by Django 3.2.5 on 2021-07-29 07:10 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='appointment', fields=[ ('id', models.AutoFi...
import pyalps import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pyalps.plot import numpy as np import pyalps.fit_wrapper as fw from math import sqrt #prepare the input parameters parms = [] for j2 in [0.,1.]: for t in np.linspace(0.01,1.0,20): parms.append( { ...
import os def get_root(): this_folder = os.path.dirname(__file__) root_folder = os.path.realpath(f'{this_folder}/..') return root_folder
import mlrose_hiive import numpy as np import datetime import matplotlib.pyplot as plt from util import generate_graph """ np.random.seed(SEED) N = 20 fitness = mlrose.Knapsack(weights=np.random.uniform(size=N), values=np.arange(1, N+1, 1),max_weight_pct=0.8) problem_fit = mlrose.DiscreteOpt(length = N,fitness_fn = fi...
#!/usr/bin/python2.7 import xml.etree.ElementTree as ET from urllib2 import urlopen import datetime from time import time import os.path data_path = os.path.expanduser('~/bus/data') uts_url = 'http://uts.pvta.com:81/InfoPoint/map/GetVehicleXml.ashx?RouteId=%s' ntf_url = 'http://ntf.pvta.com:81/InfoPoint/map/GetVehicl...
""" DS=int(input("Enter the marks")) Micro=int(input("Enter the number")) Al=int(input("Enter the marks")) Java=int(input("Enter the marks")) net=int(input("Enter the marks")) n=(DS+Micro+Al+Java+net)*100/500 if 0<=n<40: print("D") elif 40<=n<60: print("C") elif 60<=n<70: print("B") elif 70<=n<80: pri...
import random import math import pygame from pygame.locals import * from items.armor import base as armor from items.weapon import base as weapon class baseEnemy(object): def __init__(self, name, lvl, hostile, x, y, img, ID): self.name = name self.lvl = lvl self.img = pygame.image.load(img).convert_alpha() s...
# Generated by Django 3.0.8 on 2020-07-23 17:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trips', '0005_auto_20200723_2323'), ] operations = [ migrations.RemoveField( model_name='trip', name='status', ...
class Solution: def multiply(self, num1: str, num2: str) -> str: res = '' if num1 == '0' or num2 == '0': return '0' lastsum = 0 for lastnum in num2[::-1]: nowji = int(num1) * int(lastnum) nowsum = nowji + lastsum res = f"{nowsum % 10}" ...
modo = raw_input("Cifrar(c) o descifrar(d)?: ") cesar = input("Numero cesar: ") cad = raw_input("Introduce cadena:") def accion(modo, cadena, cesar): """Realiza el cifrado o descifrado de la cadena segun la eleccion del usuario""" cifrado = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",...
def formatuj(*args, **kwargs): lista = [] wynik ='' for i in args: for k, v in kwargs.items(): if f'${k}' in i: lista.append(i.replace(f'${k}',str(v))) for i in lista: if lista.index(i) == len(lista)-1: wynik += i break wynik +=...
#!/bin/python3 import sys # Grab the number of test cases t = int(input().strip()) for a0 in range(t): # Grab current test's set limit (n) and integer limit (k) n,k = map(int, input().strip().split(' ')) # Loop over all combinations of a&b and print the largest value under k currMax = 0 for a in ...
from base64 import b64encode from IPython.display import HTML from PIL import Image from tqdm import tqdm import cv2 import numpy as np import os # helper function to display video def display_avi_video(path): '''Display video in Colab.''' compressed_path = path.split('.')[0] compressed_path = ...