text
stringlengths
8
6.05M
""" ********************************************************************* This file is part of: The Acorn Project https://wwww.twistedfields.com/research ********************************************************************* Copyright (c) 2019-2021 Taylor Alexande...
import cv2 import numpy as np camera = cv2.VideoCapture("2.mp4") #video dosyadan okundu. def nothing(x): pass cv2.namedWindow("frame") cv2.createTrackbar("H1","frame",0,180,nothing) #TRACKBAR OLUŞTURULDU. cv2.createTrackbar("H2","frame",0,180,nothing) cv2.createTrackbar("S1","frame",0,255,nothing)...
'''Convert to and from Roman numerals This program is part of 'Dive Into Python 3', a free Python book for experienced programmers. Visit http://diveintopython3.org/ for the latest version. ''' roman_numeral_map = (('M', 1000), ('CM', 900), ('D', 500), ...
#!/usr/local/bin/python3 # -*- conding: utf-8 -*- import os BASE_DIR = os.path.abspath(os.path.dirname(__file__)) # 定义配置基类 class Config: # 秘钥 SECRET_KEY = os.environ.get('SECRET_KEY') or '4329581751' # 数据库配置 SQLALCHEMY_TRACK_MODIFICATIONS = False MYSQL_USER = 'root' MYSQL_PASS = '' SQLA...
from sys import stdin N = int(stdin.readline().strip()) for i in range(0, N): r, e, c = [float(x) for x in input().split()] incwith = e - c incwithout = r if incwithout == incwith: print("does not matter") if incwithout > incwith: print("do not advertise") if incwithout < incwith: print("adve...
# The problem is here: # https://www.hackerrank.com/challenges/30-regex-patterns # This was perticularly enkoyable for me cause it was my first attempt # on regex #!/bin/python import sys import re N = int(raw_input().strip()) names = [] for a0 in range(N): firstName,emailID = raw_input().strip().split(' ') ...
from pandac.PandaModules import * #basic Panda modules from direct.showbase.DirectObject import DirectObject #event handling from panda3d.ai import * #panda AI from direct.actor.Actor import Actor import math, time class Enemy(object): def __init__(self, parent, spawnPos, AIpath): self.speed = 0.4 self....
# Exercício 5.2 - Livro i = 50 while i <= 100: print(f'Número {i}') i += 1
# Task3 import time from inspect import signature import numpy as np import inspect class decorator3: def __init__(self,fun): self.fun= fun decorator3.fun1 = fun decorator3.source = inspect.getsource(fun) self.arguments= [] decorator3.count= 0 self.exe_time = 0 def __call__(self,*ar...
import numpy as np import tensorflow as tf from tensorflow.contrib.slim import fully_connected from tensorflow.python.ops.rnn_cell_impl import _RNNCell as RNNCell import sys from dps import cfg from dps.config import DEFAULT_CONFIG from dps.train import training_loop from dps.env.room import Room from dps.rl import RL...
def singlenum(nums):
import sys import json import os path=sys.argv[1] libname=sys.argv[2] print(path) f=open(path,'r') jf=json.loads(f.read()) os.system('mkdir libs') os.system('mkdir libs/' + libname) versions=jf['versions'] print(versions) print('=====================') for v in versions: print('Installing ' + libname + ' ' + v) ...
from Deck import * from Player import * class Util: @staticmethod def moveListOrder(listv): if(type(listv) == list and listv!=[]): listv = listv[1:]+[listv[0]] return listv @staticmethod def chooseDirection(playerNameList,dir=True): if(len(playerNameList)>2 and dir =...
# -*- coding: utf-8 -*- """ Advenced String Analysis Methods contains of the following functions: - Wordstemm Cluster : wordstemm_clusters ... clusters lines of text into wordstemm items, groups them one-hot encodes them and returns a filtered dataframe with the original dat...
def convtobin(n,l): a=[] c=n while c>0: a.append(c%2) c=c/2 while len(a) < l: a.append(0) return a def bitwisedig(m,n,k): r = m % (2**k) if r < 2**(k-1): return 0 else: if n-m > 2**k -r-1: return 0 else: return 1 ...
import os from typing import Type import polars as pl __all__ = [ "Config", ] class Config: "Configure polars" @classmethod def set_utf8_tables(cls) -> "Type[Config]": """ Use utf8 characters to print tables """ os.environ.unsetenv("POLARS_FMT_NO_UTF8") # type: igno...
from math import log phi = (1 + 5 ** 0.5) / 2 def fib(n): ''' Find the Fibonacci number using Binet's formula. ''' return int(round((phi ** n - (1 - phi) ** n) / 5 ** 0.5)) def fibinv(f): ''' Inverse Fibonacci function using Binet's formula. ''' if f < 2: ...
# 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is the name of the person you like? \n") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 name1_lower_case = name1.lower() name2_lower_case = name2.lower() true...
from pywebio import * from pywebio.output import * from pywebio.input import * from pywebio.pin import * from pywebio.session import hold def put_pin_value(text): with use_scope('text_output', clear=True): put_text(text) def main(): put_table([ ['Commodity', 'Price / unit'], ...
import cv2 import numpy as np image = cv2.imread("image/picasso.jpg") cv2.imshow("Original",image) cv2.waitKey(0) mask = np.zeros(image.shape[:2],dtype = "uint8") (cX,cY) = ( image.shape[1] // 2 , image.shape[0] // 2 ) cv2.rectangle(mask,(cX-75,cY-75),(cX+75,cY+75),255,-1) cv2.imshow("Mask",mask) cv2.waitKey(0) prin...
from flask import Flask, render_template, request, jsonify import imdb APP = Flask(__name__) DEFAULT_SEASON = 1 @APP.route('/') def search_page(): return render_template('trivia.html') @APP.route('/show') def show(): opt_args = {} if 'year' in request.args.keys(): opt_args['year'] = int(reque...
from pyUbiForge.misc.file_object import FileObjectDataWrapper from pyUbiForge.misc.file_readers import BaseReader class Reader(BaseReader): file_type = '0E5A450A' def __init__(self, file_object_data_wrapper: FileObjectDataWrapper): # readStr(fIn, fOut, 184) file_object_data_wrapper.read_bytes(14) for _ in ra...
# Recursive Call def Fibonacci(num): if num <= 1: return num return Fibonacci(num-1) + Fibonacci(num-2) # Dynamic Programming - Fibonacci def DP_Fibonacci(num): cache = [0 for _ in range(num+1)] cache[0] = 0 cache[1] = 1 for index in range(2, num+1): cache[index] = cache[inde...
def read_line(linename,writename): with open(linename,'r') as f:#a+ 用seek(0) #f.seek(0) #开头位置 str=f.read() print(str) with open(writename,'w') as e: # e.seek(0) #开头位置 e.write(str) #read_line("D://hello.txt")
class Settings(): def __init__(self, LRslowMode = True, Slow = False, PrintLevel = 0): self.LRslowMode = LRslowMode self.Slow = Slow self.PrintLevel = PrintLevel
import pandas as pd import array df = pd.read_csv("IMDB_movies_dataset.csv", low_memory=False, error_bad_lines=False) df['language'] = df['language'].fillna('') filtered_csv = pd.DataFrame() for i in range(1960, 2020): temp = df[df['year'] == str(i)] filtered_csv = pd.concat([filtered_csv, temp], axis=0) filt...
# -*- encoding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from models import ItemAgenda from forms import FormItemAgen...
from project.settings import * # noqa DEBUG = True CELERY_TASK_ALWAYS_EAGER = True EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' ENABLE_HTTP_BASIC_AUTH = False DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' MEDIA_ROOT = os.path.join(MEDIA_ROOT, 'test')
import socket """ *****需求:模拟客户端向服务发起tcp链接请求******** 1. 创建客户端套接字 2. 发出连接请求 3. 收发数据 4. 关闭套接字 """ # 1. 创建客户端套接字 tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 获取服务器的IP地址和端口号 server_ip = input("请输入您要连接的服务器的ip地址:") server_port = int(input("请输入服务器的端口号:")) # 2. 向服务器发起连接请求 tcp_client_socket.connect((...
from elements.code_elements import GenericElement from elements.return_types import * class StringElement(GenericElement): return_type = STR def __init__(self, string: str): self.string = self._clean_string(string) def _clean_string(self, string): return string.replace('"', '""') de...
import datetime import json import random import time import traceback import faker import requests from tqdm import tqdm import os # Data source: # https://raw.githubusercontent.com/BlankerL/DXY-COVID-19-Data/master/json/DXYArea-TimeSeries.json fake = faker.Factory.create("zh-CN") api = "http://45.77.26.112/" api = ...
# Copyright (c) 2021 Mahdi Biparva, mahdi.biparva@gmail.com # miTorch: Medical Imaging with PyTorch # Deep Learning Package for 3D medical imaging in PyTorch # Implemented by Mahdi Biparva, April 2021 # Brain Imaging Lab, Sunnybrook Research Institute (SRI) from itertools import product import warnings def len_...
#!/usr/bin/env python __author__ = "Alessandro Coppe" ''' Given a set of directories with VarScan2 VCFs obtained from iWhale or vs_format_converter.py (varscan_accessories) it filters it using somaticFilter command from varscan.jar software ''' import argparse import os.path import os import sys import pathlib impor...
# -*- coding: UTF-8 -*-. import csv from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import LinearSVC from sklearn.metrics import accuracy_score STOP_WORDS="english" # STOP_WORDS=None MAX_FEATURES = 1000 MIN_DF = 0.1 MAX_DF = 0.5 # read cs...
import numpy as np import os def calculateTop50(inputDirName, outputDirName): fwrite = open(outputDirName,'w') matrix = np.loadtxt(inputDirName, dtype='float',comments='#', delimiter=None) matrix = matrix.transpose(); for i in range(matrix.shape[0]): output = matrix[i].argsort()[-50:][::-1] for j in range(50):...
print(2 + 5) print(10 - 4) print(5 * 7) print(60 / 6) print('2 + 5 =', 2 + 5) print('10 - 4 =', 10 - 4) print('5 * 7 =', 5 * 7) print('60 / 6 =', 60 / 6)
#Given a 32-bit signed integer, reverse digits of an integer. #Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: #[−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed #integer overflows. class Solution:...
from pid import PID from yaw_controller import YawController from lowpass import LowPassFilter import math import rospy GAS_DENSITY = 2.858 ONE_MPH = 0.44704 class Controller(object): def __init__(self, *args, **kwargs): # TODO: Implement # self.steer_pid = PID( -1.0987, -0.0047, -7.4110, mn = -0...
''' Interface to finds all the dependencies of package. ''' import sys import argparse from depfinder.finder import find_deps, generate_requirements def parse(args): ''' Parses arguments using argparse Parameters ---------- args: list of strings argument options and values Return...
""" Write a python function, check_anagram() which accepts two strings and returns True, if one string is an anagram of another string. Otherwise returns False. The two strings are considered to be an anagram if they contain repeating characters but none of the characters repeat at the same position. The length of the...
# -*- coding: utf-8 -*- from PIL import Image from django.core.files import File from selenium import webdriver import datetime import os import tempfile def make_screenshot(screenshot): # get screenshot driver = webdriver.Firefox() driver.get(screenshot.url) fd, filename = tempfile.mkstemp('.png') ...
#! /usr/bin/python3 from matplotlib import pyplot as plt from matplotlib import dates as mdates import matplotlib.ticker as ticker import sys class Item: #Item class constructor def __init__(self,ID,name,key,log,host_name,units): self.ID = ID self.name = name self.host_name = host_name ...
import lasagne import numpy as np from braindecode.veganlasagne.layers import transform_to_normal_net def get_layers(layers_or_layer_obj): """Either return layers if already a list or call get_layers function of layer object.""" if hasattr(layers_or_layer_obj, '__len__'): return layers_or_layer_obj...
print ('DESAFIO 01') nome = input ("Olá, qual o seu nome?") print ('Seja bem vindo ', nome, '! Prazer em te conhecer!')
import json from contextlib import closing from urllib.error import URLError, HTTPError from urllib.request import urlretrieve from os.path import basename from time import time import requests from urllib.parse import quote_plus as url_quote from logging import getLogger def _catch_err(req): if not req.ok: ...
""" A Schema is a more general container for Python objects. In addition to tracking relationships between objects, it can also keep other kind of indexing structures. Will need a more flexible query object that can represent comparisons. NOTE -- not sure if this is really worth it since it only kicks in with relati...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent import pytest from pants.backend.build_files.fmt.buildifier.rules import BuildifierRequest from pants.backend.build_files....
SomaIdade = 0 MaisVelho = 0 ContMulher = 0 for c in range(1,5): print(5*'-' + ' {}ª PESSOA' .format(c) + 5*'-') Nome = str(input('Nome: ')) Idade = int(input('Idade: ')) Sexo = str(input('Sexo [M/F]: ')).upper().strip() print(Sexo) SomaIdade += Idade if Sexo == 'M': if MaisVelho < Id...
import time import pyupbit import datetime import requests access = "your-access" secret = "your-secret" myToken = "slack-token" def post_message(token, channel, text): """슬랙 메시지 전송""" response = requests.post("https://slack.com/api/chat.postMessage", headers={"Authorization": "Bearer "+token}, ...
from selenium import webdriver class LoginPage(): # locate all the elements of page textbox_username_id = "Email" textbox_password_id = "Password" button_login_xpath = "/html/body/div[6]/div/div/div/div/div[2]/div[1]/div/form/div[3]/input" link_logout_linktext = "Logout" def __init__(self,drive...
UPDATE salary SET sex = CASE WHEN sex = 'm' THEN 'f' ELSE 'm' END;
'''Task 1. Проверить, что слово начинается и заканчивается на одну и ту же букву. [in]--> лол [out]--> True !!! [in]---> c [out]---> False (!!!!!!!!!) ''' message = input('Введите что-то: ').strip().lower() # храню передаваемое сообщение и убираю возможные пробелы if len(message) > 1: print(message[0] == message[...
from decouple import config, Csv class Settings: TELEGRAM_TOKEN = config('TELEGRAM_TOKEN', default='') ADMIN_USERNAMES = config('ADMIN_USERNAMES', default='', cast=Csv()) SENTENCE_COMMAND = config('SENTENCE_COMMAND', default='sentence') REMOVE_COMMAND = config('REMOVE_COMMAND', default='remove') V...
/Users/daniel/anaconda/lib/python3.6/genericpath.py
import pandas as pd import numpy as np # Read the dataset into a data table using Pandas df = pd.read_csv("ratings.csv", dtype={'userId': np.int32, 'movieId': np.int32, 'rating': np.uint8}) # Convert the running list of user ratings into a matrix using the 'pivot table' function ratings_df = pd.pivot_table(df, index=...
""" 2nd attempt: DP, learned from others the idea is to divide the problem into subproblems: for each amount, calculate the number of different combinations using the result from smaller amount e.g. dp[amount] = dp[amount] + dp[amount-coin] dp[4] = 1 + dp[2] it means 4 can be came up with 1111 and the dp[2]...
import numpy as np # シグモイド関数 # y = 1 / (1 + exp(-x)) # 不連続であるステップ関数を滑らかな関数に近似する。 def sigmoid(input): return 1 / (1 + np.exp(-input))
import re import difflib import string import pandas as pd from datetime import datetime from functools import wraps from flask import Flask, request, jsonify from jsonschema import validate, ValidationError, FormatChecker from enlevement_vehicule import SCHEMA_ENLEVEMENT_VEHICULE from entite_remettante import SCHEM...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 14 16:05:33 2018 @author: ck807 """ import os, glob import numpy as np import pandas as pd import cv2 i = 0 data_file = glob.glob('/local/data/chaitanya/landmarker/images/train/*.png') files = [] data_file_label = glob.glob('/local/data/chaitany...
xs = [] ys = [] try: while True: x, y = map(float, input().split()) xs.append(x) ys.append(y) except: pass ans = [] for i in range (0,len(ys)): div = 1 for j in range (0,len(xs)): if i == j: continue div = div * (xs[i] - xs[j]) ans.append( ys[i] / div ) ...
#!usr/bin/env python # -*- coding:utf-8 -*- import math import numpy as np import random def check(sr, rbsc, chromosome): m = np.size(sr, 0) n = np.size(rbsc, 0) for i in range(n): down_bandwidth = 0 up_bandwidth = 0 process = 0 for j in range(m): down_bandwidt...
program = [ {'mode': 'sweep', 'start': 8.9, 'stop': 7.6, 'dt': 10, 'nsteps': 1000}, {'mode': 'single', 'freq': 80, 'ampl': 0, 'phase': 0}, # {'mode': 'sweep', 'start': 10.7, 'stop': 8.7, 'dt': 10, 'nsteps': 1000}, # {'mode': 'sweep', 'start': 80, 'stop': 80.1, 'dt': 0.1} # {'mode': 'single', 'freq': 0, 'ampl': 0, 'ph...
# 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 in writing, software # d...
x = int(input()) halved_x = x >> 1 print('integer halved is {}'.format(halved_x))
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import os.path from typing import Iterable from pants.core.util_rules.config_files import ConfigFilesRequest from pants.core.util_rules.external_tool i...
a = [1, 2, 3, 4, 5, 6, 7] i = 0 while(a[i] <= 5): print(a[i]) i = i + 1 print("hello") a = 5 if(a % 2 == 0): print("even no") else: print("odd no") i = 4 if (i == 1): print("sparsh") elif (i == 2): print("prabal") elif(i == 3): print("dhruv") else: print("sorry")
import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Dense, Flatten, Conv2D from constants import nb_class class Classifier(Model): def __init__(self): super(Classifier, self).__init__() self.conv1 = Conv2D(6, kernel_size=(3, 3), strides=(2, 2), activation...
import csv import uuid import pymongo import geopy.distance client = pymongo.MongoClient( "mongodb+srv://admin:adminadmin@cluster0-dhc2n.mongodb.net/test?retryWrites=true&w=majority") db_posts = client.test_database.posts class LocationModel: @staticmethod def get_pin(args): # args: _id (pin id) # returns the pa...
# -*- coding: utf-8 -*- import urllib.request import json class DataTransferTestCase(object): def __init__(self, url): self.url = url def set_message_push_config_test(self): url = self.url + 'DataTransferSetMessagePushConfig' jroot = {} jroot['msg_code'] = 'valueType=long long' postData = json.dumps(j...
# website for wordcloud: http://www.wordclouds.com/ import math with open('website_WF.txt', 'r') as rf: with open('website_WF_Optimized_Text.txt', 'w') as wf: m = 0 for line in rf: line = line.replace('\n', '') line = line.split('\t') line[0] = int(math.log(int(line[0]), 1.2)) if line[0] >= 5: wf.w...
class NhpcDBException(Exception): def __str__(self): return self._msg class NhpcDBInvalidProperty(NhpcDBException): def __init__(self, props, data_type): self._msg = "'%s' properties invalid, should be %s" % (" ".join(props), data_type) class NhpcDBInvalidAttribute(NhpcDBException): def __...
#!/usr/bin/env /data/mta/Script/Python3.6/envs/ska3/bin/python ##################################################################################### # # # get_data_for_month.py: get a month amount of data and update data files ...
# -*- coding: utf-8 -*- # Personal Assistant Reliable Intelligent System # By Tanguy De Bels from Brains.social import * from Brains.utils import * from Brains.net import * from Brains.custom import * import Utilities.vars import Utilities.tools import Senses import os import re import pickle fro...
""" Module for reading ME6000 .tff format files. http://www.biomation.com/kin/me6000.htm """ import datetime import os import struct import numpy as np def rdtff(file_name, cut_end=False): """ Read values from a tff file. Parameters ---------- file_name : str Name of the .tff file to r...
""" Explorations for Sokoban. Fill free to add new exploration code here. """ import pygame from pygame.locals import * import common as C from utils import * import queue import heapq from time import time from math import sqrt class DFS: """ Classical Depth-First Search walkthrough of the level to discover...
import click import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry def error(*msg): msg = " ".join([str(x) for x in msg]) click.echo(click.style(msg, fg="red")) def warning(*msg): msg = " ".join([str(x) for x in msg]) click.echo(click.style(...
from __future__ import print_function import json import unittest import sys from peggy.peggy import PackratParser, Not, ZeroOrMore # References : https://github.com/antlr/grammars-v4/blob/master/json/JSON.g4 # TODO Think and optimize spaces class JsonParser(PackratParser): def __init__(self, text): r...
from __future__ import absolute_import, division, print_function import numpy as np import torch from pyemd import emd from collections import defaultdict from transformers import * def tokenize(text): """ Tokenizes a text and maps tokens to token-ids """ return tokenizer.convert_tokens_to_ids(tokenize...
from lib.imageManager import ImageManager import os import shutil class DirectoryManager(ImageManager): """ This class allows to manage all the categories with directory on the local disk. """ def __init__(self): """ Initiate the directory manager by creating the directory in data/cat...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Nov 16 16:33:02 2019 @author: chakra """ #A set is a collection which is unordered and unindexed. #In Python sets are written with curly brackets. thisset = {"apple", "banana", "cherry"} print(thisset) #sets are unordered so that you wont know what ...
import dex2 import sys import signal interrupted = False def signal_handler(signal, frame): global interrupted interrupted = True def interrupt_callback(): global interrupted return interrupted #Specify the model obtained from Snowboy website if len(sys.argv) == 1: print("MODEL NOT SPECIFIED"...
import sqlite3 from datetime import date, timedelta database = "C:\Program Files\lonchepos1.1.0_w10\database.db" connection = sqlite3.connect(database) cursor = connection.cursor() def fetchData(folio): query = "SELECT total, hora, nombre, notas FROM tickets WHERE folio = '{}';".format(folio) cur...
#!/usr/bin/env python import sys import os from flavorite import Recommender from combosaurus import load_data from datetime import datetime def find_closest_demo(): data = load_data('../data/dump_interests.tsv', '../data/dump_ratings_small.tsv') item_data = data['item_data'] recom = ...
import numpy as np #perform an expilicit march using euler approximation def eulerstep(input,grid,t,f,delta): new=[] #get shape of input row,col=input[0].shape #create a new array to contain the new time step for i in range(0,len(input)): array=np.zeros([row,col],float) new.append(ar...
# Generated by Django 3.1.5 on 2021-01-07 13:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Maker', fields=[ ...
from base64 import b64encode import base64 from collections import OrderedDict import json, csv, sys, os from re import split import re, requests from localSettings import * from logger import * from utilityTestFunc import * #===========================================================================================...
import requests import json from pprint import pprint # Gets user information url1 = f"https://api.github.com/users?" data = requests.get(url).json() user_list = [] for i in data: user_list.append(i['login']) for i in user_list: url = "https://api.github.com/users/{}/repos".format(i) data = requests.get(u...
#!/usr/bin/env python3 print("Name:Tyler Sperle") slicingFile = open('slicing-file.txt', 'r') listfiletext = slicingFile.readlines() slicingFile.close() A = listfiletext[24::3] print(A) B = listfiletext[2:5] print(B) C = listfiletext[12:-9][::-1][::2] print(C) D = listfiletext[10:-14] print(D) E = listfiletext[6...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Will create a new synthetic_cascades_thresholds.txt """ import pylab num_cascades = 4 num_stages = 800 thresholds = [0]*num_stages if False: # 2011 cascade (CVPR submission time) score_0 = -0.01 score_1250 = -0.03 score_2000 = -0.01 for i in range(num_sta...
# encoding: utf-8 from tastypie.fields import *
from pwn import * import time import sys def add(size): proc.sendlineafter(b':', b'1') proc.sendlineafter(b':', f'{size}'.encode()) def free(offset): proc.sendlineafter(b':', b'2') proc.sendlineafter(b':', f'{offset}'.encode()) def write(data): proc.sendlineafter(b':', b'3') proc.sendafter...
from django.shortcuts import render from django.http import HttpResponse from .models import Meetups def home(request): return render(request,'meetm/home.html') def user_home(request): context = { 'meetup': Meetups.objects.all() } return render(request,'meetm/user_home.html', context) def ...
from .. import Interpreter, adapter from ..interface import Block from typing import Optional import random class FiftyFiftyBlock(Block): def will_accept(self, ctx : Interpreter.Context) -> bool: dec = ctx.verb.declaration.lower() return any([dec=="5050",dec=="50",dec=="?"]) def process(self, ...
import sys import os import numpy as np import math class ALS: def __init__(self): print("init als") #原始评分表,m * n的评分表 def simple_train_set(self): train = np.array( [[3, 4, 5,2], [0, 1, 1,3], [0, 0, 1,2]] ) return train #计算差错 ...
import sys n = int(sys.stdin.readline()) time = list(map(int, sys.stdin.readline().split(' '))) time = sorted(time) incul = 0 deagi = 0 for v in time: incul += deagi + v deagi += v print (incul)
# Generated by Django 3.1.4 on 2020-12-18 22:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('recorder', '0001_initial'), ] operations = [ migrations.CreateModel( name='Manufacturer', ...
import urllib.request from bs4 import BeautifulSoup import csv from time import sleep import pandas as pd import json import urllib.request import os from PIL import Image import yaml import requests import sys import argparse import Levenshtein df = pd.read_excel('/Users/nakamurasatoru/git/d_genji/kouigenjimonogatari...
#!/usr/bin/env python import os, sys, tempfile, subprocess class_path = '"/Users/noji/Dropbox/tmp/stanford-corenlp-full-2015-12-09/*"' input_dir = '/Users/noji/Dropbox/data/penn3/PARSED/MRG/WSJ/' output_dir = os.path.dirname(os.path.abspath( __file__ )) + '/../section/' if not os.path.exists(output_dir): os.make...
word = str(input("Give me a word to check if it is a Palindrome:")) rev_word = word[::-1] if word == rev_word: print ("The word is a palindrome") else: print ("The word is not a palindrome")
#https://www.wsy.com/search.php?accurate=&search_type=item&q=%E7%94%B7%E8%A3%85 # 低优先