text
stringlengths
38
1.54M
import asyncio, discord from discord.ext import commands from config import token from service.crawling import Crawling from service.statistics import Statistics from service.utils import Util my_token = token game = discord.Game("도움말 : !도움말") bot = commands.Bot(command_prefix="!", status=discord.Status...
""" The same appearence as in Jupyter Notebook, except bold font for the header and interleaved backround for rows. """ from IPython.display import display import numpy as np import pandas as pd df = pd.DataFrame({ 'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Series(1, inde...
# Generated by Django 3.2 on 2021-04-12 11:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Categories', fields=[ ...
#import sys, os, socket #ipdefine contains the list of IP addresses we want to check import subprocess import ipdefine #Let's see if the device is on the network right now #for device, ipadd in ipdefine.ip_address.iteritems(): # try: # socket.gethostbyaddr(ipadd) # # If previous line doesn't throw exc...
# -*- coding: utf-8 -*- from PIL import Image import os image_directory = '/Users/vdtang/Documents/test' grayscale_directory = '/Users/vdtang/Documents/test_grayscale' if not os.path.isdir(grayscale_directory): os.makedirs(grayscale_directory) counter = 0 for file in os.listdir(image_directory): if file.lower...
from sys import argv, stdout, displayhook, path script, first, second, third = argv #from sys import * #script = stdout, #first = displayhook, #second = path, #third = argv print "The script is called: ", script print "Your first variable is: ", first print "Your second variable is: ", second print "Your third vari...
#! /usr/bin/python from __future__ import print_function import os, sys, re #### REAL DEMO VERSION TAB = '\t' HOSTS = '/etc/hosts'; HOSTS = './hosts' MDN = 'md.ddn.com'; MDN = 'homerj' IME = 'ime.' + MDN; IME = 'homerj' TOP = '/var/named/'; TOP = './' #TOP = '/etc/named' #TOP = '/etc/dhcp' SOA = TOP + 's...
def dateexam(d, m, y): ''' Функция принимает дату и проверяет её на достоверность ''' d_31 = [1, 3, 5, 7, 8, 10, 12] d_30 = [4, 6, 9, 11] if (y <= 2021) and (y > 0 and m > 0 and d > 0 and m < 13 and d < 32): if (y < 2021) or (y == 2021 and m < 10) or (y == 2021 and m == 10 and d <= 9): ...
# -*- coding: utf-8 -*- """ computes the lag of the amdf function Args: x: audio signal iBlockLength: block length in samples iHopLength: hop length in samples f_s: sample rate of audio data (unused) Returns: f frequency t time stamp for the frequency value """ import numpy as np impo...
import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from statsmodels.graphics.tsaplots import plot_acf from statsmodels.graphics.tsaplots import plot_pacf def plotDataset(dataset): values = dataset.values figure, axes = plt.subplots(nrows=len(dat...
# Exercise 3 # Take a list, say for example this one: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # and write a program that prints out all the elements of the list that are less than 5. # Extras: # Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this # list ...
#!/usr/bin/python import socket from hashlib import md5 import socket import sys import threading def modify(message): print("\033[91m[!]\033[00m Start modification of request...") #### START IMPLEMENTING YOUR LOGIC HERE #### END response = message print("\033[91m[!]\033[00m Modified reques...
import matplotlib.pyplot as plt import __builtin__ as base from numpy import * from numpy.random import rand, randn, permutation, randint class agent(object): def __init__(self, environment): assert(isinstance(environment, gridworld)) self.environment = environment self.__init_Qmap() ...
import numpy as np #0.15582822 if __name__ == "__main__": x, y = 1, 2 p, q = 3, 4 r = 1 for %R %x in (*.jpg) do ( for /f "tokens=1-3 delims=. " %%F in ("%%A") do ( set /a a=%%G set zeros= if !a! LSS 1000 set zeros=0 if !a! LSS 100 set zeros=00 if !a! LSS 10 set zeros=...
from django.contrib.sitemaps import Sitemap from dish.files.models import ( Model_1, Model_2, ) class CuisinesSitemap
import gensim, logging, os logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) import stat import fileinput import time import random import sys, traceback import subprocess from subprocess import Popen, PIPE import cPickle import re import gzip class MySent...
class Solution: def shortestPalindrome(self, s): A = s + "*" + s[::-1] lps = [0] for i in range(1, len(A)): index = lps[i - 1] while index > 0 and A[index] != A[i]: index = lps[index - 1] lps.append(index + (1 if A[index] == A[i] else 0)) ...
"""Evan, please check in the latest version, so that I can start from it""" from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.contrib import rnn import random import collections import time start_time = time.time() def elapsed(sec): if sec<60: return str(sec)...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import time import pycurl import pymysql import subprocess from multiprocessing import Pool # 导入配置文件 from config1 import * # 记录日志 def write_log(e): # 异常出现时间 err_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 异常信息 error_info = "[%s] %s...
from data import data_manager def get_shows(page): page_number = int(page) data = data_manager.execute_select( f'''SELECT * FROM shows ORDER BY rating DESC LIMIT 15 OFFSET {15 * page_number}; ''') return data # def get_pagination(): # data = dat...
# 1. Создать класс для сериализации данных Serializer. Объект класса принимает на вход сложный объект(list, dict, etc), и обладает методами loads и dumps. Эти методы работают так же как и json.loads и json.dumps. # 2. dumps принимает на вход один параметр - contetnt_type(это может быть json или pickle) и на выходе возв...
import torch from torch import nn M = {} def setup(opt, checkpoint): print('=> Creating model from file: models/' .. opt.netType .. '.lua') model = require('models/' .. opt.netType)(opt) if checkpoint: modelPath = paths.concat(opt.resume, checkpoint.modelFile) assert(paths.filep(modelPath...
import dash import dash_core_components as dcc import dash_html_components as html app = dash.Dash() df = [{'x':[1,2,3,4,5], 'y':[1,4,9,16,25] , 'type':'line', 'name':'boats'}, {'x':[5,4,3,2,1], 'y':[9,8,7,6,5] , 'type':'bar', 'name':'cars'}, ] ''' dict = [{'x': ['abhi','lovee','ishu','mo...
import pickle s = 'Hola mundo' print(s) print(type(s)) se = s.encode() print(se) print(type(se)) sp = pickle.dumps(s) print(sp) print(type(sp)) ss2 = pickle.loads(se) print(ss2) print(type(ss2)) # No imprime debido a que encuenra una h primero en lugar de la direccion \x80
def ispalindrome(n): liste=list(str(n)) liste2=list(reversed(liste)) return liste==liste2 def sominv(n): liste=list(str(n)) liste2=reversed(liste) chaine="".join(liste2) n1=int(chaine) return n+n1 def islychrel(n): for _ in range(1,51): if ispalindrome(sominv(n)): re...
from collections import Counter import itertools import re import numpy as np class Moon(object): def __init__(self, line): self.pos = np.array([int(s) for s in re.findall(r'[-\d]+', line)]) self.vel = np.array([0]*len(self.pos)) def __repr__(self): return '%s, %s'%(self.pos, self.vel)...
# coding = utf-8 # @Time : 2021/7/15 16:59 # @Author : pengjiangli # @File : Pytest04.py # @Software: PyCharm # @contact: 292617625@qq.com import pytest ''' 如果一个方法或者一个class用例想要同时调用多个fixture,可以使用@pytest.mark.usefixture()进行叠加。注意叠加顺序,先执行的放底层,后执行的放上层。 ''' @pytest.fixture() def test1(): print('\n开始执行function1') @pyte...
from airflow.models import DAG from datetime import datetime from airflow.operators import BashOperator from airflow.operators import PythonOperator dag =DAG( dag_id='testdag', schedule_interval=None, start_date=datetime.now() ) def check_stat(**kwargs): context=kwargs print(context['...
""" author: Dr. Mohammed Zia https://www.linkedin.com/in/zia33 Problem Statement: You are given N elements and your task is to Implement a Stack in which you can get minimum element in O(1) time. more: https://practice.geeksforgeeks.org/problems/get-minimum-element-from-stack/1 """ class Stack: """ Implement ...
from rest_framework.views import APIView from rest_framework.response import Response from cloudengine.core.models import CloudApp # View for creating new apps class AppView(APIView): def post(self, request, name): app = CloudApp(name=name) app.save() return Response({"id": app.key}) cl...
x=10 while x<=1: if x%5==0: print(x) continue x-=1 final copy Thank you :)
#!python3 """ This script updates the alexa rankings and sort the csv file. Usage: python3 update.py """ import csv import sys import os import itertools import math import alexa from download_favicons import download_favicons sites_path = os.path.join(os.path.dirname(__file__), "..", "_data", "sites.csv") upd...
import unittest, prob13 class Test_testprob13(unittest.TestCase): def test_make_self_quotient(self): obj = prob13.Prob13() obj.convert_grey() obj.make_self_quotient(1) obj.save('sd_1.jpg') obj = prob13.Prob13() obj.convert_grey() obj.make_self_quotient(5) ...
#!/usr/bin/env python import dataset import csv from slugify import slugify from collections import OrderedDict from summarize import METRO_PARISHES, METRO_FIPS INPUT_FILES = ( ('decennial-2000-bg', 'data/decennial-2000-bg/DEC_00_SF1_P004_with_ann.csv'), ('acs-2013-bg', 'data/acs-2013-bg/ACS_13_5YR_B03002_wit...
__author__ = 'siva' from PIL import Image as PILImage import FileHandle import datetime import zbarlight import cv2 def QRReader(file_path = './out.png'): start = datetime.datetime.utcnow() with open(file_path, 'rb') as image_file: image = PILImage.open(image_file) image.load() codes = z...
from scipy.ndimage import interpolation import os import random import tensorflow as tf import numpy as np import nibabel as nib import copy import pprint import logging from random import shuffle import glob import gc try: import medpy.io medpy_found = True except ImportError: medpy_fou...
from django.contrib.auth.views import LoginView, LogoutView from django.contrib.auth.mixins import LoginRequiredMixin from cinema.permission import LoginSuperUserRequiredMixin from django.views.generic import ListView, CreateView, UpdateView from django.contrib import messages from django.shortcuts import redirect from...
class PublicKey: def __init__(self, pkey): self.key = self.get_keytext(pkey) def get_keytext(self, keytext): return self.split_file(keytext) @staticmethod def split_file(keytext): return keytext.replace('[', '').replace(']', '').replace('\t', '').replace(' ', '').replace('\n',...
# Importing necessary libraries import random import time import matplotlib.pyplot as plt import numpy as np import seaborn as sns from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import confusion_matrix # The following represents a class of RandomForrest implementation # from analysis.an...
# -*- coding: utf-8 -*- """ Created on Sat Jun 15 19:55:55 2019 @author: Yudy Andrea Fierro """ #EJERCICIO 8 mul_3 = [] mul_4 = [] '''Se verifica el residuo del número para saber si es multiplo de tres y si lo es almacenarlo en una lista, igualmente para cuatro''' for i in range(1,101): if ...
import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM import keras odd_nums = np.array([1,3,5,7,9,11,13]) series = np.array([1,3,5,7,9,11,13]) window_size = 2 X = [] y = series[window_size:] for index in range(len(series) - window_size -1): input = ...
import glob import shutil import re from typing import List, Union fileList_working = [] def get_files(spec = 0): #excluded_files = [] if spec == 0: fileList_0 = sorted(glob.glob('R:/groups/seeley_pathology/NP Reports/Finalized/*.doc*')) else: fileList_0 = spec fileList ...
import tensorflow_datasets as tfds import tensorflow as tf import time import numpy as np from model import Transformer from modules import create_look_ahead_mask, create_padding_mask examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, as_supervised=True) tra...
import numpy as np class Dataset(object): def __init__(self, dtype='uint8', is_row_iamge=False): '''数据集 Args: dtype: uint8 或 float32,uint8:每个像素值的范围是[0, 255];float32像素值范围是[0., 1.] is_row_image: 是否将3维图片展开成1维 ''' images = np.fromfile('./images/test_image.bin',...
# !/usr/bin/python3 from tkinter import * top = Tk() E1 = Entry(top, bd=5) E1.pack(side=RIGHT) L1 = Label(top, text="User Name") L1.pack(side=LEFT) top.mainloop()
import sys import MainWinHorLayout from PyQt5.QtWidgets import QApplication, QMainWindow if __name__ == '__main__': # 创建QApplication类的实例 app = QApplication(sys.argv) # 创建一个窗口 mainWindow = QMainWindow() ui = MainWinHorLayout.UI_MainWindow ui.setupUi(mainWindow) mainWindow.show() # 进入程序的主...
import subprocess def command(command): command = command.rstrip() try: stdout = subprocess.check_output( command, stderr=subprocess.STDOUT, shell=True ) except: stdout = f"Can't execute: {command}" return stdout
''' (C) Copyright 2020-2022 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent ''' from pydaos.raw import DaosApiError import avocado from data_mover_test_base import DataMoverTestBase class DmvrSerialSmall(DataMoverTestBase): # pylint: disable=too-many-ancestors """Object Data Mover valida...
import pandas as pd dict_data = { 'c0': [1, 2, 3], 'c1': [4, 5, 6], 'c2': [7, 8, 9], 'c3': [10, 11, 12], 'c4': [13, 14, 15] } #리셋 인덱스 # print("# 딕셔너리를 데이터프레임으로 변환. 인덱스를 [r0, r1, r2]로 지정") # df = pd.DataFrame(dict_data, index=['r0', 'r1', 'r2']) # print(df, end='\n\n') # # print("#행 인덱스를 정수형으로 초기화")...
#/usr/bin/env python ############################################################################### # Copyright one_formula.py script - 2020 Marc Rosanes Siscart # Copyright of the formula_of_one discovered - May 2014 Marc Rosanes Siscart # # This program is free software: you can redistribute it and/or modify # it ...
import time import hashlib class Transaction: def __init__(self, sender, receiver, amount, timestamp=None): self.sender = sender self.receiver = receiver self.amount = amount self.time = timestamp or time.time() def get(self) -> dict: return { 'sender': self...
import time books_avail=[{'name':'Mahabharata','author':'Maha author'}, {'name':'Ramayana','author':'Rama author'}, {'name':'Secret Seven','author':'Enid Blyton'}] class Library: def __init__(self,alistbook,alibname): self.listbook=alistbook self.libname=alibname...
# -*- coding: utf-8 -*- """ Created on Wed Apr 14 16:15:38 2021 @author: gtxnn """ string = "themartian" dictionary = ['the', 'martian', ] def max_match(sentence, dictionary): if not sentence: return "" for i in range(len(sentence), -1, -1): first_word = sentence[:i] re...
# EXT ADV import numpy as np from scipy.optimize import minimize import numdifftools as nd """X=[v1,v2,x11,x21,f11,f21,x12,x22,f12,f22,r11,r12,r21,r22,r01,r02]""" a1=[0.0,0.3,0.7] a2=[0.0,0.6,0.4] rgov=0.0 def U_1(X,sign=1.0): return sign*(((a1[0]+rgov)*X[0]**0.5+(a1[1]-rgov/2.0)*X[2]**0.5+(a1[2]-rgov/2.0)*X[3]**0...
my_set = set() my_set.add(1) my_set.add(2) print(my_set) mylist = [1,1,1,1,2,2,2,2,3,3,3,3] my_set= set(mylist) print(my_set) type(False)
def try_to_change_string_reference(the_string): print('got', the_string) the_string = 'In a kingdom by the sea' print('set to', the_string) outer_string = 'It was many and many a year ago' print('before, outer_string =', outer_string) try_to_change_string_reference(outer_string) print('after, outer_stri...
import sys if len(sys.argv) < 2: msg = '\n' msg += "Usage 1: %s $INPUT_ROOT_FILE(s)\n" % sys.argv[0] msg += '\n' sys.stderr.write(msg) sys.exit(1) from larlite import larlite as fmwk # Create ana_processor instance my_proc = fmwk.ana_processor() # Set input root file for x in xrange(len(sys.arg...
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('<int:board_id>',views.board_topics, name='board_topics'), path('<int:board_id>/new', views.new_topic, name='new_topic'), ]
""" Problem 461 - Hamming Distance Given two integers x and y, calculate the Hamming distance """ class Solution: def hammingDistance(self, x: int, y: int) -> int: new_int = x ^ y hd = 0 while new_int != 0: new_int = new_int & (new_int - 1) hd += 1 return...
from pymongo import MongoClient from tkinter import * import random from PIL import Image, ImageTk import base64 import io import time from bson.objectid import ObjectId import threading from DataBase import * client = MongoClient('mongodb+srv://admin:admin@cluster0.o6hxp.mongodb.net/retryWrites=true&w=majority') db...
from FPI_old import FPI import pandas as pd data = pd.read_csv("test/data/trainData.csv", sep=";") labels = pd.read_csv("test/data/trainDataLabels.csv", sep=";") fpi = FPI(data, 0.3) fpiFit = FPI.fit(fpi) fpiPredict = FPI.predict(data, fpiFit, 50) results = fpiPredict.join(labels) print(accuracy_score(results["Cla...
#!/usr/bin/python3 # -*- coding:utf-8 -*- import unittest import random import heapq from MinHeap import MinHeap class TestMinHeap(unittest.TestCase): def test_min1(self): heap1 = MinHeap() data = [5, 1, 2, 3, 4] for v in data: heap1.push(v) self.assertEqual(1, heap1.mi...
from flask import Flask, render_template import os app = Flask(__name__) @app.route('/') def index(): img_file = os.path.join(app.root_path, 'static/img/cat.jpg') mtime =int(os.stat(img_file).st_mtime) return render_template('05.index.htm', mtime = mtime) # mtime를 넣어주면 이미지경로가 바뀔때마다 리플레쉬됨 /html에도 동일적용 if _...
""" #serialize pickle.dump(vectorizer, open(path+"vectorizer.p","wb")) pickle.dump(data, open(path+"data.p","wb")) pickle.dump(experiences, open(path+"experience_index.p","wb")) pickle.dump(substance_index, open(path+"substance_index.p","wb")) pickle.dump(tag_index, open(path+"tag_index.p","wb")) pickle.dump(substance_...
class MyException(Exception): '''这是我是某某异常''' def __init__(self,num,atleast): super().__init__() self.num = num self.atleast = atleast
from organization.models import Organization def user_context(request): request.user.ownedorgs = Organization.objects.filter( administrator=request.user.id) return dict()
# #! # # 畳み込みニューラルネットワーク # # (https://www.tensorflow.org/tutorials/images/cnn) from tensorflow.keras import datasets, layers, models # gpu = tf.config.experimental.list_physical_devices('GPU')[0] # tf.config.experimental.set_memory_growth(gpu, True) # ## MNISTデータセットのダウンロードと準備 (train_images, train_labels), (test_ima...
import numpy as np import theano import theano.tensor as T import lasagne def make_network(settings): last_layer = lasagne.layers.InputLayer( shape=(None, settings['input_length'], settings['phi_length']), ) for num_units in settings['layers']: last_layer = lasagne.layers....
import machine import time from machine import Timer from machine import Pin # 0 - close # 1 - open # 2 - closing # 3 - opened # 4 - error PWM_CLOSE = 40 PWM_OPEN = 115 ADC_ALARM = 700 TIME_END = 500 class Valve: def __init__(self, p_close, p_open, p_button, p_control, p_out): self.pwm = None se...
# -*- coding: utf-8 -*- import os class CapsNetParam(object): """A Container for the hyperparamters of Efficient-CapsNet. Attributes: """ __slots__ = [ "input_width", "input_height", "input_channel", "conv1_filter", "conv1_kernel", "conv1_stride", ...
warned={} def warn_reset(): global warned warned={} def warn(msg): if msg not in warned: print("Warning:",msg) warned[msg]=1
""" This file contains code that was run once or a few times, mainly to get an intuitive sense of the scope of the problem or to create matrices that only need to be created once. """ import numpy as np OpeningMovesSaveFileName = "openingMoves.npz" """ How many possible hands are there of l...
""" @Time : 2021/8/6 下午12:37 @Author : lan @Mail : lanzy.nice@gmail.com @Desc : 将控制台输出到文本框内 """ import sys import time from PyQt5.QtCore import QObject, pyqtSignal, QEventLoop, QTimer from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QTextEdit from PyQt5.QtGui import QTextCursor class Stream(...
# -*- coding: utf-8 -*- ''' Salt module to manage unix mounts and the fstab file ''' # Import python libs import os import re import logging # Import salt libs import salt.utils from salt.modules import state_std from salt._compat import string_types from salt.utils import which as _which from salt.exceptions import ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from todo.models im...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def __init__(self): self.ans = None def reverseList(self, head: ListNode) -> ListNode: if head is None: return None self.reverseAnswer(head) re...
import matplotlib.pyplot as plt; plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt import datetime import os import sys #Time stamp function. Returns the time that the function was called at def tstamp(): return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") #Open the log file log = open(...
import pytest from pg8000.dbapi import convert_paramstyle # "(id %% 2) = 0", @pytest.mark.parametrize( "query,statement", [ [ 'SELECT ?, ?, "field_?" FROM t ' "WHERE a='say ''what?''' AND b=? AND c=E'?\\'test\\'?'", 'SELECT $1, $2, "field_?" FROM t WHERE ' ...
from django.shortcuts import render, get_object_or_404, redirect, render_to_response from django.template import RequestContext from myBlog.models import Post, Comment from myBlog.forms import CommentForm def view_post(request, slug): post = get_object_or_404(Post, slug = slug) if request.method == 'POST': commen...
import time from time import sleep import random import sys from config import * from camera_smoketest_config import * ############################################################ print '*******************************************************************' print 'Take pictures quickly' print '***********************...
import unittest from terratalk.bitbucket_server import BitbucketServer class TestMain(unittest.TestCase): def test_pr(self): base_url = 'https://foobar.com' username = 'user' password = 'pass' project_key = 'FOOBAR' repository_slug = 'barfoo' pull_request_id = 11 ...
#learning generators in python from itertools import * def main(): ''' f = nFibonacci(10) print(list(f)) print(list(firstn(fibonacci(), 10))) l = ['6','4','a'] print(list(permutations(l))) ''' for time in trange((10, 10, 10), (13, 50, 15), (0, 15, 12) ): print(time) def trange(start, end, inc): curr = li...
#!/usr/bin/env python # -*- coding: utf-8 -*- import __future__ import sys sys.stdin = open("./stdin.txt", 'r') def print_full_name(a, b): print("Hello {} {}! You just delved into python.".format(a,b)) print_full_name(raw_input(),raw_input())
#!/usr/bin/python # -*- coding: utf-8 -*- import util.py2exe_helper import time from objects_canvas.strategy import Strategy from objects_canvas.move_strategy import MoveAndSelectStrategy from commands.simulation_command import SimulationCommand import traceback import json from petri import petri import wx...
from __future__ import print_function # -*- coding:utf-8 -*- __author__ = "ganbin" import httplib2 import os import re from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage import Gmail import settings import logging # if retrive credentia...
def rm_mtpls(base, nums): for m in range(base*2, len(num), base): nums[m] = False num=[True]*2000000 #remove 0 and 1 num[0]=False num[1]=False listofprimes=[] for i in range(len(num)): if num[i]==True: rm_mtpls(i,num) listofprimes.extend([i]) ans=0 for i in listofprimes: ans+=i...
#coding:utf-8 ''' 背景:2018-01-24,电脑出现故障,启动蓝屏,导致无法开机启动,只好重置电脑,重置后chrome的书签全部没有了,感觉很可惜, 之前添加了许多很有用的网页全部都没有了 目的:在计算机后台运行,定时检查chorme书签是否有更新,并及时备份到非系统盘,以防再次发生意外 所用包:os 注意:代码文件不要删除,第二,备份文件地址之前写在与代码文件同级目录下,结果发现文件执行目录不是py文件存放目录,无法使用相对目录,当然也可以存放在相同目录下然后再查找一次也可以 ''' import os import sys import time import win3...
import os from flask import Flask, render_template, request, jsonify from flask_cors import CORS from helpers.detect import detect_image_class # Initializing flask application app = Flask(__name__) cors = CORS(app) @app.route('/') def home(): return render_template('form.html', title='Home') @app.route("/predi...
""" LeetCode: Valid Parentheses (#20) https://leetcode.com/problems/valid-parentheses/ Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: > Open brackets must be closed by the same type of brackets. > Open bracket...
# Generated by Django 3.1 on 2020-08-10 02:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='word', name='wordcount', fiel...
import base64 import json from flask import render_template, flash, redirect, session, url_for, request, g from flask_login import login_user, logout_user, current_user, login_required from app import app, db, lm, facebook from models import * from forms import * @lm.user_loader def load_user(id): return User.que...
tempC = float(input('Temperatura em graus Celsius: ')) tempF = 32 + tempC*9/5 print(f'Temperatura em graus Fahrenheit: {tempF}°F')
#! /usr/bin/env python # Revised by YungshanSu, in November """Action server example In this code, it demonstrates how to initialize action server, and defines execute callback function. """ import rospy import actionlib import action_example.msg class DoDishesAction (object): """Action server for doing dishes ...
#!/usr/bin/env python3 from rest_framework import serializers from ..models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'first_name', 'last_name'] def __str__(self): return self.username
# This file contains the utlity functions for our Chess game from piecesetup import * import copy import re # our board is an 8 x 8 2D list # TODO: 1.1 - Using list comprehension initialize our default board and all of # the possible directions for each piece except the pawn. # Label them in the followin...
from dajax.core import Dajax from django.utils import simplejson from dajaxice.decorators import dajaxice_register from django.template.loader import render_to_string from pamplesneak.models import GameWord, Player from pamplesneak.forms import MessageSender import random word_file = "/usr/share/dict/words" WORDS = op...
# XOR gate : 다층 퍼셉트론 # - 다층 퍼셉트론의 동작 설명 # 1. 0층의 두 뉴런이 입력 신호를 받아 1층의 뉴런으로 신호를 보낸다. # 2. 1층의 뉴런이 2층의 뉴런으로 신호를 보내고, 2층의 뉴런은 # 이 입력신호를 바탕으로 y를 출력한다. # 3. 단층 퍼셉트론으로는 표현하지 못한 것을 층을 하나 늘려 구현 # 할 수 있었다. # - 퍼셉트론은 층을 쌓아(깊게하여) 더 다양한 것을 표현할 수 있다. import numpy as np # AND gate def AND(x1, x2): x = np.a...
import numpy as np from scipy.optimize import linprog from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d, Axes3D import itertools import time from mayavi import mlab def test_optimization(): points = np.random.uniform(-1,1,(4,2)) norms = np.apply_along_axis(np.linalg.norm, 1, points) points...
#!/usr/bin/env python # _*_ coding:utf-8_*_ # author:jinxiu89@163.com # create by thomas on 18-4-1. import os from app.admin import admin from utils import change_filename from flask import jsonify, request, current_app, url_for from app.decorate import admin_login @admin.route("/upload", methods=["POST"]) @admin_log...
try: import service import uix import uiutil import mathUtil import blue import uthread import xtriui import form import triui import trinity import util import draw import sys import types import uicls import uiconst import time import stackless import functools import listentry...