text
stringlengths
8
6.05M
import argparse import os from tensorflow.contrib.learn.python.learn.utils import ( saved_model_export_utils) from tensorflow.contrib.training.python.training import hparam # --------------------------------------------------- # Library used for loading a file from Google Storage # --------------------------------...
from lib.list import List def partition_list(items, node): lower = List() upper = List() current = items.head while current: if current.data < node.data: lower.add(current.data) elif current.data > node.data: upper.add(current.data) current = current.next lower.tail.next = node n...
from __future__ import absolute_import # encoding: UTF-8 import six from json import dumps from datetime import datetime from time import mktime from jinja2 import nodes from jinja2.ext import Extension from jinja2.filters import do_mark_safe from jinja2.utils import contextfunction from tml import full_version from tm...
from collections import namedtuple import numpy as np from ._base import Base from ._common import ifunc from ._cps import swegn96 from ._exception import DispersionError __all__ = [ "RayleighEllipticity", "Ellipticity", ] RayleighEllipticity = namedtuple( "RayleighEllipticity", ("period", "ellipticity...
"""Handles reports over scheduler data. """ from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import from __future__ import print_function import bz2 import datetime import fnmatch import io import itertools import logging import time import numpy as np import pa...
tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = ''' I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass ''' print tabby_cat print persian_cat print backslash_cat print fat_cat # while True: # for i in ["/","-", "|","\\","|"]: # print ...
from django.db import models from django.urls import reverse from tinymce.models import HTMLField from django.contrib.contenttypes.fields import GenericRelation from administrator.models import MenuItem class Category(models.Model): title = models.CharField(max_length=255, verbose_name='Название') description...
from string import ascii_lowercase from performance import (contains, contains_fast, ordered_list_max, ordered_list_max_fast, list_concat, list_concat_fast, list_inserts, list_inserts_fast, list_creation, list_cre...
# -*- coding: utf-8 -*- ''' Crea un usuario dentro de la base de datos. PYTHONPATH="../../../python" python3 createUser.py dni name lastname sin email ni nada adicional. ''' from model.registry import Registry from model.connection import connection from model.users import users import systems import logg...
#!/usr/bin/env python # _*_ coding: utf-8 _*_ # @Time : 2021/4/8 19:07 # @Author :'liuyu' # @Version:V 0.1 # @File : # @desc : def clean(keys): res = [] for key in keys.split('-'): ga = key.split('%') if len(ga) > 2: continue if len(ga) == 2: if (not ga[0].isdigit()) or (l...
from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from meeting import views from django.conf.urls import include urlpatterns = [ path('users/', views.UsersList.as_view()), path('users/<int:pk>/', views.UsersDetail.as_view()), path('meetings/', views.MeetingsList.as_...
#!/usr/bin/env python3 # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. from idlnode import * def render(idl_node, indent_str=' '): output = [] ...
def foursome(numbers): sum = 0 for i in range(len(numbers)): sum += numbers[i] return sum def main(): numbers = [5, 10, 15, 20, 25] print(foursome(numbers)) if __name__ == "__main__": main()
from Claket import db from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship class TabelaPlano(db.Model): __tablename__ = 'Plano' id = db.Column(db.INT(), primary_key=True, nullable=False) preco= db.Column(db.FLOAT(), nullable=False) nome= db.Column(db.VARCHAR(45), nullable=False)...
print("---Basic Lambda---") answer = (lambda x:x * x) print(answer(3)) # Here order doesn't matter as we can assign to variables while passing in any order math_operation = (lambda a, b, c, d: (a + b) / (c - d)) print(math_operation(4, 3, 2, 1)) print(math_operation(d=1, a=4, c=2, b=3)) print("\n---Map Lambda---") nu...
""" 测试mtcnn_freezed_model.pb是否可用 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from scipy import misc import tensorflow as tf import numpy as np import sys import os import detect_face import cv2 from tensorflow.python.framework.graph_util import con...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @author: hogelog ''' from setuptools import setup setup(name="kestrel-cli", version="0.0.6", description="kestrel command-line interface", license="MIT", author="hogelog", author_email="hogelog@hogel.org", url="http://github.com/hogelo...
from django import forms from .models import Rate from account.models import MyUser class PostRateForm(forms.ModelForm): class Meta: model = Rate fields = ('account', 'liner', 'pol', 'pod', 'buying20', 'sell...
from math import sqrt x1=float(input("x1= ")) x2=float(input("x2= ")) x3=x2-x1 if x3<=(-0.1): print(x3*(-1)) else: print(x3)
# coding: utf-8 # 1 """ Реализовать контекстный менеджер такой же как open, но с проверкой на наличие файла т.е. если файла нет то конструкция не должна падать с ошибкой with MyOpen('wrong_file_path') as fh: fh.readlines() """ import os class MyOpen(object): def __init__(self, file_name,...
# JTSK-350112 # deadoralive.py # Taiyr Begeyev # t.begeyev@jacobs-university.de import random class Card(object): """ A card object with a suit and rank.""" RANKS = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) SUITS = ('Spades', 'Diamonds', 'Hearts', 'Clubs') def __init__(self, rank, suit): ...
MIN_LENGTH = 4 print("Please enter a valid password, with a length no less than {}".format(MIN_LENGTH)) password = input("> ") while len(password) < MIN_LENGTH: print("Invalid password length") print("Please enter a valid password, with a length no less than {}".format(MIN_LENGTH)) password = input("> ")...
def unordered_search(givenList, value): for index in range(len(givenList)): if value == givenList[index]: return index return None def ordered_search(givenList, value): for index in range(len(givenList)): if value == givenList[index]: return index elif givenList[index] > term: return None return N...
""" 후위 표기식 https://www.acmicpc.net/problem/1918 첫째 줄에 중위 표기식이 주어진다. 단 이 수식의 피연산자는 알파벳 대문자로 이루어지며 수식에서 한 번씩만 등장한다. 그리고 -A+B와 같이 -가 가장 앞에 오거나 AB와 같이 *가 생략되는 등의 수식은 주어지지 않는다. 표기식은 알파벳 대문자와 +, -, *, /, (, )로만 이루어져 있으며, 길이는 100을 넘지 않는다. """ """ 풀이: 우선순위가 중요하다. ( ) < + - < * / 0 1 2 )가 나온경우 (이 나올...
# This program uses turtle graphics and nested loops to draw a snowflake. import turtle win = turtle.Screen() t = turtle.Turtle() # set pen size and color t.pensize(10) t.pencolor("purple") # Using nested loops, draw a snowflake for i in range(6): # Turn the other direction ...
# -*- coding: utf-8 -*- """ Administration forms used to edit news """ from app.forms import custom_validators, CustomGrid, CustomFieldSet, \ create_date_field from app.models import News from web import config import datetime # Patterns & formats used by the validators DT_FORMAT = "%d/%m/%Y" # Lam...
import os import traceback import subprocess import tempfile import dj_database_url from xml.etree import ElementTree import re import logging from xml.dom import minidom from django.views.generic import View from django.conf import settings from django.contrib.auth.decorators import login_required from django.utils.d...
from unittest.mock import patch from family_foto.app import add_user from tests.base_test_case import BaseTestCase class BaseLoginTestCase(BaseTestCase): """ Test Case that provides a logged in user mock. """ def setUp(self): super().setUp() self.patcher = patch('flask_login.utils._g...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 18 23:40:23 2020 @author: eugeniy """ from pylibdmtx.pylibdmtx import encode from PIL import Image from docx import Document from docx.shared import Mm def marks_download (data=''): marks = [['123123323133dsfsdds3213ssdcfsdvsd12312','Обувь мужс...
import pandas as pd data = pd.read_csv('psy_20151221.csv', encoding='cp1251', sep=';', index_col=False, na_values='?', decimal=',') nominal_data = '0:1,2' for nominal_line in nominal_data.split(';'): nom_column, nom_data = nominal_line.split(':') nom_id = int(nom_column) data.iloc[:, nom_id] = data.iloc[:,...
class Solution: def solve(self, s): tokens=s.split() string="" for word in tokens: if word != "and": string += str(word[0]) return string.upper() ob = Solution() print(ob.solve("Indian Space Research Organisation"))
import asyncio import redis import json import aiohttp from colorama import Back, Fore class ProxyChecker: test_url = "http://ya.ru" timeout_sec = 10 # read the list of proxy IPs in proxyList from the first Argument given r = redis.Redis() redis_key = 'proxy' proxy_list = [] async def is...
# # Copyright © 2021 Uncharted Software Inc. # # 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 l...
import wx import wx.lib.newevent import utility import os from appdirs import user_config_dir PrefsChangedEvent, EVT_PREFS_CHANGED = wx.lib.newevent.NewEvent() _config = None _defaults = { 'font' : wx.Font( 12, wx.TELETYPE, wx.NORMAL, wx.NORMAL ).GetNativeFontInfoDesc(), 'save_window_size' : True...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Notes(models.Model): user_id=models.ForeignKey(User,on_delete=models.CASCADE) title=models.CharField(max_length=255) notes_data=models.TextField() thumbnail=models.FileField(default="") created...
# -*- coding=utf-8 -*- # @Time:2020/10/12 10:42 上午 # Author :王文娜 # @File:useragents.py # @Software:PyCharm ua_list=['Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36' ,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Fi...
#!/usr/bin/python3 """ Base class """ import uuid import datetime as dt from . import storage class BaseModel(): """ Defines all common attributes/methods for other classes """ def __init__(self, *args, **kwargs): """ Creating attributes id - Generated a str converted Unique...
#!/usr/bin/env python import os import sys import time import sqlite3 import argparse from subprocess import PIPE from subprocess import Popen class Capture(): def __init__(self, iface): self.nodes_ita = {} exists = os.path.isfile('DB') self.db = sqlite3.connect('DB') self.ieee = ...
import sqlite3 ''' #============================================================================== Database Interactions ''' #============================================================================== class DatabaseInfo: def __init__(self): self.database = sqlite3....
import sys input = sys.stdin.readline word1 = sorted(list(input().strip())) word2 = sorted(list(input().strip())) meh = word1[:] for i in range(len(word2)): if word1[i] == word2[i]: #print(meh) del meh[meh.index(word1[i])] print(meh[0]) #print(word1) #if len(set(word1)) > len(set(word2)): #jerry = list(se...
#!/usr/bin/env python2 """ replacement for submatrix.awk """ import sys start = int(sys.argv[1]) end = int(sys.argv[2]) in_fn = sys.argv[3] for line in open(in_fn).readlines(): sl = line.split() col_one = int(sl[0]) if (col_one >= start) and (col_one <= end): col_one = col_one - start + 1 print col_one,...
""" LIBRARY_NAME -> str get_initial_conditions(reporting_unit: int) -> List[InitialConditionNonSpatialDistributionSerializer] create_spatial_initial_conditions """ import os import sys from importlib.util import spec_from_file_location, module_from_spec from landscapesim.importers import ProjectImporter, ScenarioIm...
import os from subprocess import call import sys import tkinter as tk def click_checkinn(): call(["python", "checkin_gui_and_program.py"]) def click_list(): call(["python", "listgui.py"]) def click_checkout(): call(["python", "checkoutgui.py"]) def click_getinfo(): call(["python","getinfoui.py"]) cl...
"""backend URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
# -*- encoding: utf-8 -*- from django import forms class SearchForm(forms.Form): query = forms.CharField(min_length=3, required=False)
#I pledge my honor that I have abided by the stevens honor system. #OmP1.py def main(): n = int(input("How many numbers would you like in the list?")) numlist = list(float(x) for x in input("Enter a list of numbers separated by spaces.").strip().split())[:n] print("The entries of the list are", numlist) ...
import random def twoLists(): set1 = random.sample(range(20), 10) print("Первый список: " + str(set1)) set2 = random.sample(range(20), 10) print("Второй список: " + str(set2)) result = set(set1).union(set(set2)) print("Общий список: " + str(result)) twoLists()
import os ACCESS_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token' AUTHORIZATION_URL = 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent' AUTHORIZATION_SCOPE = 'openid email profile' AUTH_REDIRECT_URI = "http://localhost:8080/api/auth/signin/google/callback" # os.environ.get("FN_A...
#!/usr/bin/env python # -*- coding: utf-8 -*- import http import math import os import json import time from enum import Enum from os.path import expanduser from electrum.util import Ticker, make_aiohttp_session import requests # from eth_accounts.account_utils import AccountUtils from eth_keyfile import keyfile from e...
from .train import Train from .infer import Infer from ._logging import Logging class Runner(): def __init__(self, param): self.exp_param = param["exp_param"] self.train_param = param["train_param"] self.log_param = param["log_param"] self.train_param.update(self.exp_param) ...
from Up import Person from getconn import getconn from video import video import logging from Up import up import re import time uplist=list(map(str,[39180492,382666849])) conn = getconn() # 爬取up基本信息 time1 = 0 for uid in uplist: per = Person(uid) basic = per.getbasic() print(time1,basic["name"] ) keys ...
n1 = 0 n2 = 1 i = 3 while i <= 20: n3 = n1 + n2 n1 = n2 n2 = n3 i += 1 print(n3) # 檔名: exercise0710.py # 作者: Kaiching Chang # 時間: July, 2014
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import os import time import fnmatch import datetime #get directory list of files #find only files that are with DY*EU #find only files that are with DY* #find only files that are with DY*CA """ Renames the filenames within the same directory to be Unix friendly (1) Changes spaces to hyphens (2) Mak...
class Beverage(object): """ Beverage Class, parent class to all other beverage classes. Attributes: name: beverage name. price: beverage price. time: time it takes to make beverage. """ def __init__(self, name, price, time): self._name = name self._price = pr...
def isLeapYear(year): if year%4==0 and (year%100!=0 or year%400==0): return True return False ''' In this kata you should simply determine, whether a given year is a leap year or not. In case you don't know the rules, here they are: years divisible by 4 are leap years but years divisible by 10...
############################### # # Name: PyDrive # Author: Jessie Ray # Purpose: Provide Google Drive # cross platform # ############################### def main(): print("test") main()
# Generated by Django 2.2.3 on 2020-09-12 08:38 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateM...
import numpy as np import pylab n = int(raw_input("Enter the number of nodes in the beam: ")) noelem = n - 1 K = np.zeros([n, n]) F = np.zeros([n, 1]) EI = float(raw_input("Enter the bending stiffness of the beam(Ncm^2): ")) L = float(raw_input("Enter the length of the beam(cm): ")) M = float(raw_input("Ent...
from django.apps import AppConfig class PerpostConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'perpost'
import os class PDMLConverter: def convertPCAP(self, pcap): self.pcap = pcap if pcap is None: print("Empty File") else: pdml = self.pcap.split('.') cmd = "tshark -T pdml -r " + str(self.pcap) + " > " + pdml[0] + ".pdml" os.system(cmd)
# -*- coding: utf-8 -*- class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e def __eq__(self, other): return self.start == other.start and self.end == other.end class Solution: def merge(self, intervals): intervals.sort(key=lambda interval: interval....
from django.shortcuts import render,get_list_or_404,get_object_or_404 from django.contrib.auth import get_user_model from notification.models import Notification from django.utils import timezone from rest_framework import generics,status,viewsets from rest_framework.views import APIView from rest_framework.response im...
from rlpy.Tools.run import run run("examples/gridworld/posterior_sampling.py","./Results/Tests/gridworld/PSRL",ids=range(5), parallelization ="joblib") run("examples/gridworld/lspi.py","./Results/Tests/gridworld/LSPI",ids=range(5), parallelization ="joblib") run("examples/gridworld/sarsa.py","./Results/Tests/gridwo...
from flask import Flask, request, url_for, render_template, flash, redirect from flask_wtf import FlaskForm, CSRFProtect from wtforms import StringField, TextField, SubmitField, IntegerField, RadioField from wtforms.validators import DataRequired, Length, NumberRange, ValidationError import os import pickle class I...
from yolact import Yolact from utils.augmentations import FastBaseTransform from layers.output_utils import postprocess import pycocotools from data import cfg, set_cfg import numpy as np import torch import torch.backends.cudnn as cudnn import time import json import os import cv2 class YolactInter...
def is_isogram(string): return is_isogram_help(string.lower()) def is_isogram_help(string): if len(string) <= 1: return True elif not (string[0].isalpha()): return is_isogram_help(string[1:]) else: print(string[0], string[1:]) return (not (string[0] in string[1:]...
from __future__ import absolute_import from collections import deque class Instruction(object): def __call__(self, vm, match): pass class Fetch(Instruction): def __init__(self, pos): self._pos = pos def __call__(self, vm, match): vm.push(match.group(self._pos)) ...
even_numbers = [2, 4, 6, 8, 10] heros = ['Ironman','Thor','Hulk','Spiderman'] info = ['Batman', 4500, 6375.60] numbers = list(range(5)) numlist = [4] * 5 dlist = [1, 2, 3] * 3 print(even_numbers) print(heros) print(info) print(numbers) print(numlist) print(dlist)
import math import os import random import re import sys def solve(string): letters = list(string) result = "" for index in range(len(letters)): if index == 0: letters[index] = letters[index].capitalize() if letters[index] == " ": letters[index+1]=letters[index+1].ca...
name = 'mini' age = 17 # not a lie height = 64 # inches weight = 120 # lbs eyes = 'Black' teeth = 'White' hair = 'Black' print "Let's talk about %r." % name print "She's %r inches tall." % height print "She's %f pounds heavy." % weight print "Actually that's heavy." print "S...
""" Filreader enriching files with synonyms out of wordnet """ import sys from os import listdir, rename, makedirs, remove from os.path import join, isfile, dirname, exists import shutil from pydub import AudioSegment import subprocess __author__ = "kaufmann-a@hotmail.ch" temp_path = "./temp" def copy_files(sourc...
""" Sorting people into different files according to the clustering Author : Diviyan Kalainathan Date : 28/06/2016 """ from lib_lopez_paz import experiment_challenge as lp from multiprocessing import Process import os,sys inputdata = 'obj8' lopez_paz = True max_proc=int(sys.argv[1]) # Creating parameters cluster_n = 1...
def message(dct): name = dct['name'] role = dct['role'] movie = dct['movie'] print(f'In {movie}, {name} is a {role}') message( { "name": "Han Solo", "role": "smuggler", "movie": "Star Wars" } )
"""Routine to plot the neutrino power spectrum, as output by this code.""" import math import numpy as np import scipy.interpolate def load_genpk(path,box): """Load a GenPk format power spectum, plotting the DM and the neutrinos (if present) Does not plot baryons.""" #Load DM P(k) matpow=np.loadtxt(pa...
""" Assignment 2: Trees for Treemap === CSC148 Fall 2016 === ################################## Department of Computer Science, University of Toronto === Module Description === This module contains the basic tree interface required by the treemap visualiser. You will both add to the abstra...
from .tum_validation_data_module import TumValidationDataModule from .tum_validation_dataset import TumValidationDataset from ..concat_dataset import ConcatDataset class TumValidationDataModuleFactory(object): def __init__(self, dataset_folders): if type(dataset_folders) is not list: dataset_f...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Build a trial loop Step 2 Use this template to turn Step 1 into a loop @author: katherineduncan """ #%% #In the task, there are 8 trials. To begin a trial, press the space bar. After a #short delay, a face will be shown. After another brief delay, a second face will #b...
from abc import ABC, abstractmethod class AcquisitionError(Exception): pass class Acquisition(ABC): """Acquisition abstract class """ @abstractmethod def get_data(self): return iter() @abstractmethod def terminate(self): pass acquisition_strategies = {} def register...
# Author:ambiguoustexture # Date: 2020-02-24 from chunk_analysis import chunk_analysis file_parsed = './neko.txt.cabocha' file_result = './verbs_case_result.txt' with open(file_parsed, 'r') as text_parsed, open(file_result, 'w') as text_result: sentences = chunk_analysis(text_parsed) for sentence in sen...
#!/usr/local/bin/python3.8 ''' In case you want to use a variable you defined outside of a function (global variable) you can do so using the 'global' keyword Limitation: > you cannot use a global variable in a function if the function parameter is the name of the global variable Min prod: you can create a new glo...
import pygame from view.game_view import GameView from model.game_model import GameModel from controller.player_input import player_input, player_input2 from controller.enemy_input import enemy_input from model.vehicle_handling.spawn_enemies import spawn_chance from global_variables import MOVEMENT_PATTERNS import time...
import os import random import torch import numpy as np from torch.utils.data import Dataset from .common import PairedDataset from .davis2017 import davis2017 def attrib_basic(_sample, class_id): """ Add basic attribute Args: _sample: data sample class_id: class label asscociated with the ...
import math # i started the financial calculater by printing out 3 statement # the 1st statement explains to the user what to do # the 2nd and 3rd 1 explains to the user what the inputs are namely bond and investement. print("Choose either 'investment' or 'bond' from menu below: \n") print("Investment ...
# -*- coding: utf-8 -*- """ Created on Mon Dec 9 13:47:18 2019 @author: monre """ #USED import os import open3d as o3d import numpy as np registered = 'C:/Users/monre/OneDrive - Imperial College London/ME4/FYP/DATA/OAI-ZIB/processed_data/04.registered_scaled_PCDs' corresponded = 'C:/Users/monre/OneDrive ...
# -*- coding: utf-8 -*- class Connection: def __init__(self,sock,addr): self.sock = sock self.addr = addr self.readsize = 4096 self.timeout = 5 def handle(self): for data in self.read(): print data print len(data) def read(self): w...
from .de import DE, AsyncDE
def degree_centrality(G, nodes): ... def betweenness_centrality(G, nodes): ... def closeness_centrality(G, nodes, normalized: bool = True): ...
from __future__ import unicode_literals from django.db import models class internal_key_data(models.Model): key=models.CharField(max_length=200,blank=True,null=True) value=models.CharField(max_length=200,blank=True,null=True) # Create your models here.
""" ********************************************************************* This file is part of: The Acorn Project https://wwww.twistedfields.com/research ********************************************************************* Copyright (c) 2019-2021 Taylor Alexande...
import re import os import math import typing import pathlib import logging from .logginglib import log_debug from .logginglib import get_logger # the regular expression that matches any valid format specification, each # group contains one specification item format_reg = re.compile(r"^((?:.(?=(?:<|>|\^)))?)([<>=^]?...
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_pymongo import PyMongo from flask_mongoengine import MongoEngine mongo = PyMongo() me = MongoEngine() db = SQLAlchemy() ma = Marshmallow() def create_app(): app = Flask(__name__) sec...
import pbPlots as pbPlots import supportLib as supportLib series = pbPlots.GetDefaultScatterPlotSeriesSettings() series.xs = [-2, -1, 0, 1, 2] series.ys = [2, -1, -2, -1, 2] series.linearInterpolation = True series.lineType = "dashed" series.lineThickness = 2 series.color = pbPlots.GetGray(0.3) settings = pbPlots.Get...
class Animal: def run(self): print('我是一个动物') class Dog(Animal): pass class Cat(Animal): pass dog = Dog() dog.run()
from app.DAOs.MasterDAO import MasterDAO from app.DAOs.AuditDAO import AuditDAO from psycopg2 import sql, errors from flask import jsonify import re def Find(string): """ Private Method to verify if string is a website link (URL) Uses :func:`~app.re.findall` :param string: string to check URL for ...
from flask import Flask, render_template, url_for, send_from_directory app = Flask(__name__) app.debug = True @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return 'User %s' % username @app.route('/post/<int:post_id>') def show_post(post_id): # show ...
# -*- coding: utf-8 -*- """Top-level package for juliet.""" __author__ = """Raphael Gyory""" __email__ = 'raphael@gyory.net' __version__ = '0.1.0'
import cv2 import numpy as np from PIL import Image import time def S_cut(img): flag1 = 0 flag2 = 0 x1_list = [] x2_list = [] print(img.shape)#(height_Y,weith_X) #print(img[...,31]) print(img[...,33].all())# == False print(img[...,34].any())# == True #print(img[...,...
import sys import time import os import random ### Terminal TIC TAC TOE ### # v 1.0 # single player # multiplayer soon # add game stats: avg time to move, total length, number of invalid moves # add help option # 0 = blank, 1 = 'O', 9 = 'X' def rand_start(): r = random.random() if r < 0.5: return 1 return 9 ...
"""initializing the sqlite database with all the tables Revision ID: 2df7283702ad Revises: Create Date: 2020-08-31 18:57:40.394646 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2df7283702ad' down_revision = None branch_labels = None depends_on = None def ...