text
stringlengths
8
6.05M
import wx class TestFrame(wx.Frame): # inherit from PanelFrame def __init__(self): wx.Frame.__init__(self, None, -1, '"Real World" sizer example') panel = wx.Panel(self) # 1st create controls topLbl = wx.StaticText(panel, -1, "Personal Information") topLbl.SetFont(wx.Font(1...
class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ used_characters = {} max_length = 0 i = 0 j = 0 while i <len(s) and j < len(s): if s[j] in used_characters.keys(): del used_char...
# -*- coding: utf-8 -*- from django.conf import settings from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from ckeditor_uploader.fields import RichTextUploadingField from base.models import BaseArticle, BaseArticleSection class News(BaseArticle): ...
#!/bin/python3 # This is done with hasty code letters = [0] * 26 for char in input().strip(): letters[ord(char)-97] += 1 bycount = {} for i in range(len(letters)): if letters[i] == 0: continue bycount[letters[i]] = bycount.get(letters[i], 0) + 1 if len(bycount) > 2: print('NO') elif len(byco...
""" There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you sh...
file=open("C:/a.txt") a=file.read() a=a+"\n" str="" #this string will contain line of word file line=[] #line as a list initialised for b in a: if b!='\n': str=str+b ...
from rest_framework.routers import SimpleRouter from api.banners import views router = SimpleRouter() router.register(r'^site_?banners', views.SiteBannerViewSet, basename='site_banners') urlpatterns = router.urls
import torch from torch import nn import numpy as np import torch.nn.functional as F from utils import * class BaseNet(nn.Module): def __init__(self, config): super(BaseNet, self).__init__() self.config = config # #Embed layer # self.embeddings = nn.Embedding(vocab_size, self.config...
# -*- coding: utf-8 -*- # @Author: aaronlai # @Date: 2016-10-15 01:00:07 # @Last Modified by: AaronLai # @Last Modified time: 2016-11-12 13:03:00 from unittest import TestCase from run_VQA import run_VQA class Test_running(TestCase): def test_VQA(self): run_VQA('train_questions', 'train_choices', 't...
from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_validators import validate_bool CENTRALIZED = False EXAMPLE_PAIR = "ZRX-WETH" DEFAULT_FEES = [0, 0.00001] USE_ETHEREUM_WALLET = True FEE_TYPE = "FlatFee" FEE_TOKEN = "ETH" KEYS = { "bamboo_relay_use_coordinator": ...
#Take the items in this list of lists: [["Top Gun", "Risky Business", "Minority Report"], ["Titanic", "The Revenant", "Inception"], ["Training Day", "Man on Fire", "Flight"]] #and write them to a CSV file. The data from each list should be a row in the file, with each item in #the list separated by a comma. impor...
# Empty objects needed for ErrorScreen debug_mode = 0 screen = None # Try pygame import necessary for visual windows of applications try: import pygame except ImportError as e: print(e) exit() # Main error handling try: import json import traceback from classes.game_screen impor...
from flask import Flask from flask import Flask app=Flask(__name__, instance_relative_config=True) app.config.from_object('config') import criptomonedas.views
import sys class Node(object): """ Abstract base class for AST nodes """ def children(self): """ A sequence of all children that are Nodes """ pass def show(self, buf=sys.stdout, offset=0, attrnames=False, nodenames=False, showcoord=False, _my_node_nam...
#!/usr/bin/python print("Hello Git!") print("Now I'm Git user!")
from django.urls import resolve from rest_framework import status from rest_framework.exceptions import ErrorDetail from rest_framework.reverse import reverse from rest_framework.test import APITestCase, APIRequestFactory from cars.models import Car, Manufacturer from cars.views import CarDeleteView factory = APIRequ...
from django.test import TestCase from folder.models import Folder from folder.serializers import FolderSerializer, FolderSerializerWithoutChildren from user.models import User from user.serializers import UserSerializer class FolderSerializerTest(TestCase): @classmethod def setUpTestData(cls): user ...
# Creates a post and then deletes it from tools.steps_helper import create_post, delete_post, get_latest_post_id, get_api, page_id, post_msg def test_delete_post(): api = get_api() create_post(api, post_msg) post_id = get_latest_post_id(api) delete_post(api, post_id) assert api.request(page_id + '...
def printCalculate(cidr): s_cidr=cidr.split("/") ip=s_cidr[0] binary_ip="" s_ip=ip.split(".") for i in range(4): int_ip=int(s_ip[i]) str_binary=str(decimalToBinary(int_ip)) zeros="" for i in range(8-len(str_binary)): zeros+="0" binary_ip+=zeros+st...
# -*- coding: utf-8 -*- """ Created on Thu Oct 08 16:22:26 2015 @author: tw5n14 """ from networkx import * import matplotlib.pyplot as plt import numpy as np import csv import math import os G = Graph() userps = {} gw, cw = [],[] #load user profile from file file_path = os.sep.join(os.path.dirname(__file__).spli...
from selenium import webdriver import time # инициализация хром-драйвера driver = webdriver.Chrome("C:\\selenium\\chromedriver.exe") # перевод браузера в полноэкранный режим driver.fullscreen_window() # переход на монголо-русский переводчик google driver.get("https://translate.google.ru/?hl=ru&tab=TT&authuser=...
#PYTHON CODE for Q6: import pandas as pd import csv df = pd.read_csv('faculty.csv') faculty_dict={} df.name = df[df.columns[0]] df.name = df.name.apply(lambda x: x.split(' ')[-1]) faculty_dict = df.set_index('name').T.to_dict('list') print first3kv = {k: faculty_dict[k] for k in faculty_dict.keys()[:3]} print first3k...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-08-03 03:46 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ...
'''test class''' import unittest import collections from CsvIO import read_stock_csv, write_stock_csv class TestCsvIO(unittest.TestCase): """TestCsvIO - Tests stock io""" def test_readstockcsv(self): """test_readstockcsv - should read stocks list from csv file """ stocks = read_stock_csv('AAPL...
from rest_framework import serializers from .models import Calculator, Chance class CalculatorSerializer(serializers.ModelSerializer): class Meta: model = Calculator fields = '__all__' class ChanceSerializer(serializers.ModelSerializer): class Meta: model = Chance fields = '__a...
import requests import time requests.post('http://localhost:5000', data = {'temp':'20','mac':'B4:21:8A:F0:13:44','sensor_id':'example_sensor_id'}) #requests.get('http://localhost:5000/data/99')
#print("hello world") import tkinter ############## FUNCTIONS def find_screen_width(): t = tkinter.Tk() # new window t.update() t.state('zoomed') width = t.winfo_width() t.destroy() return width def find_screen_height(): t...
from .metric import Metric import numpy as np import mot.utils.box import mot.utils.debug class EuclideanMetric(Metric): """ An affinity metric that only considers the euclidean of tracklets' box and detected box. """ def __init__(self, use_prediction=False): super(EuclideanMetric).__init__() ...
import random as rd import math import matplotlib.pyplot as plt def base_station(num_base, pos_base): """input base station point""" # Set POS base station here station = [] for _ in range(num_base): station.append(map(int, pos_base.split(','))) return station def random_nodes(width, hei...
#!/usr/bin/env python import sys, os import subprocess build_dir = sys.argv[1] try: for line in open(build_dir + "/tests/all_tests.txt", "r").readlines(): print "******************************************************************" \ "*************" print "* RUNNING: %s" % line.strip() print "****...
from .quality_metric_list import * from .quality_metric_calculator import (compute_quality_metrics, get_quality_metric_list, QualityMetricCalculator, get_default_qm_params) from .pca_metrics import get_quality_pca_metric_list
import torch from segmentation_models_pytorch.utils.train import TrainEpoch, ValidEpoch class TrainEpochMultiGPU(TrainEpoch): def __init__(self, model, **kwargs) -> None: super().__init__(model, **kwargs) def _to_device(self): device = self.device if isinstance(self.device, list) and ...
import VRP import readers import time from gurobiHandler import vrpSolver import csv import getopt import sys import os import matplotlib.pyplot as plt import networkx as nx class vrpRunner: def __init__(self,readerType): if readerType == "solomon": self.reader = readers.solomonFileReader(...
from flask import Flask, render_template, request, redirect, url_for from werkzeug import secure_filename import os UPLOAD_FOLDER = '/root/portal/upload' ALLOWED_EXTENSIONS = set(['txt','pdf','png','jpg','jpeg','gif','doc','docx','mp4']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/'...
import unittest from Calculator import Calculator from CsvReader import CsvReader from pprint import pprint class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.calculator = Calculator() def test_instantiate_calculator(self): self.assertIsInstance(self.calculator, Calculator) ...
''' Berkeley Deepdrive Segmentation Dataset loader ''' import os import re import numpy as np from matplotlib.image import imread from PIL import Image import torch from torch.utils.data import Dataset #from dataset.utils import listdir class BDDSegmentationDataset(Dataset): ''' Dataset loader for Berkeley Deepd...
# https://www.reddit.com/r/dailyprogrammer/comments/3s4nyq/20151109_challenge_240_easy_typoglycemia/ import re import random def typo(sentence): wordList = re.findall(r'\w+', sentence) reworkedSentence = "" for word in wordList: newWord = "" newMiddle = "" firstLetter = word[0] ...
from pkg_resources import EntryPoint, get_distribution import pytest from raincoat import match as match_module @pytest.fixture def basic_match(): return match_module.Match(filename="yay.py", lineno=12) def test_str_match(basic_match): assert str(basic_match) == "Match in yay.py:12" def test_match_from_...
from keras.models import Sequential from keras.layers.core import Dense,Activation model = Sequential() model.add(Dense(units=32,input_shape=(784,))) model.add(Activation('relu')) print(model.summary())
#!/usr/bin/python3 import re import time def getstats(): rv = {} f.seek(0) for i in range(2): f.readline() for line in f: (name, data) = line.strip().split(":") data = data.split() rv[name] = [int(x) for x in data] return rv if __name__ == "__main__": f = open("/proc/...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import sys import json import platform import warnings try: from setuptools import setup from setuptools import Extension from setuptools import find_packages import setuptools setuptools_version = setuptools.__version__.split('.') if int...
from base64 import b64encode from django import template from LandingPage.models import * register = template.Library() @register.filter def bin_2_img(_bin): if _bin is not None: return b64encode(_bin).decode('utf-8') @register.filter(name='getVideos') def getVideos(id): video=CourseVdeo.objects.get(Vid=id) ...
# Generated by Django 3.2.3 on 2021-05-17 18:34 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('main', '0002_rename_cat_category'), ] operations = [ migrations.CreateModel( name='News', ...
import math import os import random import re import sys def squares(a, b): count = 0 end = int(b ** (0.5)) start = int(a ** (0.5)) for x in range(start, end + 1): if b >= (x * x) >= a: count += 1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'...
# Written By Saurav Paul from tools.json_manager import JsonManager as JM interaction_setting = { 'voice_reply' : False, 'text_reply' : True , 'voice_read+voice_reply' : False , 'text_read' : True, } bot = { 'name' : 'Jarvis', # You can change bot name from here 'gender' : 'male', #Whatever you...
import numpy from nltk.sentiment.vader import SentimentIntensityAnalyzer for i in numpy.arange(0,0.5,0.01): pos_count = 0 pos_correct = 0 with open("positive.txt","r") as f: for line in f.read().split('\n'): sen = SentimentIntensityAnalyzer().polarity_scores(line) if sen['...
import networkx as nx from networkx.exception import NetworkXError from networkx.algorithms.bipartite import random_graph \ as bipartite_random_graph from warnings import warn # from IPython import embed import numpy as np #from pathos.multiprocessing import ProcessingPool import pymp class SBM(nx.DiGraph): '...
import torch import torchvision import torch.nn as nn import numpy as np import torchvision.transforms as transforms import torchvision.datasets as datasets import os from PIL import Image import io import sys from matplotlib.pyplot import imshow from torch import topk from torch.nn import functional as F class Dense...
from rest_framework import serializers from rest_framework.utils import model_meta from .models import Topic, Preference, Medium class TopicSerializer(serializers.ModelSerializer): class Meta: model = Topic fields = ('id', 'name', 'description') extra_kwargs = { 'name': { ...
# -*- coding: utf-8 -*- """ Created on Mon Dec 21 18:28:19 2020 @author: Chethan """ # Importing libraries import numpy as np, pandas as pd import matplotlib.pyplot as plt, seaborn as sb # Importing Dataset range1 = [i for i in range(0,2)] df = pd.read_csv(r"C:/Users/Chethan/Downloads/preprocessed_data...
from BasicGame import * from pygame import * from pygame.locals import * from math import e, pi, cos, sin, sqrt from random import uniform, randint import time #add your classes here from Player import * from Projectile import * # from Alien import * from Wave import * from UFO import * #constants FPS ...
def f(i): if i<6: return 0 return i//3-2 assert(f(12)==2) assert(f(14)==2) assert(f(1969)==654) assert(f(100756)==33583) with open("input.txt", "rt") as fi: lines=fi.read().splitlines() print(sum([f(int(l)) for l in lines]))
from requests_html import HTMLSession import requests import json from hashlib import md5 import uuid import datetime google_api_key = '' def get_verification_code(username): # The code is the first 16 chars of the md5 hash of the username username_hash = md5(username.encode('utf-8')) return username_ha...
# encoding = utf-8 from flask import Flask, render_template, redirect, request, session, url_for # 为下文session产生一个随机数 import os from exts import db # 引入配置文件 import config from models import Users from home.home import home_ob from school.school import school_ob from techn.techn import techn_ob from talk.talk import ta...
class Solution: def isPalindrome(self, s): ans = [i.lower() for i in s if i.isalnum()] return ans == ans[::-1] def isPalindrome(self, s): l, r = 0, len(s) - 1 while l < r: while l < r and not s[l].isalnum(): l += 1 while l < r and not s[r]...
''' Created on Sep 13, 2016 @author: Dayo ''' from django.conf.urls import url, include from .views import * from .webhooks import * urlpatterns = [ #url(r'^$', Index.as_view(), name='index'), url(r'^sms/$', SMSReport.as_view(), name='sms-reports'), url(r'^email/$', EmailReport.as_view...
print( "The number of participants that survived beyond 5 years in a cohort of N participants" " follows binomial distribution." "\nThe parameter is q.")
# -*- coding: utf-8 -*- ''' Faire des tests sur les dimensions des fonctions, rapide juste un assert pour être sur ''' import numpy as np from src.Activation.ReLU import ReLU from src.Activation.softmax import Softmax from src.Loss.CESoftMax import CESoftMax from src.Module.conv1D import Conv1D from src.Module.flatt...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import logging.config import sys from logging.handlers import RotatingFileHandler from src.settings import config class CadastroLogger: """Custom logger for keeping track of the libreCatastro Scrapping""" def __init__(self, class_name): "...
""" Utility functions. """ import asyncio import collections import functools import inspect import io import logging import os from typing import Set # noqa import libnacl import logbook import logbook.compat import logbook.more # noinspection PyPackageRequirements import lru import wrapt from .key import Key __al...
#-*- coding:utf8 -*- import time import datetime import cStringIO as StringIO from django.contrib import admin from django.http import HttpResponse from shopapp.yunda.models import (ClassifyZone, BranchZone, LogisticOrder, ...
# git的使用教程 # git 与svn的区别(git是分布式,而svn是集中式管理) """ 1.下载git服务器(64为windows)--默认路径programs/git 2.tortoiseGit安装 3.创建一个本地仓库--(创建文件 --git init [或者是点击git beash]) 4. """
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPRegressor from sklearn.metrics import mean_squared_error, mean_absolute_error def regevaluate(t, predict, criterion): if criterion == 'mse': ret...
def showsite(siteurl): html = requests.get(siteurl).text soup = BeautifulSoup(html, 'html.parser') kind = soup.select(".content-header-desc__detail")[1].text.strip() # 分類 area = soup.select(".content-header-desc__detail")[2].text.strip() # 區 item_desc = soup.select(".location-item .location-item__...
from get_fish_info import get_fish_info import pandas as pd from pathlib import Path import pylab as pl import pickle import numpy as np root_path = Path("/n/home10/abahl/engert_storage_armin/ariel_paper/free_swimming_behavior_data/dot_motion_coherence") for experiment in ["chrna2a", "disc1_hetinx"...
#functional programming means that you're allowed to pass functions around just as if they were variables or values. #an anonymous function is a function that we simply do no define #a named function: def by_three(x): return x % 3 == 0 #an anonymous function, that does the same thing: lambda x: x % 3 == 0 #we ca...
import web render = web.template.render('templates/') urls = ( '/', 'index' ) db = web.database(dbn='postgres', user='dave', password='password', audb='mydb') class index: def GET(self): todos = db.select('todo') return render.index(todos) if __name__ == "__main__": # web.application(l...
# -*- coding: utf-8 -*- #!/usr/bin/env python from models import drfOpsClass, drfOpsClassBase, session import uuid import itchat import re def to_dict(self): return {c.name: getattr(self, c.name, None) for c in self.__table__.columns} '''test_msg_s = '#S06:00 1740' test_msg_e = '#E18:00 1859' ''' classStart = dr...
n = int(input()) board_size = [list(input()) for _ in range(n)] def search_board(board, search): for y, row in enumerate(board): for x, ch in enumerate(row): if ch == search: return y, x snake_pos = search_board(board_size, "S") game_over = False eaten_food = 0 def move(dy...
#不借助临时,交换2个变量,使用2中方法 # 方法1: # a=10 # b=20 # print('交换前:',a,b) # a,b=b,a # print('交换后:',a,b) # 方法2: a=20 b=10 print('交换前:',a,b) a=a+b b=a-b a=a-b print('交换后:',a,b)
import json with open('quishpi_org.mrp') as f: counter = 0 for l in f: found_in_this = False graph = json.loads(l) for node in graph['nodes']: if 'anchors' in node: if len(node['anchors']) > 1: if found_in_this: co...
def sign_up(): '''회원가입 함수''' try: sign_up() except BadUserName: print('이름으로 사용할 수 없는 입력입니다.') except PasswordNotMatched: print('입력한 패스워드가 서로 일치하지 않습니다.')
from bs4 import BeautifulSoup import urllib3 A = ['A','B','C'] B = ['01', '02', '03'] code = [] C = ['0', '1', '2', '3','4'] D = ['.0', '.1', ] dd = [] for i in A: for x in B: code.append(i+x) def check_code(idc): url = "https://www.icd10data.com/search?s={}&codebook=icd10cm".format(idc) http = ur...
from bs4 import BeautifulSoup from companies_matcher.config import config from .abc import ParserABC import aiohttp class MarketwatchParser(ParserABC): _url = config['marketwatch']['url'] _endpoint = config['marketwatch']['endpoint'] _headers = {'User-Agent': config['service']['userAgent']} def __ini...
#python program to check given number is prime or not n=int(input("Enter an integer number")) k=0 for i in range(1,n+1): rem=n%i if rem==0: k=k+1 if k==2: print(n,"is a prime number") else: print(n,"is not a prime number") print("End of the program")
from unittest import TestCase, main from ... import UndirectedGraph class TestGetEdgeWeight(TestCase): def setUp(self) -> None: self.g = UndirectedGraph(edges={("a", "b"): 1, ("b", "c"): 2, ("e", "f"): 3}) def test_get_weight(self) -> None: self.assertEqual( self.g.get_edge_weigh...
from replit import clear #HINT: You can call clear() to clear the output in the console. logo = ''' ___________ \ / )_______( |"""""""|_.-._,.---------.,_.-._ | | | | ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch from torch.autograd import Variable def batch_cosine_sim(u, v, epsilon=1e-6): """ u: content_key: [batch_size x num_heads x mem_wid] v: memory: [batch_size x mem_hei x mem_wid] ...
import os import abc from . import utils class BaseProcessor: def __init__(self): self.data_dir = None def set_data_dir(self, data_dir): self.data_dir = data_dir @abc.abstractmethod def precoppy(self, prop, value): pass @abc.abstractmethod def postcoppy(self, prop,...
"""Keep your requirements.txt files in sync with Pipfile or Pipfile.lock files.""" from .pipfile_requirements import PipfileRequirementsManager
import datetime import time from django.contrib.auth import get_user_model, authenticate from django.contrib.auth.models import AnonymousUser import graphene import graphql_jwt from graphene_django import DjangoObjectType from graphql_jwt.decorators import login_required from graphql_jwt.utils import get_payload from...
""" This file defines class CorrectClassifiedReward. @author: Clemens Rosenbaum :: cgbr@cs.umass.edu @created: 6/8/18 """ from .BaseReward import BaseReward class CorrectClassifiedReward(BaseReward): """ Class CorrectClassifiedReward defines the +1 reward for correct classification, and -1 otherwise. """...
from django.db import models from django.utils.regex_helper import Choice from django.utils.timezone import now # Create your models here. class cart_item(models.Model): Img = models.ImageField(upload_to='pics') Product = models.CharField(max_length=255) Quantity = models.IntegerField() Price = model...
import tkinter as tk from PIL import Image, ImageTk from player import Player, COLORS from utils import * from game_state import GameState import pieces from pieces.special_moves import * from game_rules import * from timer import * from ai import * class Board(tk.Frame): def __init__(self, parent, rows=8, colum...
# -*- coding:utf-8 -*- import os import sys import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication import base64 import logging reload(sys) sys.setdefaultencoding('utf8') # Get an instance of a logger logger = logging.getL...
#Enclosing function local #Funciones anidadas name = "This is a global name" def greet(): name = "Sammy" def hello(): print("Hello "+name) hello() greet() ################################ x = 50 def func(): x = 1000 return x print("Before function call, x is:", x) x = func() print("A...
# -*- coding:utf-8 -*- """ 机器人启动index """ import datetime import json import sys import time import itchat from config import oss_url_2, oss_url_1, sms_msg_1, add_friend_msg from itchat.content import * from robot.service import service_handle from robot.util.redis_conf import predis from robot.util.oss import upload_...
import logging import os import random import string from kubeflow.testing import argo_build_util # The name of the NFS volume claim to use for test files. NFS_VOLUME_CLAIM = "nfs-external" # The name to use for the volume to use to contain test data DATA_VOLUME = "kubeflow-test-volume" E2E_DAG_NAME = "e2e" EXIT_DAG...
import webapp2 import cgi import os import re from google.appengine.ext import db import jinja2 import random from string import letters import hashlib import hmac jinja_env = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) # private regula...
# conditions and booleans # lang='python' # if lang=='js': # print('lang is js') # elif lang=='python': # print('lang is py') # elif lang=='go': # print('lang is go') # else: # print('no match') user='modi' lang='python' if not user: print('correct user') else: print('bad') a=[1,2,3] b=[1,2,3] print...
# @Title: 统计位数为偶数的数字 (Find Numbers with Even Number of Digits) # @Author: 2464512446@qq.com # @Date: 2020-01-03 11:59:50 # @Runtime: 64 ms # @Memory: 12.4 MB class Solution: def findNumbers(self, nums: List[int]) -> int: count = 0 for i in nums: if len(str(i)) % 2 == 0: ...
elements=[23,14,56,12,19,9,15,25,31,42,43] i=0 even_count=0 odd_count=0 while i<len(elements): if elements[i]%2==0: even_count=even_count+1 else: odd_count=odd_count+1 i=i+1 print("even_count",even_count) print("odd_count",odd_count)
from google.appengine.ext import db class Word(db.Model): langA = db.StringProperty() langB = db.StringProperty()
# Bisection method def bisection(f, a, b, tol=1e-5): lower, upper = a, b if f(a)*f(b)>=0: print("Method won't work. Needs opposite signs.") else: middle = 0.5*(upper + lower) while abs(f(middle)) > tol: if f(middle)*f(upper)<0: lower, upper = middle, uppe...
from ..connecting import connect2MySQL connect2MySql=connect2MySQL.connect2MySql # from connect2MySql.connecting.connect2MySQL import connect2MySql import xlsxwriter import pandas as pd import os class createScript(connect2MySql): def __init__(self, script, conObj) : self.script=script ...
N = int( input()) A = [(0,0)]*N for i in range(N): A[i] = ( int( input()), i) A.sort() ANS = [0]*N now = A[0][0] ans = 0 for i in range(N): a, j = A[i] if now == a: ANS[j] = ans else: now = a ans += 1 ANS[j] = ans for i in range(N): print( ANS[i]) ##print( " ".join( m...
from typing import Union from datetime import datetime from csv import DictReader from operator import gt, lt import bisect from dateutil.parser import parse, ParserError def _insort_reverse(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a...
# Generated by Django 2.2.3 on 2019-09-09 17:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tracks', '0017_exam_result_case'), ] operations = [ migrations.AddField( model_name='exam_result', name='times', ...
from flask import Blueprint,render_template,url_for from pybo.models import Question, Answer, User from datetime import datetime from pybo import db from werkzeug.utils import redirect bp = Blueprint('main', __name__, url_prefix='/') @bp.route('/test') def test(): for i in range(100): q = Question(subjec...
""" @Author : Laura @File : __init__.py.py @Time : 2020/4/16 18:24 """