text
stringlengths
8
6.05M
# n=int(input('Enter:')) # for i in range(1,n+1): # for j in range(i): # print('*',end=' ') # print() # n=int(input('Enter:')) # for i in range(n,0,-1): # for j in range(i): # print('*',end=' ') # print() # n=int(input('Enter:')) # k=1 # for i in range(1,n+1): # for j in range(i)...
#!/usr/bin/env python # coding: utf-8 # In[1]: import sys import time # In[2]: sys.path.append(".") # In[3]: import boucleThread # In[6]: time_init = time.perf_counter() boucleThread.boucleSimple(1000000) print( time.perf_counter() - time_init) # In[7]: time_init = time.perf_counter() boucleThread.bo...
#!/usr/bin/env python # -*- coding: utf-8 -*- from storage.impl.deserialize import Deserializer from storage.schema.deserialize import SchemaDeserializer from storage.markdown.serialize import MarkdownImplSerializer, MarkdownSerializer from models.reg import Registry from models.data_types import ComplexDataType, Primi...
################################################################## # Fengjun Yang, 2018 # Code for doing q-learning with the alpaca algorithm ################################################################## import numpy as np import tensorflow as tf from metamountaincar.mmcNormalize import mmcNorm class ALPaCAQ(): ...
def product_array(numbers): all_prod = 1 for x in numbers: all_prod*=x return [all_prod//x for x in numbers] ''' Task Given an array/list [] of integers , Construct a product array Of same size Such That prod[i] is equal to The Product of all the elements of Arr[] except Arr[i]. Notes Array...
import os import glob import pandas as pd import numpy as np from PIL import Image from PIL import ImageFilter import gc import time import datetime from calendar import timegm import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler import random import math from playsound import pl...
#Kayla Batzer #HW 5 P1 #I pledge my honor to abide by the Stevens honor code def square(nums): for i in range(len(nums)): nums[i] = nums[i] * nums[i] def main(): inputList = [1, 2, 3, 4, 5] square(inputList) print(inputList) main()
""" Core module for ace-cli. """ from ace import config from ace import project from ace import graphstack from ace import plugins from inspect import getdoc def seed_parser(parser): """ Adds arguments to parser. """ seed_parser_project(parser) seed_parser_graphstack(parser) seed_parser_plugi...
## Script (Python) "getTVBrNCP" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters= ##title= ## folder_path = '/'.join(context.getPhysicalPath()) solicitacoes = context.portal_catalog.searchResults(meta_type=['Grupo'], sort_on="modifie...
import turtle count = 10 while (count > 0): turtle.forward(100) turtle.left(30) print(count) count = count - 1
from django.shortcuts import render # Create your views here. def handler404(request): return render(request, 'travolta.html', status=404) def handler500(request): # break # return True return render(request, 'travolta.html', status=500) # def handler502(request): # if (request.path == 'favi...
# 水的不能再水的题 class Solution: def nextGreatestLetter(self, letters: List[str], target: str) -> str: if letters[-1] <= target: return letters[0] for i in range(len(letters)): if letters[i]>target: return letters[i] return ""
import socket import threading import pickle from models.message import Message HOST = '127.0.0.1' PORT = 51234 username = bytes(input("Nazwa użytkownika: ").encode('utf-8')) class Client: def __init__(self): self._s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(sel...
import storingwebpages import trials import unifier import cleaner query = "husband" number_of_files = 200 storingwebpages.results(query, "advanced", "1674", "00", "1913", "99", number_of_files) trials.trials(query, number_of_files) unifier.unifier(query, number_of_files) cleaner.cleaner(query, number_of_files)
class HTMLGen(): def comment(self, text): return '<!--{}-->'.format(text) def __getattr__(self, tag): return lambda inner: '<{}>{}</{}>'.format(tag,inner,tag) ''' Another rewarding day in the fast-paced world of WebDev. Man, you love your job! But as with any job, somtimes things can get a lit...
#!/usr/bin/env python # -*- coding:utf-8-unix -*- ### ### RIBES.py - RIBES (Rank-based Intuitive Bilingual Evaluation Score) scorer ### Copyright (C) 2011-2014 Nippon Telegraph and Telephone Corporation ### ### This program is free software; you can redistribute it and/or ### modify it under the terms of the GNU Gene...
import mimetypes from Jumpscale import j from Jumpscale.clients.peewee.peewee import OperationalError from . import auth from .rooter import app, abort, enable_cors, package_route, response, request, PACKAGE_BASE_URL MODEL_URL = f"{PACKAGE_BASE_URL}/model/<model_url>" RECORD_URL = f"{MODEL_URL}/<record_id>" def g...
import cv2 ff=None video=cv2.VideoCapture(0) while True: check, f = video.read() status=0 demo=cv2.cvtColor(f,cv2.COLOR_BGR2GRAY) demo=cv2.GaussianBlur(demo,(21,21),0) if ff is None: ff=demo continue a=cv2.absdiff(ff,demo) b=...
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField, SelectField,IntegerField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError, InputRequired class BuildIdForm(Fla...
""" A simple SET card game implemented in Python Using tkinter for visualization """ import base64 import math import time import tkinter as tk from tkinter import messagebox from set_logic import * __author__ = "Frederik Leira" __version__ = "0.1" CARD_HEIGHT = 300 CARD_WIDTH = 225 CARD_SPACE = 10 CARD_BACK_BACKGR...
from .base_urls import * from django.urls import include, re_path urlpatterns += [ re_path(r'^', include('data_aggregator.urls')), ]
def evaluate_conversion(converted_model, x_test, y_test, testacc, batch_size, timesteps=50): """ Utility function for simple evaluation of the simulation accuracy. """ for i in range(1, timesteps + 1): _, acc = converted_model.evaluate(x_test, y_test, batch_size=batch_size, verbose=0) p...
/Users/samnayrouz/anaconda3/lib/python3.6/rlcompleter.py
import pcl import numpy as np import pcl.pcl_visualization # from pcl.pcl_registration import icp, gicp, icp_nl cloud = pcl.load_XYZRGB('./examples/pcldata/tutorials/table_scene_mug_stereo_textured.pcd') visual = pcl.pcl_visualization.CloudViewing() # PointXYZ # visual.ShowMonochromeCloud(cloud) # visual.ShowGrayCl...
""" tupla = ('a', '1', '2', '-2', '+4', '5', 'sis') resultat = [ valors for valors in tupla if not str(valors).isalpha()] parells = [ valors for valors in resultat if valors % 2 == 0 and valors > 0] print(sum(parells)) """ #~SOLUCIÓ 14 tupla = ('a', '1', '2', '-2', '+4', '5', 'sis') lista_nomes_digits = [valors fo...
import sys import json import numpy as np import statsmodels.api as sm from astropy.coordinates import Longitude from astropy.modeling import models, fitting sys.path.append("../Dust-wave") from bow_projection import Spline_R_theta_from_grid def departure(R, theta): """Parabolic departure of R(theta)""" retur...
from riak import RiakClient, RiakError import inspect # in the style of the sql plugin example, naturally # README example borrowed from caleb brown's bottle-couchdb # read: blatantly plundered. __author__ = 'Kevin Anderson' __version__ = '0.01' __license__ = 'BSD' class RiakPlugin(object): ''' This plugin pass...
#python没必要用全局变量,数据封装 #private 私有变量 class Student(object):#继承object,还可以继承其它的类 def __init__(self,name,score): self.__name=name self.__score=score def print_score(self): print('%s:%s'%(self.__name,self.__score))#private 不可改变数据 zhao=Student('zhao','99') zhao.print_score() class A...
# References # https://github.com/hminle/car-behavioral-cloning-with-pytorch/blob/master/utils.py # https://github.com/hminle/car-behavioral-cloning-with-pytorch/blob/master/experiment.ipynb import numpy as np import torch from torch.utils.data.dataset import Dataset from PIL import Image import scipy.misc import lmdb...
# to send a fancy content in mail we can use MIMEMultipart import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart sender_email = "yourmailid@gmail.com" receiver_email = "toemailid@gmail.com" password = input("Type your password and press enter:") message = MIMEMultipar...
import functools @functools.lru_cache() def editDist(w1, w2): if w1 == w2: return 0 if w1 == "": return len(w2) if w2 == "": return len(w1) return min( 1 + editDist(w1[:-1], w2), # deletion delete last character of w1 1 op + editdistance of w1 without last char and w2 # d o # d o...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-13 19:01 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0002_auto_20170213...
def sum(x,y): return x+y print(sum(3,4))#7 # 函数默认参数 def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s print(power(3)) print(power(3,3)) # 可变参数,传入的参数为数组或者对象 # 关键字参数 # 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。请看示例: ...
""" Created by: Gabriele Pompa (gabriele.pompa@gmail.com) File: example_options_other_params.py Created on Tue Jul 14 2020 - Version: 1.0 Description: This script shows usage of PlainVanillaOption and DigitalOption classes. Instantiation examples are provided involving combinations of the underlying level (S),...
import setuptools with open("README.md", "r") as f: long_description = f.read() setuptools.setup( name="tscribe", version="1.3.1", author="Robert Williams", author_email="robertedwardwilliams@me.com", description="Produce Word Document, CSV, SQLite and VTT transcriptions using the automatic sp...
""" Author : Lily Date : 2018-09-18 QQ : 339600718 百丽宫影城 PALACE cinema PalaceCema-s 抓取思路:在主页面获取每个影院的链接,再进入链接获取影院的具体信息 index_url: http://www.b-cinema.cn/home.jsp 注意:网页时而能加载,时而不能,只要多请求几次,需要改善。 """ from time import sleep import requests import re import datetime from lxml import etree headers = {'User-Agent':'Mozilla/5.0 ...
from matplotlib import pyplot as plt def count0(p): res = 0 for i in p: if i == '0': res += 1 return res def count1(p): res = 0 for i in p: if i == '1': res += 1 return res def count2(p): res = 0 for i in p: if i == '2': res ...
from sqlalchemy import ( create_engine, String, Integer, Column, ) from sqlalchemy.orm import ( scoped_session, sessionmaker, ) from sqlalchemy.ext.declarative import declarative_base from decouple import config DATABASE_URL = config("DATABASE_URL") ENGINE = create_engine(DATABASE_URL, ech...
from flask import Flask,render_template from models import db from views_news import views_blueprint from views_user import user_blueprint from views_admin import admin_blueprint from flask.ext.wtf import CSRFProtect from flask_session import Session import redis def Create_app(config): app = Flask(__name__) ...
import numpy as np import pickle from scipy import stats from astropy.table import Table from util import toSky, inSphere, wCen, P, flatten from classes import Catalog, Tesselation, Zones, Voids infile = "./data/vollim_dr7_cbp_102709.fits" outdir = "./data/" catname = "DR7" intloc = "./intermediate/" + catname nsi...
# -*- coding: utf-8 -*- # # This file is part of Flask-AppExts # Copyright (C) 2015 CERN. # # Flask-AppExts is free software; you can redistribute it and/or # modify it under the terms of the Revised BSD License; see LICENSE # file for more details. """Flask-AppExts provide ready to use extensions for Flask-AppFactory...
def load_correct_creds(creds): return creds['prod']['access_key'], creds['prod']['secret_key']
# 풀이 2 n = [] for i in range(1, 46): for j in range(1, i+1): n.append(i) _ = list(map(int, input().split())) s, e = _[0], _[1] print(sum(n[s-1:e]))
import os import re import cv2 from PIL import Image from cfg import output_path, newdir def read_img_size(img): """ 根据输入视频解码后的图片的尺寸觉得输出视频的尺寸 fix 原代码硬编码尺寸 """ _img = Image.open(img) return _img.size[0], _img.size[1] def generate_video(path): # 重排文件列表 filelist = os.listdir(path) ...
#python3 import requests from lxml import etree import urllib.request as ur import os,time from multiprocessing.dummy import Pool as ThreadPool url = 'https://tieba.baidu.com/p/4840077002?pn={num}' headers = ('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924....
class DynamicPointsDensityUIParameters: # ACCELERATION TIME AccelerationTimeMin = 0.01 AccelerationTimeMax = 300.0 AccelerationTimeLineEditAccuracy = 2 AccelerationTimeCalcConstant = 100 # Раз 100, значит цифры с точностью до 10**2 AccelerationTimeSliderMin = AccelerationTimeMin * Acceleration...
import email import re import tkinter import base64 import tkinter from tkinter import filedialog from tkinter import messagebox from bs4 import BeautifulSoup """splits urls from the msg""" def souper(html_content): return_string="" soup=BeautifulSoup(str(html_content), "html.parser") pretty...
''' Created on 15 nov. 2012 @author: David inspired by Telmo Menezes's work : telmomenezes.com ''' import random import numpy as np import operator as op import math import graph_types.Directed_WeightedGWU as dwgwu import graph_types.Undirected_WeightedGWU as uwgwu import graph_types.Directed_UnweightedGWU as dugwu ...
from pydantic import BaseModel from typing import Optional,List import requests from fastapi import Request, FastAPI from typing import Optional class RegisterModel(BaseModel): service_name: str api_url: str permission: str user_id: str class ServiceRegisterModel(BaseModel): service_name : str ...
from django.test import TestCase class HomePageTest(TestCase): def test_home_page_renders_home_page_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'home.html') def test_view_sets_active_class_on_link(self): response = self.client.get('/') se...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'gallery_window.ui', # licensing of 'gallery_window.ui' applies. # # Created: Thu Jan 2 17:55:43 2020 # by: pyside2-uic running on PySide2 5.9.0~a1 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, Q...
from __future__ import (absolute_import, division, print_function, unicode_literals) import unittest import numpy as np from smqtk.utils import prob_utils class TestAdjustProba (unittest.TestCase): def test_single_class(self): num = 10 dim = 1 proba = np.rando...
import subprocess # --------------------------------------- # SOLVENTFIT CALIBRATION fit function # --------------------------------------- def fit(nx_design, nx_var, xdatfile, ydatfile, modelfile, expfile, priorsfile, disc=True, writepost=True, writedisc=True, emul_params=None, calib_params=None, disc_params=...
# -*- coding: utf-8 -*- """ Created on Wed May 20 12:32:27 2015 @author: bolaka """ import sys import math from pprint import pprint from itertools import chain, combinations from datetime import datetime, timedelta import random import pandas as pd import numpy as np from sklearn import cross_validation, tree, svm,...
#!/usr/bin/env python import numpy as np import pymc as pm from pylab import * import corner # Plotting Parameters Setting rcParams['figure.figsize'] = 2*1.67323, 1.9*1.67323 rcParams['ps.useafm'] = True plt.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) rcParams['pdf.fonttype'] = 42 matplotlib.rc('...
from django.db import models from django.conf import settings from django.contrib.auth.models import User # Create your models here. class HashType(models.Model): idHashType = models.AutoField(primary_key=True) description = models.CharField(max_length=100) #if you use python 2 then use unicode de...
from __future__ import annotations from PIL import ImageOps, ImageDraw, Image, ImageFont, ImageEnhance import aiohttp import asyncio from io import BytesIO from redbot.core.utils.chat_formatting import humanize_number import humanize from datetime import datetime from bs4 import BeautifulSoup def champ_into_pic(cham...
import asyncio import multiaddr import pytest from tests.utils import cleanup from libp2p import new_node from libp2p.peer.peerinfo import info_from_p2p_addr from libp2p.pubsub.pubsub import Pubsub from libp2p.pubsub.floodsub import FloodSub from libp2p.pubsub.message import MessageTalk from libp2p.pubsub.message impo...
import chess import numpy as np root = None # MCTS class class MctsNode(): def __init__(self, state, parent=None, parent_action=None): ''' Initialise a board state ''' self.state = state self.board = chess.Board(state) self.parent = parent if self.parent...
from flask import Flask, render_template, request, flash from admin_report import Admin_Report from DB import DB app = Flask(__name__) @app.route("/administrator_report", methods=['GET']) def admin_report(): admin_report = Admin_Report() db = DB() registered_users = db.get_registered_users() return re...
from .GeomView import GeomView # This view generates indices for polygons. class PolygonView(GeomView): def generateTriangleIndices(self, firstVertex, numVerts): for i in range(firstVertex + 1, firstVertex + (numVerts - 1)): self.indices.addVertices(firstVertex, i, i + 1) self.indi...
import numpy as np import pandas as pd import tensorflow as tf from tensorflow import feature_column from tensorflow.keras import layers from sklearn.model_selection import train_test_split class StructuredModel: def __init__(self): self.dataframe = None self.train = None self.test = None ...
import sys import Libr import random # перевод в из 16-ой в 10-ую def To_teny(x): return(int(x,16)) # перевод из 10-ой в 16-ую def To_sexteen(y): if len(hex(y)[2:]) < 2: a = '0' + hex(y)[2:] else: a = hex(y)[2:] return (a) # генерация master - ключа def key_gen (): keymaster = '' ...
""" Created on Jul 3, 2013 @author: Zachary """ import math import inspect import numpy as np import matplotlib.pyplot as plt from pybrain.supervised import BackpropTrainer from pybrain.tools.shortcuts import buildNetwork from pybrain.datasets import SupervisedDataSet from scipy.io import wavfile from pybrain.tools.c...
# Generated by Django 3.2.7 on 2021-09-11 12:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Country', fields=[ ...
#!/usr/bin/env python # encoding: utf-8 """ Created by 'bens3' on 2013-06-21. Copyright (c) 2013 'bens3'. All rights reserved. python tasks/mongo_catalogue.py --local-scheduler --date 20160519 """ import time import luigi from uuid import UUID from ke2mongo.lib.cites import get_cites_species from ke2mongo.tasks.mo...
areas = [ { "area_data": [3364] }, { "area_data": [3103, 3159, 3364, 3016, 3017, 3018] } ] platform = [ { "platform_type": "APP", }, { "platform_type": "APPLET", } ] status = [ { "status": "ENABLED" }, { "status": "DISABLED" ...
# Generated by Django 3.2.5 on 2021-08-04 13:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('master_file', '0029_alter_product_sort_group'), ] operations = [ migrations.AlterField( model_name='color', name='co...
''' 但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含 1000 万个元素的列表, 不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。 所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢? 这样就不必创建完整的 list,从而节省大量的空间。 在 Python 中,这种一边循环一边计算的机制,称为生成器:generator。 在 Python 中,使用了 yield 的函数被称为生成器(generator)。 跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。 在调用生成...
import csv from pathlib import Path import json menu_filepath = Path('./Resources/menu_data.csv') sales_filepath = Path('./Resources/sales_data.csv') output_path = Path("sales_report.txt") menu = [] sales = [] report = {} quantity = 0 price = 0 cost = 0 with open(menu_filepath, 'r') as menu_data: reader = csv.re...
# Generated by Django 1.11.8 on 2018-01-12 15:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('admin', '0011_domain_transport'), ] operations = [ migrations.AddField( model_name='domain', name='dkim_key_length',...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua import pandas as pd d = pd.DataFrame([range(1,8)],range(2,9)) d.corr(method="pearson")#计算相关系数 s1 = d.loc[0] s2 = d.loc[1] p= s1.corr(s2,method="pearson") print(p)
import sys sys.path.append('../linked_lists'); from node import * class graph: def __init__(self, input_file, data_type=str): #initialize variables self.ref_list = []; #pass on the work to other functions self.read_file(input_file, data_type); def read...
from flask import Flask, json from flask_sqlalchemy import SQLAlchemy from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_jwt_extended import JWTManager # for session from datetime import timedelta app = Flask(__name__) app.secret_key = "test" #SqlAlchemy Database Configuration With Mysql ...
import pandas as pn from sklearn.svm import SVC data = pn.read_csv('/Users/oleg/PycharmProjects/ML-Found-Yandex/DATA/w3_01.csv', header=None) clf = SVC(kernel = 'linear', C = 100000, random_state = 241) X = data.loc[:, 1:] y = data.loc[:, 0] # print(data) clf.fit(X, y) print(clf.support_) # print(data)
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-23 05:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('treatment_sheets', '0004_txsheet_date'), ] operations = [ migrations.AlterFi...
import requests, json, sqlite3, csv, sys import plotly as py import plotly.plotly as py import plotly.graph_objs as go from collections import Counter from final_proj_secrets import * def params_unique_combination(baseurl, params): alphabetized_keys = sorted(params.keys()) res = [] for k in alphabetized_k...
from sklearn.ensemble import AdaBoostClassifier method=AdaBoostClassifier(n_estimators=10000)
from flask import Blueprint import syft as sy import torch as th # Avoid Pytorch deadlock issues th.set_num_threads(1) hook = sy.TorchHook(th) local_worker = sy.VirtualWorker(hook, auto_add=False) hook.local_worker.is_client_worker = False main = Blueprint("main", __name__) ws = Blueprint(r"ws", __name__) from .....
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/3/31 21:48 # @Author : Yunhao Cao # @File : cqueue.py import queue as thread_queue from . import logger from .task import RequestTask __author__ = 'Yunhao Cao' __all__ = [ 'WebRequestQueue', ] class Queue(object): def get(self, block, tim...
from catalyst.contrib.utils import plot_tensorboard_log from model import Model import torch.nn as nn class CustomRunner(dl.Runner): def _handle_batch(self, batch): # model train/valid step features, targets = batch["features"], batch["targets"] logits = self.model(features) score...
import numpy as np print('Hello world') print("Im learning git") # 添加了一条注释 123456
import argparse from loguru import logger def main(): parser = argparse.ArgumentParser() parser.add_argument("filename", help="file name to process") args = parser.parse_args() try: with open(args.filename, 'w') as f: f.write("hello") except Exception as ex: logger.info...
# Copyright 2020 Pulser Development Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
from wfdb.processing.basic import ( resample_ann, resample_sig, resample_singlechan, resample_multichan, normalize_bound, get_filter_gain, ) from wfdb.processing.evaluate import ( Comparitor, compare_annotations, benchmark_mitdb, ) from wfdb.processing.hr import compute_hr, calc_rr, ...
from pandac.PandaModules import * from MarginCell import MarginCell import random class MarginManager(PandaNode): def __init__(self): PandaNode.__init__(self, 'margins') self.cells = set() self.visiblePopups = set() def addGridCell(self, x, y, left, right, bottom, top): paddin...
import sys from PIL import Image from django.core.files.uploadedfile import InMemoryUploadedFile from django.core.validators import MinValueValidator, MaxValueValidator from six import BytesIO from users.models import User from django.db import models import datetime from mptt.models import MPTTModel, TreeForeignK...
#import all library that needed import sqlite3 import tweepy from nltk.corpus import stopwords import re import string from Sastrawi.Stemmer.StemmerFactory import StemmerFactory import json import pandas as pd import itertools import matplotlib.pyplot as plt from nltk.tokenize import word_tokenize from nltk...
def array_conversion(arr): ops = {True:lambda x,x1:x+x1, False:lambda x,x1:x*x1} add = True while len(arr)!=1: new_arr = [] for i in range(0,len(arr[:-1]),2): new_arr.append(ops[add](arr[i],arr[i+1])) arr = new_arr add = not add return arr[0] ''' Task ...
from django.db import models class URL(models.Model): original_url = models.URLField(max_length=200, unique=True) shortened_url = models.URLField(max_length=200, unique=True) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): ...
import json jsonstring = ''' { "accuracy": { "fit": 0.1, "sig": 0.2, "col": 0.3 }, "comfort": { "fit": 0.4, "sig": 0.5, "col": 0.6 }, "duration": { "fit": 0.7, "sig": 0.8, ...
import logging import fmcapi import time def test__acp_rule(fmc): logging.info( "In preparation for testing ACPRule methods, set up some known objects in the FMC." ) starttime = str(int(time.time())) namer = f"_fmcapi_test_{starttime}" # Build an IP host object iphost1 = fmcapi.Hosts...
""" Write a python function, check_double(number) which accepts a whole number and returns True if it satisfies the given conditions. The number and its double should have exactly the same number of digits. Both the numbers should have the same digits ,but in different order. Otherwise it should return False. Example...
# # Copyright © 2021 Uncharted Software Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-08-10 05:58 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Creat...
from datetime import datetime from app.domainmodel.movie import Movie class Review: def __init__(self, input_movie: Movie, review_text: str, input_rating: int): if input_rating < 0 or input_rating > 10: self.__rating = None else: self.__reviewText = review_text ...
# Generated by Django 2.1.2 on 2018-11-08 19:45 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('orders', '0002_auto_20181108_2136'), ] operations = [ migrations.AlterField( ...
from django.db import models from django.contrib.auth.models import AbstractUser from users.models import User from .filters import dollar VARIANT = [ ('Квартира', 'Квартира'), ('Дом', 'Дом') ] class SaleFlat(models.Model): cost = models.PositiveIntegerField(verbose_name='стоимость квартиры'...
def search_quadruplets(sequence: list[int], target: int) -> list[int]: """ >> > search_quadruplets([4, 1, 2, -1, 1, -3], 1) [-3, -1, 1, 4], [-3, 1, 1, 2] Explanation: Both the quadruplets add up to the target. >> > search_quadruplets([2, 0, -1, 1, -2, 2], 2) [-2, 0, 2, 2], [-1, 0, 1, 2] Ex...
import sys from django.conf import settings from django.core.management import call_command from django.db.backends.creation import TEST_DATABASE_PREFIX from django.test.simple import DjangoTestSuiteRunner try: from django.test.simple import dependency_ordered except ImportError: from django_extras.django124.t...