text
stringlengths
38
1.54M
import argparse class Options: def __init__(self): ap = argparse.ArgumentParser() ap.add_argument("--data_dir", default='datasets/records_albert', help="path to folder containing training/inference data.") ap.add_argument("--output_dir", default="output", help="inference output.") ...
import torch import numpy as np from PIL import Image from torchvision import transforms import os from . import global_vars class SceneDescriptionDataset(torch.utils.data.Dataset): def __init__(self, data, mappings, imgs_path): self.data = data self.mappings = mappings self.imgs_path = i...
from builder import Builder class BitBuilder(Builder): def __init__(self): self.__result = [] def result(self): return self.__result def __transform(self, char): if char == ' ': pass else: binary = bin(ord(char)) self.__result.append(bi...
from src.bingo import carton def contar_celdas_ocupadas(): mi_carton = carton() contador = 0 for fila in mi_carton: for celda in fila: contador = contador + celda return contador == 15 def test_no_menor_de_15(): assert contar_celdas_ocupadas() >= 15 def test_no_mayor_de_15():...
# @Time : 2018/11/14 下午7:15 # @Author : Kaishun Zhang # @File : my_perceptron.py # @Function: 小实验生成感知机模型 # 实验过程: # 先生成一些x属于[0,1) y属于[0,1)的数据 # 然后用y = -x + 1对数据进行标记 # 然后通过SGD进行参数更新 # 最后将结果进行可视化 import numpy as np import matplotlib.pyplot as plt class Perceptron(object): def __init__(self,iterator_num = 100 ,lea...
class Solution: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: if x == 0: return 0 forb = set(forbidden) if a in forb: return -1 q = deque([(a, 'f', 1)]) v = set([(a, 'f')]) while q: pos, dr, j = q.popl...
from models.common import MusicObject, defaultAge import db.basic as dbm class Artist(MusicObject): def __init__(self, id = 0, name = "", country="", location="", image="", age=defaultAge, gender=GenderEnum.MALE, isBand=BandEnum.UNKOWN, status=StatusEnum.ACTIVE, genre=None, lyricalThemes="...
#coding=utf-8 import time import hashlib import requests import json import urllib2 def md5(s): m = hashlib.md5(s) return m.hexdigest() def push_broadcast(appkey, app_master_secret, device_token, custom_content): timestamp = int(time.time() * 1000 ) method = 'POST' url = 'http://...
# -*- coding: utf-8 -*- import hashlib import json from time import time from urllib.parse import urlparse
# Write a program which asks the user to enter a positive integer 'n' # (Assume that the user always enters a positive integer) and # based on the following conditions, prints the appropriate results exactly # as shown in the following format (as highlighted in yellow). # when 'n' is divisible by both 2 and 3 (for exa...
# -*- coding: utf-8 -*- """ Here we present the MLPy through a graphical user interface (based on pygame). """ import pygame import random import sys from ehrlesamson import * from mlpcore.mlp import MLP import time displaySize = (1024,600) # for widescreen # The background of the screen BGCOLOR = (127,1...
# import numpy as np # import math # from pylab import * # from scipy import stats # from mean import Mean # import matplotlib # import matplotlib.pyplot as plt # import matplotlib.mlab as mlab # from scipy.stats import norm # # # class Env1(object): # def __init__(self): # m = Mean() # # 固定量 # ...
from selenium import webdriver from selenium.webdriver import ChromeOptions, FirefoxProfile from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.w...
from flask import Flask from flask import jsonify, request from flask.ext.pymongo import PyMongo from flask_pymongo import PyMongo from flask_cors import CORS app = Flask(__name__) CORS(app) app.config['MONGO_DBNAME'] = 'athlete_profile' app.config['MONGO_URI'] = 'mongodb://gauravp966:qwe123@ds257838.mlab.com:57838/a...
# def increment(list1): # str1 ='' # for number in list1: # str1 += str(number) # result = int(str1)+1 # finish = list(str(result)[-1:-5:-1]) # finish.reverse() # newlist = [int(x) for x in finish] # return newlist # # print (increment([0,0,9,9])) # a = [0,8,9,9] # def s(n): # ...
import scripts from flask import redirect from query_parser import QueryParser from settings import Settings class QueryHandler: def __init__(self, query_parser): self.query_parser = query_parser def handle_query(self, aliases): if self.query_parser.alias not in aliases: # Need to ...
# -*- coding: utf-8 -*- import atexit import sys import traceback import time import threading import requests from data import bot, Userdata, users, answers, getUsername, top100indexes, botSendMessage, Answer import authors from recommendation import initData, startFunc, recomendationFunc, showResult from top100 imp...
#!/bin/python import os import sys import time import convnets import train IMDIR = "images/raw" def TimedTrainingRun(images, net, train_fn): mark = time.time() train_fn(images) return time.time() - mark def main(base_net, size, starting_batch_size, runs, reps): handles = [os.path.join(IMDIR, h) for h i...
import numpy as np def derivative(x, dt=1.) : """ Compute time-derivative of the data matrix X along first axis. Parameters ---------- X : array-like, shape (n_samples,n_features) Input variables. dt : double precision. Time step. Returns ------- dX : array-l...
print("Hello, World!") #这是一个注释 # print("Hello\nWorld!") #这是一个换行 \n print("Hello\\World!") #这是一个转义符 \ #转义字符 特殊的字符 无法”看见“的字符,与语言本身语法有冲突的字符。 # \ 续航 \n 换行 \' 单引号 \t 表示空4个字符,就是缩进,就是按一下tab键 \r 回车 print(r"01234\n56789") #把字符变成一个原始字符串 r print("0123456"[-1]) #得倒数第一个字符 print("01234...
#! python3 # __author__ = "YangJiaHao" # date: 2017/10/23 from queue import Queue class Node(object): def __init__(self, val=-1, left=None, right=None): self.val = val self.left = left self.right = right class BinaryTree(object): def __init__(self, root=None): self.root = roo...
from app.models.player import * games = [ { "selection_1" : "rock", "selection_2" : "paper", "result" : "lost to"}, { "selection_1" : "rock", "selection_2" : "scissors", "result" : "won against"}, { "selection_1" : "rock", "selection_2" : "rock", "result" : "tied with"}, { "selection_1" : "paper", "sel...
# encoding=utf-8 ############################################################################################## # @file:baozouvideocomments.py # @author:Yongjicao # @date:2016/11/21 # @version:Ver0.0.0.100 # @note:暴走漫画视频频道获取评论的文件 ##############################################################r##########################...
#Usage : python seminar.py > Log-<Date>.txt import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup from os import mkdir, makedirs import re import nltk, string from sklearn.feature_extraction.text import TfidfVectorizer import csv import requests ...
from nitime.analysis.base import BaseAnalyzer import numpy.testing as npt def test_base(): """Testing BaseAnalyzer""" empty_dict = {} input1 = '123' A = BaseAnalyzer(input=input1) npt.assert_equal(A.input, input1) npt.assert_equal(A.parameters, empty_dict) input2 = '456' A.set_inpu...
from pwn import * local = False elf = 'easy_bof' if local: context.binary = './'+elf r = process("./"+elf) else: ip = "sqlab.zongyuan.nctu.me" port = 6000 r = remote(ip,port) context.arch = 'amd64' addr = payload = r.recvuntil(':') r.sendline(payload) r.interactive()
import requests class HTTP_NotOK(Exception): def __init__(self, httpStatusCode, message): super().__init__(message) self.HttpStatusCode = httpStatusCode class AutoGradrClient: def __init__(self, email, password): self.__baseUrl = "https://autogradr.app/api" ...
import matplotlib.pyplot as plt from matplotlib import rcParams import numpy as np import Conductance import weave from numpy.linalg import inv from ThresholdModel import * from Filter_Rect_LogSpaced import * from Tools import reprint class GIF(ThresholdModel) : """ Generalized Integrate and Fire model ...
# -*- coding: utf-8 -*- """Test the base nested sampler""" import datetime import os import pickle import pytest import time from unittest.mock import MagicMock, create_autospec, patch from nessai.samplers.base import BaseNestedSampler @pytest.fixture def sampler(): obj = create_autospec(BaseNestedSampler) o...
import os import re def regex_match(text_file, regex): if not os.path.isfile(text_file): return "file not found" f = open(text_file) lines = f.read() f.close() # The re.compile() function accepts a flag, re.DOTALL, which is useful here. It makes the . in a regular expression match all cha...
import pytest from yamlpath.differ.enums.aohdiffopts import AoHDiffOpts class Test_differ_enums_aohdiffopts(): """Tests for the AoHDiffOpts enumeration.""" def test_get_names(self): assert AoHDiffOpts.get_names() == [ "DEEP", "DPOS", "KEY", "POSITION", "VALUE", ] def test_get_choices(self): ...
from HardwareRepository.BaseHardwareObjects import HardwareObject import os import sys class RobodiffController(HardwareObject): def __init__(self, *args): HardwareObject.__init__(self, *args) def init(self, *args): sys.path.insert(0, self.getProperty("source")) config = __import__("config", globa...
#!/usr/bin/env python import argparse import os import sys from pprint import pprint parser = argparse.ArgumentParser() parser.add_argument('--result_dir', help='Output directory for images and model checkpoints [default: .]', default='.') parser.add_argument('--epochs', type=int, default=1000, help='number of epochs...
# 6kyu - Collatz """ A collatz sequence, starting with a positive integern, is found by repeatedly applying the following function to n until n == 1 : collatz sequence n = { n / 2 for even n ; 3n + 1 for odd n } ======= Create a function collatz that returns a collatz sequence string starting w...
import smtplib from email.mime.text import MIMEText # conexão com os servidores do google smtp_ssl_host = 'smtp.gmail.com' smtp_ssl_port = 465 # username ou email para logar no servidor username = 'jacksonenazus@gmail.com' password = 'AmoraLoh' from_addr = 'jacksonenazus@gmail.com' to_addrs = ['jacksonenazus@gmail.co...
#Block Class #Contributors: Ben Coorey import rhinoscriptsyntax as rs import Rhino.Geometry as rg import scriptcontext as sc import Rhino as rh import System.Drawing.Color as col import urbansimulator as us import math, random class Block(us.typedSurface): #Define and initiate the class def __init__(self,...
import leased_ip from netmiko import ConnectHandler import time import re def sudo_mn(ip): mininet={ 'device_type':'linux', 'username':'mininet', 'password':'mininet', 'ip':ip, } #connect to mininet vm conn=ConnectHandler(**mininet) #starting up default mininet topolo...
import json import os class ViaResource: def __init__(self, json_path=None): if json_path: self.load(json_path) def load(self, json_path): with open(json_path) as json_file: self.data = json.load(json_file) def save(self, save_path): with open(save_pa...
a = [1,2,3,4,5,6,7,8,9,10] print(a) temp=0 b=[] c=[] #Initially sorting is done for j in range(len(a)): i = 0 while i<len(a)-1: if a[i]>a[i+1]: #swapping temp=a[i] a[i]=a[i+1] a[i+1] = temp i = i+1 for j in range(len(a)): ...
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='django-tasks', version='0.2', description='Python Django Tasks.', author='Luan Fonseca', author_email='luanfonceca@gmail.com', url='https://github.com/luanfonceca/todo-list/', packages=find_packages(), ...
import importlib.resources as pkg_resources import logging import random import discord from discord import Interaction, app_commands from discord.ext import commands from milton.core.bot import Milton from milton.utils.paginator import Paginator from milton.utils.tools import get_random_line log = logging.getLogger...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """generate a integer sequence for testing""" import numpy as np def generate_sequence(count=30): return [np.random.randint(0, 100) for i in range(count)]
#반복문:while #조건이 참일동안 실행 # while True: # print('python') #1부터 10까지 출력 # a=0 # while a<10: # a += 1 # print(a) #실습)1~10까지 합을 출력 # s=0 #합계를 누적할 변수 # a=0 #증가하는 변수 # while True: # a +=1 #a=a+1 # if a>10: break # s += a #s=s+a # print(s) #a가 증가하면서 누적합계를 구하고 그 합계가 2000이 넘으면 종료한다 #1) # s=0#합계누적변수 # ...
from django import template register=template.Library() @register.filter(name='currency') def currency(number): return "₹ " + str(number) @register.filter(name='multiply') def multiply(number1,number2): return number1*number2 @register.filter(name='status') def status(flag): if flag: return ...
# myinfo = {'Username' : 'asifulmamun', # 'Name' : 'Al Mamun', # 'Mobile' : '01721600688' # } # print(str(myinfo['Username'])) # for keys, values in myinfo.items(): # print(keys, values) users = { 'mamun' : { 'Name' : 'Al Mamun', 'Age' : '22', 'Dist' : 'Kishor...
"""karmaapp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-base...
"""4. Написать функцию-генератор cycle которая бы возвращала циклический итератор.""" def cycle(iterator): """функция-генератор, которая возвращает циклический итератор""" li = [] for element in iterator: li.append(element) yield element n = 0 le = len(li) while True: y...
import optparse import StringIO from django.core.management.base import BaseCommand from django.db.utils import IntegrityError from django.template.defaultfilters import slugify from easy_thumbnails.exceptions import InvalidImageFormatError from easy_thumbnails.files import get_thumbnailer from courseware.courses im...
class Solution: def integerReplacement(self, n: int) -> int: @lru_cache(None) def dfs(num): if num == 1: return 0 if num % 2 == 0: return 1 + dfs(num // 2) else: return 1 + min(dfs(num+1), dfs(num-1)) return ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 27 01:47:21 2019 @author: arohan """ import numpy as np import cv2 import pandas as pd # Get the names of the output layers def getOutputsNames(net): # Get the names of all the layers in the network layersNames = net.getLayerNames() # ...
# -*- coding:utf-8 -*- ''' Author: Feng Wenqiang E-mail: hoontu@sina.com ''' import socket def hostname(): return (socket.gethostname()) page_num = 2 SITE = r'文强原始凭证查询系统' SITEURL = hostname() PORT = 8080 cookie_secret = '123456789abcdef' torlite_template_name = 'torlite_template'
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error # Load the data data = np.loadtxt('zip.train') y = data[:, 0] X = data[:, 1:] # Split the data into training...
import os import sys import platform from os import path from setuptools import setup, Extension from distutils.command.config import config as CommandConfig from distutils.dist import Distribution from sipdistutils import build_ext as sip_build_ext from gitversion import get_git_version try: from PyQt4 import py...
s1,s2=map(str,input().split()) f=1 t1=list(set(s1)) t2=list(set(s2)) for i in range(len(t1)): if(t1[i] not in t2): f=0 break for j in range(len(t2)): if(t2[i] not in t1): f=0 break if(f==1): print("true") else: print("false")
from pathlib import Path import matplotlib as mp import matplotlib.pyplot as pl import seaborn as sns import pandas as pd import numpy as np import math def status(x,i): """ Helper function to get a list of data with contain trip id and other statistical info :param x: a column in original dataframe (dist...
class Solution(object): def dailyTemperatures(self, T): """ :type T: List[int] :rtype: List[int] """ t = collections.defaultdict(int) res = [ 0 for i in range(len(T))] for i in range(len(T)-1, -1, -1): temp = T[i] j = self.getMaxIndex(...
''' Text Type (String) ''' #s = "This is a single line string" #print(s) #print(type(s)) #s = """this is a multiline #string example""" #print(s) #=============== #Find a character by index #s = 'string example' #print(s[5]) #slicing #s = 'string example' #print(s[2:5]) #Rememeber the count for the left for slic...
__author__ = "Dihia BOULEGANE" __copyright__ = "" __credits__ = ["Dihia BOULEGANE"] __license__ = "GPL" __version__ = "0.1" __maintainer__ = "Dihia BOULEGANE" __email__ = "dihia.boulegane@telecom-paristech.fr" __status__ = "Development" from skmultiflow.utils import * from utils.functions import * from utils.metrics ...
__author__ = 'zafarali' #To change this template use Tools | Templates. # # ## plotting stuff # import plotly.plotly as pltly # from plotly.graph_objs import * # import plotly.tools as pltls from CellularPottsModel import CellularPottsModel from EnergyFunction import EnergyFunction from Cell import Cell from CustomEn...
#!/usr/bin/env python3 """ Given a filaname, try to open that file, which should contain a JSON object containing a username and password, then test that against PAM printing out a JSON object that is authenticated and is true or false """ import cgi # If things are not working, then this should be enabled for better ...
# Copyright 2020 Lorna Authors. All Rights Reserved. # 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 appli...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 1/5/2019 11:35 PM # @Author : 王金波 # @File : chess_piece_bodyguard.py from util import * from chess_piece import ChessPiece class ChessPieceBoyguard(ChessPiece): ''' desc: 将当前棋子随机移动。(不同category棋子移动规律与范围不同)。穷举法: 对方 ...
from Stack import Stack def reverseList(arr): stack = Stack() for x in arr: stack.push(x) for x in range(len(arr)): arr[x] = stack.pop() return arr print(reverseList([1, 2, 3])) print(reverseList([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
"""Setup the members.afpy.org application""" import logging from members.config.environment import load_environment log = logging.getLogger(__name__) def setup_app(command, conf, vars): """Place any commands to setup members here""" load_environment(conf.global_conf, conf.local_conf)
import requests from seafileapi.utils import urljoin from seafileapi.exceptions import ClientHttpError from seafileapi.repos import Repos class SeafileApiClient(object): """Wraps seafile web api""" def __init__(self, server, username=None, password=None, token=None): """Wraps various basic operations t...
import numpy as np print("-"*50) print("--------- Numpy ndarray -----------------") a=np.arange(3) for it in np.nditer(a,op_flags=["readwrite"]): print(type(it)) print(it[...]) ## as 'it' is of type ndarray, it[...] gives ndarray # containing single value (current element pointed by iter) print("-"*50) ...
import requests # def gen_headers(bearer): # headers = { # "Accept": "*/*", # "Accept-Encoding": "gzip, deflate", # "Accept-Language": "en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5", # "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (K...
""" Cost model for computing weighted score for a layout """ from collections import namedtuple import copy import json import numpy as np import os from pprint import pprint import sys from pprint import pprint # import constants from cost import CANVAS_WIDTH, CANVAS_HEIGHT ALIGN_TOLERANCE_DELTA = 0 LeafFeature = na...
# Conversion program to convert kilos to pounds and vice-versa ans = raw_input("kg or lb: ") num = raw_input("weight: ") def from_kilograms(kilos): return kilos * 2.2 def from_pounds(pounds): return pounds / 2.2 def conversion(): if ans == "kg": print from_kilograms(int(num)), "pounds" elif ans == "lb": ...
""" For this to work you have to install pdfkit and wkhtmltopdf see: https://github.com/JazzCore/python-pdfkit VERY IMPORTANT: IN LINUX a bug had to be solved by patching the pdfkit library: Had to install xvfb: sudo apt-get install xvfb And then add 'xvfb-run' infront of the wkhtmltopdf command inside the library do...
#!/usr/bin/env python3 # Unfortunately python3 does not seem to work on FreeBSD # Welcome Wizard # Copyright (c) 2020-2021, Simon Peter <probono@puredarwin.org> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condit...
import operator import numpy as np def BBox_Dice(true_bbox_txt, pred_bbox_txt): f = open(true_bbox_txt, "r") true_Boxes = [] while True: line = f.readline() if not line: break elements = line.split() if(len(elements)): continue ...
import pandas as pd import math import numpy as np with open('data.txt') as f: lines = [int(line.rstrip()) for line in f] sol = [] for x in lines: for y in lines: for z in lines: if x + y + z == 2020: sol.append(x) sol.append(y) sol.append(z)...
#!/usr/bin/ python import threading import socket if __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from helpers.soc import Socket from helpers.torrent import Torrent from helpers.db import DB else: from ..helpers.soc import...
from flask import Blueprint bp = Blueprint('Naver', __name__, url_prefix='/naver') @bp.route('/movie') def hello_Naver(): return '네이버 영화정보 입니다.'
# Generated by Django 2.2.9 on 2020-02-04 12:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('App2', '0003_order'), ] operations = [ migrations.AddField( model_name='person', name='p_delete', field=...
# -*- coding: utf-8 -*- """ Created on Thu Apr 25 05:28:51 2019 @author: KCLIANG Helper functions for biophotobot. """ from sklearn.feature_extraction.text import HashingVectorizer from sklearn.externals import joblib import pandas as pd import numpy as np from unidecode import unidecode import string import json from...
quantidade = int(input()) for i in range(quantidade): frase = input() metade = round((len(frase) / 2) - 1) new_frase = frase[metade::-1] new_frase += frase[-1:metade:-1] print(new_frase)
# Copyright (c) 2014. Mount Sinai School of Medicine # # 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 o...
[epydoc] name: Tor Weather output: html target: api/ introspect: no exclude: stem, django, manage, settings, tests private: yes
from django.shortcuts import render, HttpResponse, redirect from .models import Course, Description # from datetime import date from django.contrib import messages # Create your views here. def courses(request): if request.method == 'GET': print('ES UN GET') context = { "courses" : Cou...
#price = [2,1,2] #query = [1,2,3] # answer = [2,1,1,1,1] #price = [2,2,2] #query = [1,2,3] # answer = [3,2,1] #price = [2,1,2] #query = [1,2,3] # answer = [2,1,1] dict = {} #adding key and their count as values in dictionary for i in price: if i not in dict: dict[i] = 1 else: dict[i] = dict[...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Upgrade file generator""" import getpass from intelhex import IntelHex import click import core.signature as sig from core.blsection import * __author__ = "Mike Tolkachev <contact@miketolkachev.dev>" __copyright__ = "Copyright 2020 Crypto Advance GmbH. All rights reser...
def get_code_options(plugin_classes): """ Return AiiDA codes using a specific set of plugins :param plugin_classes: a dictionary of the type {'pw': 'quantumespresso.pw', 'ph': 'quantumespresso.ph'} where the key is a label and the value is the plugin to check for. It will return the s...
#!/usr/bin/env python # -*- coding: utf-8 -*- import configparser import logging import requests from operator import attrgetter from flask import render_template from wptdash.github import GitHub CONFIG = configparser.ConfigParser() CONFIG.readfp(open(r'config.txt')) APP_DOMAIN = CONFIG.get('app', 'APP_DOMAIN') ORG...
""" Unified interfaces to root finding algorithms. Functions --------- - root : find a root of a vector function. """ __all__ = ['root'] import numpy as np ROOT_METHODS = ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson', 'linearmixing', 'diagbroyden', 'excitingmixing', 'krylov', 'df-...
# o(nlog(n)) def find_max_cross_subarray(array, low, mid, high): left_sum = array[mid] Sum = array[mid] left_index = mid for i in range(mid-1, low-1, -1): Sum += array[i] if Sum > left_sum: left_sum = Sum left_index = i right_sum = 0 Sum = 0 right_inde...
import json from wtforms import Field class DictField(Field): def _value(self): return self.data def process_data(self, value): if value is None: self.data = None if isinstance(value, dict): self.data = value elif isinstance(value, basestring): ...
import test_case _CASE = """\ -1000000000 0 -1000000000 0 """ test_case.test_input(_CASE) ########### # code ########## a, b, c, d = map(int, input().split()) print(max(max(a * c, a * d), max(b * c, b * d))) # 最大になるパターンは # 範囲がプラス側のみの場合、`-x * -y, x * y` # 範囲がマイナス側のみの場合は` -x * x, x * -y`
import abc class GameState(abc.ABC): '''Abstract Game State''' def __init__(self, game): self.game = game @abc.abstractmethod def on_enter(self): pass @abc.abstractmethod def run(self): pass @abc.abstractmethod def exit(self): pass
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_laz...
"""Parse My Clippings highlights from kindle.""" import re from typing import Any from typing import List from textwrap3 import wrap # import dateparser regexp_author = re.compile(r"\((.*?)\)", re.IGNORECASE) regexp_map = { "es": { "regexp_page": re.compile(r"página ([0-9]+)", re.IGNORECASE), "re...
# -*- coding:utf-8 -*- # 问题 # 你想使用 Unix Shell 中常用的通配符(比如 *.py , Dat[0-9]*.csv 等)去匹配文本字符串 # 解决方案 # fnmatch 模块提供了两个函数—— fnmatch() 和 fnmatchcase() ,可以用来实现这样的匹配。用法如下: from fnmatch import fnmatch, fnmatchcase print(fnmatch('foo.txt', '*.txt')) # True print(fnmatch('foo.txt', '?oo.txt')) # True print(fnmatch('Dat45.csv',...
from items.ItemBase import ItemBase, ItemType class ZapItem(ItemBase): def __init__(self): self._cost = 15 self.owner = None @property def cost(self): return self._cost @property def type(self): return ItemType.PASS # we can't compute how many coins the play...
import os from OnlineBridge import db, CONV_CARD_FOLDER from utilities.sluggenerator import create_random_slug from datetime import datetime playercards = db.Table( 'playercards', db.Column('member_id', db.Integer, db.ForeignKey('members.id', ondelete='CASCADE'), primary_key=True), db.Column('convcards_id...
import sys thismodule = sys.modules[__name__] import json import tutum import requests from bunch import Bunch class A(object): pass def func(self): import time from firebase import firebase a = A() start = int(round(time.time() * 1000)) def logms(step): end = int(round(time.time() * 1000)) self.info(sel...
import bottle @bottle.route('/') def homepage(): mythings=['apple','mango','pine','blueberry'] return bottle.template('hello.tpl',{'username':'hari','things':mythings}) @bottle.post('/fav_fruit') def fav_fruit(): fruit=bottle.request.forms.get("fruit") if fruit==None: fruit="Not Selectd" ret...
from django.urls import path from . import views app_name="encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("create",views.create,name="create"), path("wiki/<str:title>",views.entry_page,name="entry"), path("random",views.random_page,name="random"), path('wiki/<str:title>/e...
""" Query type related functions. ALiPy implements IJCAI'15 Multi-Label Active Learning: Query Type Matters (AURO) method which queries the relevance ordering of the 2 selected labels of an instance in multi label setting, i.e., ask the oracle which of the two labels is more relevant to the instance. Due to the less a...
# Imports # Functions def apply_model(my_tweets, my_tokenized_tweets, my_model): """This function combines both aggr_df data frames into one Args: my_tweets (pandas.core.frame.DataFrame): The tweets to be labelled my_tokenized_tweets (pandas.core.frame.DataFrame): The tokenized form of the t...