text
stringlengths
8
6.05M
from Puzzle_8_node import * from time import time class Searcher(object): """Searcher that manuplate searching process.""" def __init__(self, start, goal): self.start = start self.goal = goal def print_path(self, state): path = [] while state: path...
from flask_restful import Resource, reqparse import pandas as pd from instances import config import json import requests class Predict(Resource): parser = reqparse.RequestParser() #Condicoes de entrada parser.add_argument('age', type=int, required=True, help="This field cannot be left...
#!/usr/bin/python # Adjust SED gratings. # # Copyright (C) 2010-2011 Huang Xin # # See LICENSE.TXT that came with this file. from __future__ import division import sys from StimControl.LightStim.Core import DefaultScreen from StimControl.LightStim.LightData import dictattr from StimControl.LightStim.FrameControl impor...
import api emulated = True LEDGrided = True LCDed = False keyboardHacked = True touch = False gameList = ('app','orthello','connect4','draughts','inkspill','pixelArt','simon','solitare','tetris','ticTacToe','missionmars','scamper','gridTest','flame') # 0 1 2 3 4 5 6...
import json import csv # Opening JSON file and loading the data # into the variable data with open('D:\Topic Tagging\sample.json') as json_file: data = json.load(json_file) data_file = open('D:\Topic Tagging\data_file', 'w') # create the csv writer object csv_writer = csv.writer(da...
import cv2 import numpy as np import matplotlib.pyplot as plt from edgedetector import EdgeDetector def main(): name = 'img/p1im1.png' image = cv2.imread(name) print(type(image)) detector = EdgeDetector() image = detector.apply_filter('avg', image) plt.imshow(image) plt.show() if __name_...
""" Node Module Contains Node class """ class Node: """ Node Class. A node consists of an id and neighbors """ _id: str def __init__(self, node_id): """ Constructor :param node_id: node id. Valid are all immutable data types. (Int, String, Tupel,...) ""...
#!/usr/bin/python # -*- coding: utf-8 -*- import csv import math from scipy.integrate import quad def ellipseArea(a, b, angle): area = 0 quarters = 0 while angle > math.pi / 2: area += a * b * math.pi / 4 angle -= math.pi / 2 quarters += 1 if quarters % 2 == 0: # starts at a vertical edge area += a * b *...
import os ctr=0 for filename in os.listdir('resizedall'): if filename.endswith(".JPEG"): ctr+=1 # for filename in os.listdir('400x400'): # if filename.endswith(".JPEG"): # if not os.path.exists('400x400/'+filename.split('.')[0]+str('.xml')): # os.remove('400x400/'+filename) # ...
from .throttling import ThrottlingMiddleware
rule quast: input: expand("assemblies/{assembler}/{id}/{sub}/{assembler}.ok", id=IDS, sub=sub, assembler=Assembler) # norgal = expand("assemblies/{assembler}/{id}/{sub}/{id}_{assembler}", sub=sub, id = IDS, assembler = Assembler[0]), ## norgal = rules.norgal.output, # MitoFlex = expa...
def handle_columns(mongo_data, columns): def _fill_short_columns(mongo_data): for col in short_columns: col_info = columns[col] default = col_info["default"] if default is not None: mongo_data[col] = default elif col_info["nullable"]: ...
# Copyright 2017 - The Android Open Source Project # # 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 ...
import sys import ttk import random import shelve from Tkinter import * import Tkinter import tkMessageBox import subprocess from shelvepass import * from mylibhash import * from function import fun root = Tk() global me root.configure(background='black') root.iconbitmap(default='icon.ico') root.geometry...
import uuid from dataclasses import asdict from decimal import Decimal from kaizen_blog_api.comment.entities import Comment from kaizen_blog_api.serializers import dict_factory def test_can_instantiate() -> None: # given comment = Comment(id=uuid.uuid4(), text="testing", username="user test", post_id=uuid.uu...
import numpy as np import tensorflow as tf from ..model.unet import simple_unet_3d from .pre_process import load_patch_for_test_one_subj from .utils.patches import reconstruct_from_patches import os import SimpleITK as sitk import time def prepare_data_per_case(case, config, valid=True, infer=False): #...
from utils import * from rhyme_metric import * class HierarchicalClustering: def __init__(self, dataset_name) -> None: self.dataset_name = dataset_name self.input_path = 'input/' + dataset_name self.output_path = 'output/' + dataset_name self.reports_path = self.output_path + '/re...
from Classifier import Classifier from Documents import Documents from Stemmer_Mutual_Information import Stemmer from Training import Training stemmer = Stemmer() generalPath = '20news-bydate-' trainPath = generalPath + 'train' testPath = generalPath + 'test' listOfCategories = ['alt.atheism', 'comp.graph...
class classA(): print("this is a class A")
''' 贪婪算法,是寻找最优解的一种近似方法。把大问题分解为小问题,小问题中每次都取最优。 作用:化繁为简,快速,近似最优 例子:背包问题,教室调度问题,集合覆盖问题,旅行商问题 ''' #集合覆盖问题:在未选择的省份里,每次都尽可能选覆盖最多的 stations = {} stations["kone"] = {"id", "nv", "ut"} stations["ktwo"] = {"wa", "id", "mt"} stations["kthree"] = {"or", "nv", "ca"} stations["kfour"] = {"nv", "ut"} stations["kfive"] = {"ca", "az...
import os from git.repo import Repo from git import Git import csv Threshold=0 Threshold2=0.0 commonList=[] def all_path(dirname): filter=[".py"] result1 = []#所有的文件 完整的路径 result2=[] #文件在项目中的路径 dirlen = len(dirname) zxy=0 for maindir, subdir, file_name_list in os.walk(dirname): ...
# -*- coding: utf-8 -*- ############################################################################## # # ############################################################################## { 'name' : 'Econube account correction', 'version' : '0.1', 'author' : 'Econube | Jose Pinto, Pablo Cabezas', 'categor...
import unittest from appium_advance.page_object.desired_caps import appium_desired from time import sleep class StartEnd(unittest.TestCase): def setUp(self): self.driver = appium_desired() def tearDown(self): sleep(5) self.driver.close_app()
#from package import config #from Src.EnvSetup import cnfgurl from Src.EnvSetup import cnfgurl class Myurl(object): def __init__(self, driver): self.driver = driver def access_url(self): self.driver.get(cnfgurl.URL[cnfgurl.DEFAULT_ENVIRONMENT]) def registor_url(self): self.driver...
from wtforms import StringField from wtforms.validators import DataRequired from flask_security import RegisterForm, LoginForm, ForgotPasswordForm from flask_security.utils import find_user, get_message, hash_password from flask_security.confirmable import requires_confirmation from flask import flash from werkzeug.loc...
import os from sqlalchemy import create_engine # engine = create_engine('sqlite:///pemilu.db') MYSQL_PASSWORD = os.environ['MYSQL_PASSWORD'] engine = create_engine(f'mysql+mysqldb://root:{MYSQL_PASSWORD}@localhost:3306/pemilu2019')
import Computer class Game: def __init__(self,players): self.players = players def selectHands(self): self.hands = [] for player in self.players: hand = player.getHand() self.hands.append((player,hand)) def getScores(self): battleStr = ['rr','r...
import sys import time import subprocess import os, signal from selenium.webdriver.firefox.options import Options from selenium import webdriver import platform import logging import inspect implicit_wait_time = 3 specific_wait_time = 15 # TODO: Que dandole sea capaz de sacar una "lista de elementos" hacia tabla me...
from django.contrib import admin # Register your models here. from django.contrib import admin from .models import Person, Leave admin.site.register(Person) admin.site.register(Leave)
# Copyright 2016 Red Hat, Inc. 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 applicable law o...
import sys import os import requests import re from collections import defaultdict from bs4 import BeautifulSoup # echo "PATH=\$PATH:~/.local/bin" >> ~/.bashrc # easy_install --user pip # pip install --user requests # or install pip with # wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py && python get-...
from setuptools import setup, find_packages with open("Long.md", "r") as fh: long_description = fh.read() required = [] with open("requirements.txt", "r") as freq: for line in freq.read().split(): required.append(line) setup( name="sonosco", version="0.1.0", author="Roboy", descriptio...
# s.count(char) returns the number of occurrences of char in string: college = "Wake Tech" num_e = college.count("e") print("The number of e's in college:", num_e) # checking every character in a string using methods isalpha, isdigit, # isupper, islower # card_num = input("Please enter your 16-digit card number: ") # w...
#!/usr/bin/env python # coding: utf-8 # ## Session 2 # # ## Assignment 1 Question # # ## Problem Statement # 1. Write a program which accepts a sequence of comma-separated numbers from console and # generate a list. # # 2. Create the below pattern using nested for loop in Python. # # * # * * # * * * # * * * * # * ...
""" LeetCode - Easy """ """ Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. Example: MovingAverage m = new MovingAverage(3); m.next(1) = 1 m.next(10) = (1 + 10) / 2 m.next(3) = (1 + 10 + 3) / 3 m.next(5) = (10 + 3 + 5) / 3 """ from collections import...
#_*_coding:utf-8_*_ # Author:Topaz import tornado.ioloop import tornado.web from tornado import gen from tornado.concurrent import Future from MyTornado import uimethods as mt from MyTornado import uimodules as md class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): return ...
from setuptools import setup setup( name='trainer', version='0.0.0', packages=['trainer'], include_package_data=True, install_requires=['tensorflow'], )
# https://www.hackerrank.com/contests/saggezza-coding-test/challenges/the-birthday-bar def birthday(s, d, m): ans = 0 for i in range(len(s)): rest_d = d rest_m = m j = i while j < len(s) and rest_d > 0 and rest_m > 0: rest_d -= s[j] rest_m -= 1 ...
# coding: utf-8 """ NiFi Rest API The Rest API provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ...
from data.COMMON import * #essentials imgHeader(0.001, ( 'COMMONIMG', ['png'] ), []) #the image handling system is still very much in the design process, #and is currently not used. (only verified) #functions written in here may not be implamented in UMC yet. def ImportImage(FT): #TODO: only r...
from flask import render_template, flash, redirect, session, url_for from app import app from .forms import PostForm, NameForm from .models import Post from flask.ext.bootstrap import Bootstrap from . import db bootstrap = Bootstrap(app) @app.route('/') @app.route('/index', methods=['GET', 'POST']) def index(): n...
# módulo destinado a las clases y funcionalidades de los enemigos. from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QLabel from PyQt5.QtCore import QThread, pyqtSignal from PyQt5.Qt import QTest from parameters import VEL_MOVIMIENTO, LAMBDA_HOSTIL, A_NO_HOSTIL, \ B_NO_HOSTIL, N, RANGO_VISION, VIDAS_ENEM...
# protection, remember to seal after you are done if 1: import os import shutil import glob src = '.' dest = os.path.join('html', 'resources') # ideally we want to clean the resources folder before copying new files over, but # because I am having trouble deleting it on pc https://...
from django.contrib import admin from .models import BookInfo, HeroInfo # Register your models here. class HeroInfoInline(admin.TabularInline): model = HeroInfo extra = 3 class BookInfoAdmin(admin.ModelAdmin): list_display = ['id', 'btitle', 'bpub_date'] list_filter = ['btitle'] search_fields = ...
"""Test the localization model. """ from sklearn.pipeline import make_pipeline import numpy as np import dask.array as da from pymks.fmks.bases.primitive import discretize, redundancy from pymks.fmks.localization import fit from pymks.fmks.bases.primitive import PrimitiveTransformer from pymks.fmks.localization import...
import random def part(nums,left,right): pivind=left piv=nums[pivind] while left<right: while left<len(nums)and piv>=nums[left]: left+=1 while nums[right]>piv: right-=1 if left < right: temp=nums[right] nums[right]=nums[left] ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import urllib.request import urllib.parse import http.cookiejar import json import random import math import html5lib import os from bs4 import BeautifulSoup import re import ConnectUtils school = {'1' : 'http://jwxt.gduf.edu.cn/jsxs...
import os import json from collections import defaultdict,Counter import re from nltk import word_tokenize from nltk.corpus import stopwords from nltk.corpus import wordnet as wn corpus = {} with open('corpus_data/preprocessed_corpus.json') as corpus: corpus = json.loads(corpus.read().encode('utf-8')) corpus_2 = ...
import sys data = [] for k in range(30): a = len(data) b = sys.getsizeof(data) print("length: {}, size in bytes: {}".format(a, b)) data.append(None)
from django.shortcuts import render from django.http.response import HttpResponse import os import time # Create your views here. from django.template import loader from Myapp_covert2musicscore.utils.music21tools import * def use_music21(music_str): pan = False print('准备预测') for each in music_str: ...
import cv2 import torch from tqdm import tqdm from population import Population folder = "image.jpg" pic_size = 64 drawing_pic_size = 512 population_size = 30 number_of_polygons = 50 pop_cut = 0.1 iterations = 4000 output_pic_name = "output_image.png" def pic_show(img, img_name=output_pic_name): ...
import argparse import os.path import torch import numpy as np from torchvision import datasets, transforms class Disjoint(object): def __init__(self, args): super(Disjoint, self).__init__() self.upperbound = args.upperbound self.n_tasks = args.n_tasks self.i = args.i se...
from app.api_functions.database import get_db from fastapi import APIRouter from typing import List from fastapi import status from fastapi.params import Depends from sqlalchemy.orm import Session from app.models import schemas from app.logic.oauth2 import get_current_user from app.logic import user router = APIRoute...
a={1:'he','nu':'hehe'} print(a[1],a['nu']) print(a.values()) print(a.keys()) a=['key1','key2','key3'] dic=dict.fromkeys(a,10) print(dic)
import numpy as np import matplotlib.pyplot as plt from matplotlib import style from statistics import mean import random # X = np.array([1,2,3,4,5,6],dtype='float64') # y = np.array([5,4,6,5,6,7],dtype='float64') def createDataset(samples,variance,step=2,correlation=False): val = 1 y = [] for _ in range(samples):...
''' Created on Apr 10, 2016 There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edit) away @author: chunq ''' def isOneAway(str1, str2): if len(str1)...
from selenium import webdriver browser = webdriver.Chrome() browser.get("http://www.yahoo.com") assert "Yahoo!" in browser.title browser.close() #coding=gbk from selenium import selenium def selenium_init(browser,url,para): sel = selenium('localhost', 4444, browser, url) sel.start() sel.open(para) ...
#inheritance class Employee: def __init__(self): self.__id=10 self._name="ABC" self.salary=100 class Student(Employee): def Display(self): #print(self.__id) unavailable to object print(self._name) print(self.salary) ob=Student() ob.Display() print(ob...
import requests import json r = {} start_index = 0 query = input("What would you like to search for? ") def niceprint(dct): print("\n") for book in dct: for k, v in book.items(): print("{: >10} {: >10}".format(k, v)) print("\n") def search(start_index, query=query): base_url = {...
from pprint import pprint import socket import packetcodec from binascii import hexlify UDP_IP = "0.0.0.0" UDP_PORT = 56700 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP, UDP_PORT)) while True: data, addr = sock.recvfrom(1024) packet = packetcodec.decode_pac...
from certificate_verification import RuleMaker from common import Certificate, SingletonMeta class CertificateVerifier(metaclass=SingletonMeta): @staticmethod def verify(cert: Certificate, rule_maker: RuleMaker) -> bool: # In short, it is to check whether each steel plate in the certificate has passed...
""" Groove Detection: These functions are for detecting grooves on a record. The order of the functions in this file is the order of expected use. Groove data is produced from image data and a known center point. """ import cv2 as cv import numpy as np import pandas as pd import operator import Da...
# -*- coding:UTF-8 -*- from rest_framework import serializers from . import models from wxpay.views import dwd class OrderCallbackSerializer(serializers.ModelSerializer): class Meta: model = models.OrderCallback fields = '__all__'
from startup_db_test_env.startup_env_arg_builder import StartupDBDevEnvConfigArgBuilder from startup_db_test_env.startup_env import StartupDBDevEnv class ExecStartupEnv: def __init__(self, config_arg_builder: StartupDBDevEnvConfigArgBuilder, logger_stdout=None, logger_stderr=None): self.__config_arg_buil...
class Card: #initialize the rank and suit for cards def __init__(self,rank,suit): """rank is an int in the range 1-13 indicating the rank Ace-King, and siut is a single character "d,""c,""h," or "s" indicating the suit (dimonds,clubs,herats,or spades).Create the corresponding card.""" #ret...
import os.path import math from os import path import numpy as np import scipy import scipy.optimize allNames =[ "lizard", "shiftHappens", "erato", "cubes", "sponza", "daviaRock", "rungholt", "breakfast", "sanMiguel", "amazonLumberyardInterior", "amazonLumberyardExterior", "amazonLumberyardCombinedExteri...
class YourGuesser(Guesser): def analyzeOne():
''' Created on Dec 20, 2016 @author: bogdan ''' import unittest from repo.repository import * class TestRepo(unittest.TestCase): def setUp(self): self.__driversRepo=DriverRepository() self.__ordersRepo=OrderRepository() def test_addDriver(self): self.__driversRepo.add("1","1") ...
""" 1.路由命名规范: 返回html页面的,全部以/html开头; 返回json的接口,工具类以test开头、爬虫类以spider开头、其他的以PEP8为准 """ from flask import Flask, render_template, redirect, url_for from config import DevConfig from flask_cors import CORS import configparser import pymongo import redis from selenium import webdriver from lxml import etree ...
class Valores: def __init__(self): self.__id= 0 self.__valor_trans_id=0 self.__valor=0 @property def id (self): return self.__id @id.setter def id(self,id): self.__id = id @property def valores_trans_id(self): return self.__valor_trans_id...
# Copyright (c) 2012 Stuart Pernsteiner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions a...
class UrlTable: def __init__(self, urls): self.todo_list = [] self.all_url = {} for url in urls: self.all_url[url] = 0
#dependencies to create flask app and machine learning model From flask import flask, render_template, request App = Flask(__name__) #if we create our own model can use pickle. Model_TSLA = pickle.load(open(‘test_model.pkl’,’rb’)) #create route for home route @app.route("/") def home(): return render_templat...
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
import pymysql class Mysql(object): def __init__(self): """连接数据库,获取conn""" self.mysql_host = "127.0.0.1" # 数据库ip self.mysql_db = "tw" # 数据库名称,要提前在mysql中创建好数据库 self.mysql_user = "root" # 数据库登录账号 self.mysql_password = "123456" # 数据库登录密码 self.mysql_port = 3306 # 数...
from django import template register = template.Library() @register.filter def index(my_list: list, i: int): return my_list[int(i)]
#****************************************************************************** # #"Distribution A: Approved for public release; distribution unlimited. OPSEC #4046" # #PROJECT: DDR # # PACKAGE : # ORIGINAL AUTHOR : # MODIFIED DATE : # MODIFIED BY : # REVISION : # # Copyright (c) 2020 DCS Corporati...
from django.urls import path from . import views urlpatterns = [ path('create/', views.create_sensor, name='create_sensor'), path('get/', views.get_sensor, name='get_sensor'), ]
#Oppage 1 side 95. Grunneleggende programmering. #Denne delen tar imot informasjon som navn, adresse, telefornummer og utdanning. name = input('Skriv inn navn: ') #Man skriver inn sitt navn address = input('Skirv inn adressen din: ') #Skriver inn adressen tlf = int(input('Skriv inn ditt telefonnummer: ')) #Telefo...
#!/usr/bin/python d=set() def f(x, W): y = x % W if y == 0 or x % y != 0: return None A = (x-y)/W assert x / y == W * A / y + 1 return x / y def g(x, W): origin = x while True: z = f(x, W) if z == x or z is None: if z is not None: global...
#!/usr/bin/env python import sys, matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from networking.lib import * #@UnusedWildImport from location.lib import * #@UnusedWildImport from location.maps import SUNYNorthSpine as Map n = Networking.load() print >>sys.stderr, "Starting." long_device_sessions...
import wrcX.core import wrcX.core.data from statsmodels.graphics import utils import seaborn as sns import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.dates as mdates from pandas import melt,merge, DataFrame, notnull from numpy import arange from wrcX.core.filters import groupCl...
from __future__ import print_function import sys import os def main(): if 'CXX' not in os.environ: cxx = 'DEFAULT_CXX' else: cxx = os.environ['CXX'] print(cxx, sys.executable, sys.version) if __name__ == '__main__': main()
tabuada = 1 numero = 1 while tabuada <= 9: print("%d x %d = %d" % (tabuada, numero, tabuada * numero)) numero = numero + 1 if numero == 11: numero = 1 tabuada = tabuada + 1
#!/usr/bin/env python ''' Program : lineup.py Version : 1.0 Author : b.k.gjelsten@fys.uio.no Description : ''' import sys,os import bkgjelstenArgReader # ##################################################### GLOBAL METHODS # ##################################################### GLOBAL METHODS # ###################...
from __future__ import print_function from sympy import * # numerical value of PI PI = pi.n() def gen_basis_set( h, N ): # generate grid points A = -(N-1)/2.0*h xgrid = [] for i in range(N): xgrid.append(A + i*h) # x = symbols('x') bfs = [] for i in range(N): bfs.append...
from sys import argv scripts, source, dest = argv i = 0 source = float(source) dest = float(dest) print ("source is:", source) print ("dest is:", dest) while source <= dest: source = source * (1 + 0.1) i = i + 1 print ("需要", i, "次涨停")
fileName = input('Enter a filename: ') file = open(fileName, 'r') words = [] for line in file: for word in line.split(): words.append(word.upper()) dict = {} for word in words: number = dict.get(word, None) if number == None: dict[word] = 1 maximum = max(dict.values()) for key in dict: ...
import sys import os import datetime import inspect import h5py import random import numpy as np import matplotlib.pyplot as plt import littlefish.core.fish as fi import littlefish.core.simulation as si import littlefish.core.terrain as tr log_folder = r'C:\little_fish_simulation_logs' simulation_length = 2000 # 1000...
#!/usr/bin/env python # ------------------------------------------------------------------------------ # helper.py # Author: Alan Ding # ------------------------------------------------------------------------------ from database import db, Message from sqlalchemy import func def add_message(time, sender, message): ...
from config.wsgi import * from core.brain.models import * positions = ['Agente', 'Supervisor', 'Formador', 'ACCM'] Lobs = ['BGI ARGENTINA', 'BGI CHILE', 'BGI COLOMBIA', ] for i in range(0, len(positions)): try: position = Position() position.position_name = positions[i] position.save() ...
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path("", views.index, name="homepage"), path("addfile/", views.add_file, name="yougotitfiles"), ]
# -*- coding: utf-8 -*- from openerp.osv import fields, osv from datetime import datetime import openerp.addons.decimal_precision as dp class account_move(osv.osv): _name = "account.move" _inherit = "account.move" def onchange_import(self,cr,uid,ids,context=None): act_obj = self.poo...
# -*- coding:utf-8 -*- from flask import Flask from flask_cors import CORS from datetime import datetime, timedelta app = Flask(__name__) app.config['SECRET_KEY'] = 'skeyasdasdasdas' app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=50) app.config['JWT_AUTH_URL_RULE'] = None app.config['JWT_AUTH_EMAIL_KEY'] = "ema...
class Solution: def isValid(self, characters): length = len(characters) if len(characters) % 2 == 1: return for i in range(length//2): characters = characters.replace('[]', '').replace('{}', '').replace('()', '') return len(characters) <= 0
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv('skychallenge_clean_data.csv') df = df.head(10000) # df = df.drop(columns = ['condition', 'fuel', 'transmission']) df = df.drop_duplicates() df # In[2]: from statsmodels.graph...
import torch from pytorch_pretrained_biggan import (BigGAN, one_hot_from_names, truncated_noise_sample, save_as_images, display_in_terminal, convert_to_images) import os from quart import Quart, send_file, request, make_response import os import pickle import numpy as np import P...
import os def save_picture(form_picture): f_name,f_ext=os.path.splitext(form_picture.filename) picture_fn = f_name + f_ext picture_path=os.path.join(app.root_path,'static/pictures',picture_fn) form_picture.save(picture_path) return picture_fn from flask import render_template,...
from src.main import db, ma #---------Models-------------------------- subs = db.Table('subs', db.Column('user_id', db.Integer, db.ForeignKey('users.user_id')), db.Column('channel_id', db.Integer, db.ForeignKey('channels.channel_id')) ) #------------User Model----------------- class User(db.Model): __tab...
import re regex = '[+-]?[0-9]+\.[0-9]+' def find(floatnum): if (re.search(regex ,floatnum)): print(True) else: print(False) if __name__ == '__main__': floatnum = "4" find(floatnum) floatnum = "5.000" find(floatnum) floatnum = "6.95" find(floatnum) floatnum = "0.6" ...