text
stringlengths
38
1.54M
import os from collections import namedtuple def on_github_action(): """ Examples -------- >>> import os >>> >>> os.environ["GITHUB_ACTION"] = "true" >>> on_github_action() True """ return "GITHUB_ACTION" in os.environ def get_action_input(name): """ Examples ---...
#!/usr/bin/env python #--------------------------------------------------------------------------------------- # Load configuration values # #--------------------------------------------------------------------------------------- # see https://wiki.python.org/moin/ConfigParserShootout from configobj import ConfigObj ...
""" Write a program which asks the user to enter their first name and two numbers. The program will then display the relationship between the two numbers. The program should display the message Please enter your first name: followed by Hi <FirstName>, please enter the first number: followed by Thank you. Please ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys class Solution: def abs(self, v): return (1, v) if (v > 0) else (-1, -v) def filter_rst(self, r): if r > 0: return r if (r < 2147483647) else 2147483647 else: return r if (r > -2147483648) else -2147483648...
from route4me import Route4Me KEY = "11111111111111111111111111111111" def main(): route4me = Route4Me(KEY) address_book = route4me.address_book response = address_book.create_contact( first_name="Juan", last_name="Pimentel", address_1="17205 RICHMOND TNPK, MILFORD, VA, 22514", ...
from django.urls import path from .views import * from django.views.decorators.csrf import csrf_exempt urlpatterns=[ path('',csrf_exempt(login_view),name="login"), path('register',csrf_exempt(register_view),name="register"), path('logout',csrf_exempt(logout_view),name="logout"), ]
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import time from noodleFramework import get, post from models import User, Blog @get('/') async def index(request): blogs = [ Blog(id='1', title='你好', created_at=time.time() - 120), Blog(id='2', title='世界', created_at=time.time() - 3600) ] re...
from django.contrib import admin from solos.models import Solo class SoloAdmin(admin.ModelAdmin): model = Solo list_display = ['track', 'artist', 'get_duration'] # def get_duration(self): # return self.model.get_duration() admin.site.register(Solo, SoloAdmin)
from log import Log from sentence import Sentence class Palindrome: cache = {} def __init__(self, text): self.sentence = Sentence(text) self.ordinary_index = 0 self.opposite_index = self.sentence.length - 1 self.half_way_index = round(self.opposite_index / 2) def _increme...
# Randomly fills an array of size 10x10 with 0s and 1s, and outputs the number of blocks # in the largest block construction, determined by rows of 1s that can be stacked # on top of each other. # # Written by *** and Eric Martin for COMP9021 from random import seed, randrange import sys dim = 10 def display_gri...
def solution(key, lock): answer = True return answer key = [[0, 0, 0], [1, 0, 0], [0, 1, 1]] lock = [[1, 1, 1], [1, 1, 0], [1, 0, 1]] alock = [] bkey = [] n = len(key) for i in range(3): for j in range(3): if lock[i][j] == 0: n, m = i, j alock.append([n, m]) if ke...
from playsound import playsound import sys import speech_recognition as sr import time import webbrowser import os.path import os def amadeus_command(): r = sr.Recognizer() with sr.Microphone() as source: print('한국어로 말하세요') audio = r.listen(source) try: print("당신은 말했...
import os import base64 from flask import Flask, render_template, request, redirect, url_for, session from passlib.hash import pbkdf2_sha256 from model import Donation, Donor app = Flask(__name__) app.secret_key = os.environ.get('SECRET_KEY').encode() @app.route('/') def home(): return redirect(url_for('login')...
#!/usr/bin/env python import json import os import sys import subprocess docker_image_cmd = ['docker', 'ps', '--format', '{{.Names}} {{.ID}}'] docker_images_output = subprocess.check_output(docker_image_cmd, encoding='utf-8')[:-1] docker_images = {line.split()[0]: line.split()[1] for line in docker_images_output.split...
"""Unit test for Scene objects.""" import asyncio import unittest from unittest.mock import patch from xknx import XKNX from xknx.devices import Scene from xknx.dpt import DPTArray from xknx.telegram import GroupAddress, Telegram class TestScene(unittest.TestCase): """Test class for Scene objects.""" # pyl...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.contrib.loader.processor import TakeFirst, Join from mongoengine import * class ItemModel(Document): @classmethod def from_item(cls...
from .queue_with_stacks import Queue as z import pytest @pytest.fixture def empty_q(): return z() @pytest.fixture def small_q(): return z([1, 2, 3, 4]) @pytest.fixture def small_z(): return z([]) def test_constructor(empty_q): """ test constructor """ assert empty_q._len == 0 def test_enqu...
import numpy as np from nbodykit.lab import * from numpy.linalg import inv import scipy.integrate as integrate import math import scipy.optimize as op from scipy.optimize import curve_fit import numpy.linalg as linalg from multiprocessing import Pool import tqdm import h5py from configobj import ConfigObj from scipy.in...
#!/usr/bin/python import matplotlib.pyplot as plt def transform(track, handle): arr = [] with open(track, "r") as f: next(f) for line in f: curv = float(line.strip()) if curv != -1.0: vmax = (handle * curv/1000000)**0.5 else: vmax = 1000 arr.append(vmax) x = [i for i in range(1000)] plt.pl...
#!/usr/bin/env python ### Author: # Nam Thi # Caitlin C. Bannan (bannanc@uci.edu) # Victoria Lim (limvt@uci.edu) ### Description: This Python script minimizes mol2 files in the # given directory with the specified force field. Minimizations # are completed with the ffld_server utility from Schrodinger. # Fo...
import numpy as np import matplotlib.pyplot as plt #COFICOSTFUNC Collaborative filtering cost function # [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ... # num_features, lambda) returns the cost and gradient for the # collaborative filtering problem. # def cofiCostFunc(params, Y, R, num_...
def solution(): n = int(input()) l = list(map(int, input().split())) dic = {e:set() for e in range(1, len(l)+1)} for start, end in enumerate(l): dic[start+1].add(end) left_to_go = [True for _ in range(len(l)+1)] answer = 0 for first_start in range(1, len(l)+1): if le...
""" Bubble sort or selection sort is less efficient than merge sort, time complexity is O(n^2) in average case. """ def sort_array(my_list): """sort array or bubble array""" for j in range(len(my_list) - 1): for i in range(len(my_list) - j - 1): if my_list[i] > my_list[i + 1]: ...
from django.contrib import admin from .models import Plant, Post admin.site.register(Plant) admin.site.register(Post)
import os DEBUG = True SECRET_KEY = "fortestpurpose" STATUS = "TEST" #STATUS = "PROG" # Prod # SQLALCHEMY_DATABASE_URI = "postgres://cyhreifgcgqfbp:9a70ab4a858015cbeafdcdab9f69729b30f0c511c4c5aa65b9eb9f86afaaf8b6@ec2-184-72-236-3.compute-1.amazonaws.com:5432/dopb1f7u81aml" # SQLALCHEMY_TRACK_MODIFICATIONS = True ...
from typing import List from datahub.ingestion.api.common import RecordEnvelope, WorkUnit from datahub.ingestion.api.sink import Sink, SinkReport, WriteCallback from datahub.ingestion.run.pipeline import PipelineContext class RecordingSinkReport(SinkReport): received_records: List[RecordEnvelope] = [] def r...
# for item in 'python': # print(item) # for item in ['steve', 'john', 'sarah']: # print(item) # for item in [1, 2, 3, 4]: # print(item) # for item in range(5, 10, 2): # print(item) # exercise prices = [10, 20, 30] for price in prices: print(sum(prices)) break
#coding:utf-8 import smtplib from diff_file import betweenDiff from email.mime.text import MIMEText mail_user = 'xxxxxxxx@qq.com' mail_pass = 'nsqfcdmatzdhbjbe' mail_server = 'smtp.qq.com' mail_port = 465 to_user = 'xxxxxx@rongchat.com' def send_mail(title,content): #创建一个实例,这里设置为html格式邮件 msg = MIMEText(conte...
""" Tests of input/output. :Author: Jonathan Karr <karr@mssm.edu> :Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu> :Date: 2016-11-10 :Copyright: 2016-2018, Karr Lab :License: MIT """ from obj_tables import utils from test.support import EnvironmentVarGuard from wc_lang import (Model, Taxon, TaxonRank, Submodel, Re...
# -*- coding: utf-8 -*- """ Created on Sun Nov 26 15:57:32 2017 @author: Administrator """ from numpy.random import rand#使用import导入模块numpy import matplotlib.pyplot as plt#使用import导入模块matplotlib.pyplot import plotly as py # 导入plotly库并命名为py # -------------pre def pympl = py.offline.plot_mpl # 配置中文显示 plt.rcParams['font...
import sys from random import randint import copy def find_rand_node(input_array): first_node = input_array.keys()[randint(0, len(input_array) - 1)] second_node = input_array[first_node][randint(0, len(input_array[first_node]) - 1)] return first_node, second_node def karger_min_cut(input_array): input_copy = c...
import random import albumentations as A import cv2 import numpy as np from albumentations.augmentations.functional import clipped @clipped def random_contrast_gray(img, alpha): gray = ((1.0 - alpha) / img.size) * np.sum(img) return alpha * img + gray class RandomContrastGray(A.ImageOnlyTransform): """...
#!/usr/bin/env python ''' Renames sequences in a fasta formatted file. Magic Blast cuts the read name at the first space character and reports the name before the space as the query ID. However, fasta files can be named as: >D00468:261:HYTMHBCX2:1:1101:9119:31637 1:N:0:CAGAGAGG+ACTGCATA >D00468:261:HYTMHBCX2...
import numpy as np n = 1000 Q = np.genfromtxt('ab_data.csv',delimiter=',') Q = np.reshape(Q,(n,5)) index = 0 batch_size = 2 def RealAnswer(q_in): #Contains Logic to make the real answer from the question #for now, just adding 2 to every word (annoying right?) #a one hot answer! key = 1*np.ones_like(...
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to ...
problem = 'A' input = open('%s.in'%problem, 'r') def tokenize(file): for line in file: for token in line.split(' '): yield token output = open('%s.out'%problem, 'w') tokens = tokenize(input) OUT = lambda s: output.write(str(s)+'\n') INT = lambda : int(next(tokens)) N = INT() from itertools i...
import numpy as np import tensorflow as tf import tensorflow_hub as tfhub import tensorflow_text convert_v1 = "http://models.poly-ai.com/convert/v1/model.tar.gz" convert_module = tfhub.load(convert_v1) conv = convert_module.signatures["default"] def conv_vec(text: str) -> np.ndarray: return conv(tf.convert_to_te...
import os import re import glob import sys import urllib import urllib2 import json import argparse from color import color from file_manager import Manager _URL = "https://api.github.com" _GISTS = "/gists" def load(): try: f = open('.config') return "?access_token=" + f.read() except IOError...
import Model import View class controller: def __init__ (self, model, view): self.model=model self.view=view while (model.Jeu_en_cours): model.jouer() view.rafraichir(model) model=Model.Plateau(1) view=View.Plateau(model) controller=controller(model, view)
''' ESP Health Notifiable Diseases Framework Chlamydia Case Generator @author: Jason McVetta <jason.mcvetta@gmail.com> @organization: Channing Laboratory http://www.channing.harvard.edu @contact: http://www.esphealth.org @copyright:...
##!/usr/bin/env python #NonCharset lines import re NexFile=("/Users/ethanbartel/Downloads/nexus_files_concat/TestFile.nex") with open(NexFile) as file: with open("TestOutFile.nex", "w") as out: for line in file: out.write(str(line)) with open(NexFile) as file: head = [next(file) for x in range(26...
# init import pandas as pd import numpy as np import os os.chdir("/Users/tilmangraff/Documents/GitHub/TJ") # read in environment exec(open("./code/0.environment/read_env.py").read()) # initialise some line bl = [[0, 2, 7, 8, 15, 25, 37, 51, 52, 66, 53], 50] # lines are always a tupel of an array (number of stops) ...
"""09 Warning GUI Version 2 Buttons frame is set up now full design is complete buttons do not work yet and just print a statement """ from tkinter import * from functools import partial # To prevent unwanted additional windows class WarningGUI: def __init__(self): # Formatting variables backgro...
# -*- coding: utf-8 -*- import json import os import pipenv_to_requirements # pylint: disable=import-error import pipfile # pylint: enable=import-error VECTORS_FOLDER = os.path.join(os.path.dirname(__file__), "vectors") class TestParsing(object): @staticmethod def load_requirements(name): with ope...
# coding=utf-8 score = 100 # 定义了一个变量,给变量附了一个值 high = 200 # 变量名,并赋值 applePrice = 3.5 # 苹果的价格 weight = 7.5 # 苹果的重量 money = applePrice * weight # 总价钱等于money 苹果的价钱乘以苹果的重量 money = money - 10 # 给这个变量一个新值
def binarySearch(v, value): result = { "found": False, "index": 0 } i = 0 f = len(v) - 1 while (f - i > 1): m = int((i + f) / 2) if (value == v[m]): result["found"] = True result["index"] = m break if (value > v[m]): i = m if (value < v[m]): f = m if (False == result["fou...
from bs4 import BeautifulSoup import requests import string import re url = "http://www.bobdylan.com/songs/" main_page = requests.get(url) main_text = main_page.text soup = BeautifulSoup(main_text, "html5lib") spans = soup.find_all("span", {"class": "song"}) link_list = [] for span in spans: links ...
from leilao import Usuario, Lance, Leilao jose = Usuario('José', 200) keith = Usuario('Keith', 1000) lance_keith = Lance(keith, 789.0) lance_jose = Lance(jose, 150.0) leilao = Leilao('Celular') leilao.lances.append(lance_jose) leilao.lances.append(lance_keith) """Se alterarmos a ordem do append, e mantermos if/el...
from numpy import* Eusapia = array(eval(input("jogadas de Eusapia:"))) Barsanulfo = array(eval(input("jogadas de Barsanulfo:"))) i = 0 vitoriaEU = 0 vitoriaBA = 0 #condiçao para entrar execultar while : VETORES DO MESMO TAMANHO if(size(Eusapia) == size(Barsanulfo)): while(i < size(Eusapia) and i < size(Barsanulfo) ...
import pymysql import re import datetime db = pymysql.connect(host='localhost', passwd='123456', port=3306, user='root', charset='utf8', database='eightlang') cur = db.cursor() sql2 = 'insert into author (id,author...
#!/usr/bin/env python import argparse from bs4 import BeautifulSoup import multiprocessing import os import Queue import requests import time import threading from urlparse import urlparse def ensure_tree(path): if os.path.isdir(path): return try: os.makedirs(path) except: pass d...
# author - Mayur Bency # last edited - 11/13/2017 from __future__ import print_function import heapq import numpy as np import matplotlib.pyplot as plt import random import collections import sys class GridWorld: """Creates a 2D grid with given specs.""" def __init__(self, width, height): ...
# coding: utf-8 # Author: Sebastian Dirk Lumpp # Date: 08/07/2019 # Chair of Energy Economics and Application Technology # Technical University of Munich def returnABIstr(): abi_smartcert = """[ { "constant": false, "inputs": [ { "name": "_smgw", "type": "address" }, { ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #from __future__ import division, with_statement ''' Copyright 2010, 陈同 (chentong_biology@163.com). Please see the license file for legal information. =========================================================== ''' __author__ = 'chentong & ct586[9]' __author_email__ = 'ch...
#!/usr/bin/env python # coding=utf-8 import time,sys,queue from multiprocessing.managers import BaseManager #创建类似的QueueManager: class QueueManager(BaseManager): pass #由于这个QueueManager只能从网络上获取Queue,所以注册时只提供名字 QueueManager.register('get_task_queue') QueueManager.register('get_result_queue') #连接到服务器 server_addr = ...
def descending_order(num): # Bust a move right here numstring=str(num) place = [char for char in numstring] place.sort(reverse=True) out='' for i in place: out += i return int(out) test1=526182903 print(descending_order(test1)) # def split(word): # return [char for char in wo...
#!/usr/bin/env python # coding: utf-8 # In[1]: from tkinter import * from tkinter import ttk from tkinter import messagebox from PIL import Image, ImageTk import pymysql class login_page: def __init__(self, root): self.root = root self.root.title('Lecturer Panel') ...
# @Time : 2017/11/14 19:14 # @Author : Crown # @File : dictionary.py # 字典 key-value 无序 ''' info = { 'stu1101': "Tenglan Wu", 'stu1102': "Luola LongZe", 'stu1103': "Maliya Xiaoze" } print(info) # print(info['stu1101']) info['stu1101']="武藤兰"#如果存在key就修改,不存在添加 # info['stu1104']="苍老师" #删除 # del info["st...
# Load data from pyspark.sql.types import * path = "file:/databricks/driver/sales_log/" # Create schema for data so stream processing is faster salesSchema = StructType([ StructField("OrderID", DoubleType(), True), StructField("OrderDate", StringType(), True), StructField("Quantity", DoubleType(), True), Stru...
""" Задание 2. Курс Валюты Написать функцию get_currency_rate(), принимающую в качестве аргумента код валюты (например, USD, EUR, GBP, ...) в виде строки и возвращающую курс этой валюты по отношению к рублю. Код валюты может быть в произвольном регистре. Функция должна возвращать результат числового типа, например floa...
# -*- coding: utf-8 -*- from odoo import api, fields, models, tools, _ from datetime import date, datetime from odoo.exceptions import ValidationError, UserError from reportlab.pdfgen import canvas from reportlab.lib.units import inch from reportlab.lib.colors import magenta, red, black, blue, gray, Color, HexColor fro...
basket = {} basketamount = [] def addbasket( product ,quantity): if basket.get(product): basket[product] = quantity+basket[product] else: basket[product] =quantity def calculateamount(product, quantity): basketamount.append(product.cost*quantity ) return basketamount
__author__ = 'ramvibhakar' #https://www.hackerrank.com/contests/pythonist/challenges/python-string-formatting N = int(input()) space = len(bin(N)[2:]) + 1 for i in xrange(1, N+1): d = str(i) o = str(oct(i)[1:]) h = str(hex(i)[2:]).upper() b = str(bin(i)[2:]) print(' '*(space-len(d)-1)+d+' '*(space-...
import numbers import warnings from math import cos, inf, sin from typing import Dict, Optional import torch import torch.nn as nn import transformers from torch import Tensor from .utils import get_device def get_float_encoding( token: str, embedding_size: int, vmax: float = 1.0 ) -> torch.Tensor: """Conve...
#transposition - function #transposition eh construir serie de sequencias a partir de outra serie de sequencias, #em que a primeira nova sequencia contem o primeiro elemento de cada sequencia original, #a segunda nova sequencia contem o segundo elemento de cada sequencia original, ate que #alguma das sequencias ori...
# Generated by Django 3.1.7 on 2021-03-28 18:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tia_django_api_app', '0003_profit_by_hour'), ] operations = [ migrations.AddIndex( model_name='department', index=mo...
#!/usr/bin/env python2 # # The MIT License # # Copyright (c) 2019 Pavol Rusnak <pavol@rusnak.io> # # 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 limit...
import re from itertools import product from .. import Provider as BarcodeProvider class Provider(BarcodeProvider): # Source of GS1 country codes: https://gs1.org/standards/id-keys/company-prefix local_prefixes = ( *product((0,), range(10)), *product((1,), range(4)), ) upc_e_base_pa...
import setuptools def get_version(): exec(open("poisoning/version.py").read(), locals()) return locals()["__version__"] def get_requirements(): with open("requirements.txt") as f: lines = f.read() lines = lines.strip().split("\n") return lines name = "poisoning" version = get_version...
import pygame import math class Background: def __init__(self, surface, grid_size, line_color, line_width): self.__screen = surface self.__display_size = surface.get_size() self.__grid_size = grid_size self.__line_color = line_color self.__line_width = line_width s...
import requests from bs4 import BeautifulSoup import re # результат поискового запроса def get_html(url, ref=0): url = f'http://zakupki.gov.ru/epz/order/quicksearch/search.html?' \ f'searchString={_searchString}&' \ f'{_conformity}&' \ f'pageNumber={_pageNumber}&' \ f'sortDirect...
from . import metrics from .utils import pad_or_truncate import numpy as np def evaluate( references, estimates, win=1*44100, hop=1*44100, mode='v4', padding=True ): """BSS_EVAL images evaluation using metrics module Parameters ---------- references : np.ndarray, shape=(nsrc,...
#!/usr/bin/env python3 # This script recursively walks from the base directory, processes every json # file based on the geo location and filters out the ones that we are interested # in. We extract the location data and the tweet text from the json. from data_proc.geo_filter import geo_filter from data_proc.utils im...
from lxml import etree parser = etree.HTMLParser() html = etree.parse('demo.html', parser) result = html.xpath('//a[@href="https://www.jd.com"]/../@class') print('class属性 =',result) result = html.xpath('//a[@href="https://www.jd.com"]/parent::*/@class') print('class属性 =',result)
import pymongo def authentication(server_ip, server_port=27017, username='developer', password='Dev1234', db_name='Target_sanity'): """ create client connection, including authentication. server_ip: str IP of the server server_port: int TCP port ...
class Agent: """ Agent """ def act(self, state): raise NotImplementedError() def update(self, state, action, reward, next_state): raise NotImplementedError()
#encoding='utf-8' import pandas as pd import re import numpy as np allphones=pd.read_csv("H:\\毕业设计\\tianmaoshangchengphone(1-19)3.29.csv",encoding='gbk') # print(allphones) data_csv=pd.DataFrame(columns=['brand','product','sales']) x=0 # print(allphones) # print(allphones.sort_index(by='sales')) #手机总排行 bran...
def reverse(l): a=[] for i in range(0,len(l)): r=l.pop() a.append(r) return a inp=int(input("Enter no of elements: ")) l=[] for i in range(0,inp): b=int(input(f"Enter num {i+1}: ")) l.append(b) print(f"Original list{l}") print(f"Reversed List{reverse(l)}")
#import FuncionesMatematicas from FuncionesMatematicas import * sumar(7,5) restar(7,5) multiplicar(5,5)
import os import pickle import numpy as np import scipy.spatial.distance as sp model_path = './model_python3/' #loss_model = 'cross_entropy' loss_model = 'nce' model_filepath = os.path.join(model_path, 'word2vec_%s_final_skip2.model'%(loss_model)) dictionary, steps, embeddings = pickle.load(open(model_filepath, 'rb'))...
from PyQt5 import QtWidgets import sys import random import requests from bs4 import BeautifulSoup class Pencere(QtWidgets.QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.baslik = QtWidgets.QLabel("Film Seçme Sihirbazına Hoşgeldiniz!\nAşağıdaki...
# Copyright (C) 2008 Stout Public House. All Rights Reserved import os os.environ['DJANGO_SETTINGS_MODULE'] = 'stoutsd.settings' # Google App Engine imports. from google.appengine.ext.webapp import util # Force Django to reload its settings. from django.conf import settings settings._target = None import logging i...
from sys import argv from PyQt5.QtWidgets import QApplication, QDialog from Jumpmain2pre import homeshow from result import resultshow from PreEdit import is_ok from sumcreating import sumcreatingshow def main(): homeshow() resultshow() if __name__ == '__main__': main()
import sys def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def test_suite()...
from IPython import embed import SP_DB_CONNECT as spdbc import TL_DB_CONNECT as tldbc import argparse import csv """ International exchanges ['GR', 'GY'] DEU XETRA ['SM'] ESP Bolsa De Madrid ['SS'] SWE NASDAQ OMX Nordic ['LN'] GBR Lond...
def funcA(): from foo2 import function1 function1() funcA() #Output Command #Python3 ~/path/foo.py #Output of this execution # random statement1 # function1 is on # random statement2 # function 2 is on # function1 is on # You can note from the execution of this file #function1() inside funcA has been calle...
# age = input("How old are you?") # height = input("how tall are you") # weight = input("how much do you weigh?") # print(f"so you are {age} old {height} high and {weight} heavy.") print("how old are you", input())
import json import concurrent.futures from urllib.request import Request from urllib.request import urlopen def call_api(url): req = Request(url) response = urlopen(req) return json.loads(str(response.read(), "utf-8")) def get_contents(urls): contents = [] with concurrent.futures.ThreadPoolExec...
import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from scipy import interpolate ############################################ ### Inverse transform sampling ### # Essence: F_inv_x(U) ~ f(x) where U ~ uniform(0,1) # https://en.wikipedia.org/wiki/Inverse_transform_sampling # Generating cdf ...
from rest_framework.decorators import api_view from rest_framework.response import Response from ..models import * from ..serializers import ProductSerializer @api_view(['GET']) def getProducts(request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(...
name = "DATTA" print(list(name)) # ['D', 'A', 'T', 'T', 'A'] print([name[i] for i in range(len(name)-1, -1, -1)]) # ['A', 'T', 'T', 'A', 'D'] print("".join([name[i] for i in range(len(name)-1, -1, -1)])) # ATTAD name = list(name) name.reverse() print("".join((name)))
""" Functions for loading testing data """ def load_data(filepath): test_ans = [] with open(filepath, "r") as f: for line in f: rna, ans = line.split(",") test_ans.append(ans.rstrip()) return test_ans def load_answer(filepath): ans = [] with open(filepath, "r") as...
class Solution: def sortColors(self, nums): mid = left = 0 right = len(nums)-1 while mid<=right: if nums[mid] == 0: nums[mid], nums[left] = nums[left], nums[mid] left += 1 mid += 1 elif nums[mid] == 1: mid += 1 else: nu...
""" Random utility functions """ from functools import wraps # Things that get exposed from * import __all__ = [ "constantly", "complement", "identity", "thread", "execute_fn_with_args_and_or_kwargs" ] def thread(arg, *fns): if len(fns) > 0: return thread(fns[0](arg), *fns[1:]) else: ...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
""" 【问题描述】 输入字符串,输出字符串中出现次数最多的字母及其出现次数。如果有多个字母出现次数一样,则按字符从小到大顺序输出字母及其出现次数。 【输入形式】 一个字符串。 【输出形式】 出现次数最多的字母及其出现次数 【样例输入】 abcccd 【样例输出】 c 3 """ words = {} strInput = input() for i in range(strInput.__len__()): words[strInput[i]] = strInput.count(strInput[i]) a1 = sorted(words.items(), key=lambda x: x[1], reverse=True...
while True: a, b = 1, 1 k = 1 num = int(input("N: ")) while (k <= num-2): a, b = b, a+b k += 1 print(b)
t = int(input()) for _ in range(t): n = int(input()) i = 0 while n >0: if n%2 == 1: print(i, end='') n = n//2 i +=1
from django import forms from places.models import Place class NewPlaceForm(forms.ModelForm): class Meta: model = Place fields = [ 'name', 'description', 'address_country', 'address_city', 'address_street', 'address_post_code...
# -*- coding: iso-8859-15 -*- """ * Sisältää pelaajaan liittyvät tiedot: pisteet, minkä värisiä palloja * yrittää, yrittääkö mustaa palloa, onko voittanut tai hävinnyt. """ class Pelaaja: def __init__(self): self.pallojaJaljella = 7; self.yritanVaria = "enTieda"; self.yritanMustaaPalloa =...