text
stringlengths
38
1.54M
#!/bin/env python # -*- coding: utf-8 -*-. import os import asyncio import pyocr as pyocr from config import FOLDER_PATH, TEXT import docx import pytesseract from PIL import Image async def list_sorted_pic_folder(FOLDER_PATH) -> list[str]: list_sorted = [] for pic in os.listdir(FOLDER_PATH): list_so...
import requests import json import tkinter from tkinter import Menu import tkinter as tk import tkinter.ttk as ttk from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2Tk) from matplotlib.figure import Figure from tkinter.ttk import Combobox import datetime from matplotlib.ticker imp...
# Generated by Django 2.1.7 on 2019-03-22 10:40 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0006_auto_20190322_0922'), ] operations = [ migrations.AddField( ...
# Import relevant modules import pymc import numpy import pandas as pd class LogDModel(object): def __init__(self, df): """ Parameters ---------- df - pandas dataframe Returns ------- """ assert type(df) == pd.DataFrame self.logd = dict(...
from sqlalchemy import Sequence from sqlalchemy import Column, Integer, BigInteger, Date from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship, backref from Base import Base from SessionFactory import SessionFactory from Match import Match class Game(Base): __tablename__ = 'games' id = ...
import snap nodes = 10 G = snap.GenFull(snap.PNEANet,nodes) # define int, float and str attributes on nodes G.AddIntAttrN("NValInt", 0) G.AddFltAttrN("NValFlt", 0.0) G.AddStrAttrN("NValStr", "0") # define an int attribute on edges G.AddIntAttrE("EValInt", 0) # add attribute values, node ID for nodes, edge ID for ed...
# @author: Manish Bhattarai import glob import os import h5py import pandas as pd from scipy.io import loadmat from .utils import * class data_read(): r"""Class for reading data. Parameters ---------- args : class Class which comprises following attributes fpath : str ...
charA = 'A' stringA = str(charA) charStr = "Character " + charA print(stringA) print(charStr)
# Skall innehålla info om email-servern smtpservername = "smtp.gmail.com" smtpusername = "bunke309@gmail.com" myaddress = "bunke309@gmail.com" myname = "Hunke"
import torch import torch.nn as nn import torch.nn.functional as F from models import VGG class PerceptualLoss(nn.Module): """ PyTorch module for perceptual loss. Parameters --- model_type : str select from [`vgg11`, `vgg11bn`, `vgg13`, `vgg13bn`, `vgg16`, `vgg16bn`,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 12 21:56:24 2018 @author: raja """ import pandas as pd import re from wordcloud import WordCloud df = pd.read_csv('/home/raja/Desktop/test.txt', header=None, delimiter="\t") final=[] for one in df[0]: new=one.split(':') final.append(new...
#Prompt: To save James Bond's reputation as a gambler, you must implement a prediction of whether the Casino Royale is cheating on every observed roll. You are given a spreadsheet of dice rolls and their probabilities under two models: F, "fair dice" where all rolls have equal probability (1/6); and L, "loaded dice" wh...
# # api_microformat.py # # David Janes # 2008.12.28 # # Copyright 2008 David Janes # import os import os import sys import urllib import types import pprint import types import bm_extract import bm_uri import bm_api from bm_log import Log import hatom import hcalendar import hcard import hdocument class Micr...
from __future__ import annotations import datetime import json import logging.config import os from pathlib import Path from miranda.scripting import LOGGING_CONFIG from miranda.storage import report_file_size logging.config.dictConfig(LOGGING_CONFIG) __all__ = [ "era5_variables", "eccc_rdrs_variables", ...
import numpy as np import flask from flask import Flask, request import json from nanonet.features import events_to_features from nanonet.segment import segment from nanonet import decoding, nn from nanonet.util import kmers_to_sequence import tempfile import pkg_resources import subprocess import timeit import os ap...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from .. import _utilities import typing # Export this package's modules as members: from ._enums import * from .get_private_endpoint_connections_adt_ap...
#Do, or do not. There is no try. --Yoda ############### # CHAPTER 2: Py Ingredients: Numbers, Strings, and Variables ############## # booleans: whihc have the value True and False: # integeres: whole number such as 42 adn 10000000 # floats : numbers with decimal points such as 3.12 or sometimes exponents line 10.0e...
import sys import os sys.path.append(os.getcwd()) import torch from datasets.avmnist.get_data import get_dataloader from unimodals.common_models import LeNet,MLP,Constant from torch import nn from training_structures.cca_onestage import train, test from fusions.common_fusions import Concat from unimodals.common_models...
''' Filemaker Input: - Path to a markdown file with sections deliminated Output: - A directory of discrete markdown files. - A CSV with the path to each file and a summary of each section. Description: This script will break up a monolothinc markdown file into parts. v0.2 2021.2.15 ''' from csv import reader INFILE...
""" first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") print("Hello {} {}".format(first_name, last_name)) # The value type from Input is always a String operand_1 = int(input("Enter 1st operand: ")) operand_2 = int(input("Enter 2nd operand: ")) print("sum is " + str(operand_1 +...
# pylint: disable-all import unittest """ Description: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equa...
import os from constants import PATH_TO_WEIGHTS def get_model_versions(): previous_runs = os.listdir(PATH_TO_WEIGHTS) version_numbers = [int(r.split("_")[-1].split(".")[0]) for r in previous_runs if r[0] != "." and MODEL_ID in r] return version_numbers def load_recent_weights(mod...
# author: Arun Ponnusamy # object detection with yolo custom trained weights # usage: python3 yolo_custom_weights_inference.py <yolov3.weights> <yolov3.config> <labels.names> # import necessary packages import cvlib as cv from cvlib.object_detection import YOLO import cv2 import sys weights = sys.argv[1] config = s...
from google.appengine.ext import db from google.appengine.api import memcache import json import logging import random from imageM import * from userInfo import * import datetime import jinja2 import os import util jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) ...
# Copyright 2019 NEC Corporation # # 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 wri...
from discord.ext import commands import lib.dbman as db import random class Dice(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def r(self, ctx, pool: int = 1, diff: int = 6, wp: str = "0", *reason): """ Rolls and checks successes.\n\ Synt...
from typing import List from datetime import datetime from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from ninja import Schema, ModelSchema, Field, Router from ninja.pagination import paginate from .models import Post, Category, Tag router = Router() class PostOut(ModelSch...
#Russel Tagaca #udpServer.py import sys import time import socket import struct import random serverIp = "127.0.0.1" serverPort = 12000 dataLen = 10000000 responseCount = 0; serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #takes IPaddress and port # to socket serverSocket.bind((serverIp, serverPort)) ...
with open('file_name', 'r') as inf: s1 = inf.readline() # чтение первой строки в файле s2 = inf.readline() # Чтение второй строки в файле s = inf.readline().strip() # удаление служебных символов в троке #import os # os.path.join('.', 'dirname', 'filename') # указание полного пути к фай...
''' CTCI 1.8 - don't change values until finding all the cells with zeros - O(N*M), quadratic solution inevitably. ''' def findZero(mtrx): row = [] col = [] i = 0 for i in range(len(mtrx)): # len == # rows j = 0 for j in range(len(mtrx[i])): # len == # cols if mtrx[i][j] == 0: row.append(i) col.a...
from selenium import webdriver driver = webdriver.Chrome('Recursos\\chromedriver.exe') driver.maximize_window() driver.get('http://www.goodstartbooks.com/pruebas/index.html') elemento = driver.find_element_by_name('ultimo') if elemento is not None: print('El elemento fue encontrado') else: print('El elemento...
# SQLite 접속하기. import sqlite3 con = sqlite3.connect('c:/temp/userDB') # 데이터베이스 지정(또는 연결) cur = con.cursor() # 연결 통로 생성 (쿼리문을 날릴 통로) sql = "SELECT * FROM userTable" cur.execute(sql) print(' 사용자아이디 사용자이름 사용자나이') print(' --------------------------------') while True : row = cur.fetchone() if row == None : ...
from django.shortcuts import render,redirect,reverse from django.http import HttpResponse,JsonResponse from .models import User from .forms import LoginForm,RegisterForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required def regist_view(request)...
from random import seed from random import gauss from random import random from cv2 import cv2 as cv2 import math import jsonpickle import json import numpy import shutil import os count = 0; def sift(img): gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) gray = numpy.float32(gray) sift = cv2.xfeatures2d.SIFT...
def find_contact(file_name, find_str): '''Для поиска контакта по элементу данных переданных в виде строки. Обработка данных. Вызов функции для вывода на печать найденного контакта(ов)''' file_txt_r = open(file_name, 'r') # Открытие файла для чтения данных. contact_number = 0 # Начальное значен...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013-2015 Marcos Organizador de Negocios SRL http://marcos.do # Write by Eneldo Serrata (eneldo@marcos.do) # # This program is free software: you can redistribute it and/or modify # it un...
import unittest import sys from selenium import webdriver from utils import LogUtil from utils import common from utils.TestCaseInfo import TestCaseInfo from utils.TestReport import TestReport # sys.path.append("..") from page import page_lu as page class TestLu(unittest.TestCase): def setUp(self): self.driver ...
######## #Important parameters ######## # viewing_distance = 60.0 #units can be anything so long as they match those used in screen_width below # screen_width = 30.0 #units can be anything so long as they match those used in viewing_distance above # screen_res = (1366,768) #pixel resolution of the screen viewing_dist...
URL = "https://api.mailgun.net/v3/sandboxc2e75bed92b1485286fc02a3480847f8.mailgun.org/messages" API_KEY = "key-7a869a6056a3b8bbc14d06cc2b585392" FROM = "Mailgun Sandbox <postmaster@sandboxc2e75bed92b1485286fc02a3480847f8.mailgun.org>" ALERT_TIMEOUT = 10 COLLECTION = "alerts"
#!/bin/python3 import sys def __is_palindrome(s): return s == s[::-1] def theLoveLetterMystery(s): if __is_palindrome(s): return 0 last_index = len(s) - 1 count = 0 for i in range(0, len(s)): if last_index - i <= i: break if s[i] != s[last_index - i]: ...
class BinarySearchTree: def __init__(self, value): self.value = value self.left = None self.right = None def depth_first_for_each(self, cb): # invoke callback with the value of this node cb(self.value) # if the left has a valuse recursively invoke the depth first for each on left if se...
import datetime import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import async_call_later import logging _LOGGER = logging.getLogger(__name__) DOMAIN = 'actuator' ACTUATE_SCHEMA = vol.Schema({ vol.Required('sensor_id'): cv.string, vol.Optional('s...
import os import gym import numpy as np import logging import matplotlib.pyplot as plt from tqdm import tqdm import torch from torch.utils.tensorboard import SummaryWriter from noise import OUNoise from model import Actor,Critic,DDPG_AC from utils import get_args,dir_maker from replay import ReplayOneDeque from ddpg_ag...
from django.contrib import admin from .models import Tweet, Relationship, Like # Register your models here. class TweetAdmin(admin.ModelAdmin): list_display = ('id', 'user', 'text',) list_display_links = ('id',) admin.site.register(Tweet, TweetAdmin) class RelationshipAdmin(admin.ModelAdmin): list_display = ('id'...
""" Diffuse Self-Shading ==================== Modeling the reduction in diffuse irradiance caused by row-to-row diffuse shading. """ # %% # The term "self-shading" usually refers to adjacent rows blocking direct # irradiance and casting shadows on each other. However, the concept also # applies to diffuse irradiance ...
count = 0 for number in range(1, 10): if(number % 2 == 0): print(number) count += 1 print(f"The total number of even numbers are: {count}")
from IPython.display import clear_output board = ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] def printboard(): print board[0], board[1], board[2] print board[3], board[4], board[5] print board[6], board[7], board[8] marker = 'x' index = -1 while True: if board[0] == board[1] == board[2...
import pygame from pygame.locals import * import sys import random WINDOWWIDTH = 300 WINDOWHEIGHT = 400 PADDLEWIDTH = 60 PADDLEHEIGHT = 20 FRUITSIZE = 10 FPS = 60 PADDLECOLOR = (255, 0, 0) FRUITCOLOR = (0, 0, 255) class Paddle(pygame.sprite.Sprite): def __init__(self, window_width, window_height, width, height...
def find_duplicate(arr): i = 0 while i < len(arr): j = arr[i] - 1 if arr[i] != arr[j]: arr[i], arr[j] = arr[j], arr[i] else: i += 1 print (arr) for i in range(len(arr)): if arr[i] != i+1: return arr[i] return -1 def main(): print(find_duplicate([...
# encoding: utf-8 # module cmath # from /home/pyy2/.virtualenvs/pyy3.5/lib/python3.5/lib-dynload/cmath.cpython-35m-x86_64-linux-gnu.so # by generator 1.145 """ This module is always available. It provides access to mathematical functions for complex numbers. """ # no imports # Variables with simple values e = 2.718281...
""" Models and database functions """ from flask_sqlalchemy import SQLAlchemy import bcrypt db = SQLAlchemy() class User(db.Model): """ User information """ __tablename__ = "users" user_id = db.Column(db.Integer, autoincrement=True, primary_key=True) email = db.Column(db.String(30), unique=True, n...
from credential.telegram import key as telegramKey from credential.mongoDb import key as mongoDbKey from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher.filters import Text from pymongo import MongoClient import json import logging import datetime def bot(): client = MongoClient(mongoDbKey...
N, K = map(int, input().split()) q = list(range(1, N + 1)) ret = [] pos = 0 for _ in range(N): pos += K - 1 pos %= len(q) ret.append(str(q[pos])) del q[pos] print('<' + ', '.join(ret) + '>')
## # -*- coding: utf-8 -*- import os import cv2 import matplotlib.pyplot as plt import argparse parser = argparse.ArgumentParser(description='flip the images') parser.add_argument('--flip_dir', dest='flip_dir', required=True, help='directory to flip images') args = parser.parse_args() path_dir = args.flip_dir + '/re...
import numpy as np from .rk4 import rk4 def rka(x,t,tau,err,derivsRK,param): """Adaptive Runge-Kutta routine Inputs x Current value of the dependent variable t Independent variable (usually time) tau Step size (usually time step) err Desired fr...
""" Server to guess what ... serving ludos model. This service is running a zmq client/server interface to run the inference. To access it, just connect to the server using ``` socket = context.socket(zmq.REQ) socket.connect("tcp://IP_OF_THE_SERVER:PORT_OF_THE_SERVER") ``` The server expected request format and ser...
""" A Joule is the international unit of energy. A watt is the international unit of power. A watt is a measure of energy *flow*. That is a watt is a flow of energy (lets say out of the wall socket, into your lamp) of 1 Joule per second. One joule is approximately 1% of a peanut. This is a tiny amount. Honestly. A ...
import imutils import cv2 # print(cv2.__version__) # # load the input image and show its dimensions, keeping in mind that # # images are represented as a multi-dimensional NumPy array with # # shape no. rows (height) x no. columns (width) x no. channels (depth) image = cv2.imread("static/images/boca2000.jpg") (h, w, ...
#Exercício Python 44: Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: #– à vista dinheiro/cheque: 10% de desconto #– à vista no cartão: 5% de desconto #– em até 2x no cartão: preço formal #– 3x ou mais no cartão: 20% de juros print('='*15, '\...
import os import sys import pymysql pymysql.install_as_MySQLdb() sys.path.append(os.getcwd()) os.environ['DJANGO_SETTINGS_MODULE'] = "main.settings" ### new django versions from django.core.wsgi import get_wsgi_application wsgi_application = get_wsgi_application() def application(environ, start_response): ...
from django.urls import path from loginregist import views app_name = 'loginregist' urlpatterns = [ path('login', views.login, name='login'), path('loginlogic', views.loginlogic,name='loginlogic'), path('regist', views.regist, name='regist'), path('registlogic', views.registlogic, name='registlo'), ...
from typing import Dict, Any, Callable import logging import traceback import boto3 logger = logging.getLogger() sqs_client = boto3.client('sqs') # give a callback that return True on successful processing def process_messages( queue_url: str, message_callback: Callable[[Dict[str, Any]], bool]) -> N...
def sum_up_to_even(lista): soma = 0 for i in lista: soma = soma + i if i%2 == 0: return soma - i #Se não existir número par retorna -1 return -1 print(sum_up_to_even([1,3,8, 9, 10]))
from django.test import TestCase from numbers_converter.exceptions import TooBigNumberException from numbers_converter.services import ConverterService class ConverterServiceTest(TestCase): def test_converter_return_zero(self): converted_text = ConverterService.number_to_text(0) self.assertEqual...
# -*- coding: utf-8 -*- """ celery cli handlers logtool module. """ from pyrin.task_queues.celery.cli.decorators import celery_cli_handler from pyrin.task_queues.celery.cli.enumerations import CeleryCLIHandlersEnum from pyrin.task_queues.celery.cli.interface import CeleryCLIHandlerBase from pyrin.task_queues.celery.cl...
import numpy as np import cv2 import subprocess from VITA_PRINTER import VITA_PRINTER from camera_v4 import VITA_PRINTER_CONTROLLER import serial import pygame from pi2uno_v2 import ARDUINO from picamera import PiCamera from time import sleep from fractions import Fraction refpt = [] isClick = False def mainLoop(cont...
import unittest from zxopt.data_structures.circuit import Circuit, MeasurementComponent, GateComponent, PauliXGateType from zxopt.data_structures.circuit.register.classical_register import ClassicalRegister from zxopt.data_structures.circuit.register.quantum_register import QuantumRegister class CircuitTest(unittest...
import gym import numpy as np import matplotlib.pyplot as plt from time import sleep def get_action(observation,W1,W2,b1,b2): # convert the observation array into a matrix with 1 column and ninputs rows observation.resize(ninputs,1) Z1 = np.dot(W1, observation) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2,...
def check_memory_loop(memory, current_memory): if memory == current_memory: return True else: return False def memory_distribution(file_name): with open(file_name) as fp: line = [int(x) for x in fp.read().strip().split()] tmp = line #??????????????????????? zmienia sie ...
#Time Complexity : O(n), Space Complexity : O(1) #Solution : 움직이는 속도가 다른 두 노드를 두어 언젠가 동일해지면 loop가 존재하는 것. class Solution(object): def hasCycle(self, head): node_fast = head node_slow = head while node_fast: node_fast = node_fast.next if not node_fast: ...
# PyTorch imports import torch import torch.nn as nn import torch.optim as optim # Other libraries import numpy as np from collections import OrderedDict import math class heuristic: """ Heuristic model that just return the sigmoid of the difference in gold and experience combined, with scaling and bias....
def count_sheep( input_ ): if input_ == 0: return "INSOMNIA" digit = set() x = input_ while True: x_string = str(x) for c in x_string: digit.add(c) if len(digit) == 10: return x x += input_ if __name__ == '__main__': t = int(raw_input()) for i in xrange( 1, t+1 ): n = int(raw_input()) prin...
from django.test import TestCase from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase from authentication.models import Account class AccountTests(APITestCase): def test_create_account(self): """ Ensure we can create a new accoun...
from data_types import * import cv2 import numpy as np import math kNumLevelsInitSigma = 40 kSigmaLevel0 = 1.0 kNumFeatures = 2000 kFASTKeyPointSizeRescaleFactor = 4 # best features to keep def sat_num_features(keypoints, des=None, num_features=kNumFeatures): if len(keypoints) > num_features: ...
from itertools import permutations t = int( raw_input() ) for i in range( 1, t+1 ): inps = raw_input().split(" ") k = int(inps[0]) c = int(inps[1]) s = int(inps[2]) #print k #print c #print s if k == 1: print 'Case #{}: {}'.format(i, 1) continue print 'Case #{}:'.format(i), " ".join([ str(i) for i in range...
# Generated by Django 2.2.3 on 2019-11-15 21:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vocab_list', '0007_auto_20190404_2141'), ] operations = [ migrations.AddField( model_name='vocabularylistentry', nam...
from selenium.webdriver.common.by import By from testcase.common.allBasePageClass import AllBasePage from utils.config import get_appPackage class ZXFillAnswerPage1(AllBasePage): appPackage = get_appPackage() ''' 真题写作作答页 ''' start_to_answer_btn_id = (By.ID, "{}:id/fragment_error_find_question_star...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time: 00:14 2020/12/25 # @Author: Sijie Shen # @File: seq2seq_inference # @Project: Seq2seqModel # !/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time: 01:38 2020/8/11 # @Author: Sijie Shen # @File: seq2seq_train # @Project: Seq2seqModel import torch import torch.n...
import os from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BPPRC.settings") celery_app = Celery("BPPRC") celery_app.config_from_object("django.conf.settings", namespace="CELERY") # here is the beat schedule dictionary defined celery_app.conf.beat_schedu...
from __future__ import annotations from abc import ABC from typing import Any from .profile import EDCProfile, WindowReport from .smart_grid import EnergyDemand class ProcessingUnitReport: def __init__(self, edc_id: str, pu_id: str, pu_type_id: str, status: bool, service_id: str | None, n_session...
__author__ = 'amir' import glob import random import csv import os import math import sqlite3 import shutil import results import subprocess import wekaMethods.wekaAccuracy import utilsConf def optimize(inds_bef, mat, priors): inds=[] newPriors = [] newMat = [[] for t in mat] len_mat0_ = len(mat[0]) ...
import speech_recognition as sr # type: ignore class Listen: def listen_for_speech(self, text: str="Powiedz cość") -> str: r = sr.Recognizer() with sr.Microphone() as source: print(text) audio = r.listen(source) try: recoding = r.recognize_goo...
#!public /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2015 Sean Kirmani <sean@kirmani.io> # # Distributed under terms of the MIT license. """TODO(Sean Kirmani): DO NOT SUBMIT without one-line documentation for test TODO(Sean Kirmani): DO NOT SUBMIT without a detailed description of tes...
import threading class ZeroEvenOdd(object): odd_lock , even_lock, zero_lock = threading.Lock, threading.Lock, threading.Lock def __init__(self, n): self.odd_lock = threading.Lock() self.even_lock = threading.Lock() self.zero_lock = threading.Lock() self.odd_lock.acquire() ...
from botocore.exceptions import ClientError import boto3 import os import logging import json import time import uuid logger = logging.getLogger() logger.setLevel(logging.DEBUG) region = os.environ['AWS_DEFAULT_REGION'] sts_client = boto3.client('sts') def lambda_handler(event, context): logger.debug("Recei...
class Pound: def __init__(self,rare=False): self.rare=rare if self.rare: self.value=1.25 else: self.value=1.00 self.color="gold" self.diameter=22.5#mm self.num_edges=1 self.thickness=3.15#mm self.heads=True def rust(self): ...
import cv2 import numpy as np img = cv2.imread('SOfaOutput_img.png') LegInImg = cv2.imread('sofawithleg.jpg') LegInImgRight = cv2.flip(LegInImg, 1) list = [LegInImgRight,LegInImg] Repleg = cv2.imread('leg.jpg') for i in list: res = cv2.matchTemplate(img, i, cv2.TM_CCOEFF_NORMED) loc = np.where (res >= 0...
class Settings(): def __init__(self): self.screen_width = 900 self.screen_height = 900 self.bg_color = (243, 222, 187) self.initial_background = "image/kulami.jpg" self.hole_size = 50 self.tile_edge_color = (150, 127, 103) self.font_color = (154, 202, ...
################################################## # cpdb_services_types.py # generated by ZSI.generate.wsdl2python ################################################## import ZSI import ZSI.TCcompound from ZSI.schema import LocalElementDeclaration, ElementDeclaration, TypeDefinition, GTD, GED ######################...
from ereuse_devicehub.resources.device.models import Device from teal.resource import View class DeviceView(View): def one(self, id: int): """Gets one device.""" device = Device.query.filter_by(id=id).one() return self.schema.jsonify(device) def find(self, args: dict): """Gets...
from flask import Flask, render_template, request, redirect from flask_sqlalchemy import SQLAlchemy import pymysql from sqlalchemy import or_ pymysql.install_as_MySQLdb() #创建一个Flsak应用程序,用于实现前后端交互以及与数据库连接的功能 app = Flask(__name__) #制定连接的数据库 app.config['SQLALCHEMY_DATABASE_URI']="mysql://root:120913@localhost:3306/flask"...
import pytest from pytestqt.qt_compat import qt_api from src.dock import PangoDockWidget from PyQt5.QtWidgets import QFileSystemModel, QListView def test_basic_dock(app): assert app.label_widget.isVisible() == True assert app.label_widget.windowTitle() == "Labels" assert app.undo_widget.isVisible() == T...
import sys sys.setrecursionlimit(10**6) def dfs(v, seen, group): seen[v] = True groups[v] = group for nv in g[v]: if seen[nv]: continue dfs(nv, seen, group) n, m = map(int, input().split()) g = [[] for _ in range(n)] for _ in range(m): a, b = map(int, input().split()) a -= 1 b ...
import re class GIZAReader(object): def __init__(self, filename): self.aligned_lines = list() with open(filename, 'r') as giza_file: while True: line_info = giza_file.readline() if not line_info: break line_plain = giz...
#coding=utf-8 import itertools import math import os import random import sys import numpy as np import cv2 import codecs from img_utils import * from jittering_methods import * from parse_args import parse_args args = parse_args() fake_resource_dir = sys.path[0] + "/fake_resource/" output_dir = a...
import scrapy from scrapy import Selector import re from lxml import etree from bs4 import BeautifulSoup as BS from ljbj.items import LjbjItem class ljbj(scrapy.Spider): name = 'ljbj' def __init__(self): self.allow_domains = ['lianjia.com'] self.start_urls = ['https://bj.lianjia.com/chengjiao...
import argparse import random import parsl from parsl.app.app import App from parsl.tests.configs.local_threads import config @App('python') def map_one(x, dur): import time time.sleep(dur) return x * 2 @App('python') def map_two(x, dur): import time time.sleep(dur) return x * 5 @App('pyt...
""" Nipype-pipeline: anatomical preprocessing Anatomical data preprocessing steps: 1. Transform slices (from oblique to axial orientation and) to FSL std orientation 2. Skull strip (Can be done with BET before entering the pipeline. In that case, leave out.) 3. Tissue segmentation 4. Register to MNI152 standard tem...
import os import logging import collections from logging import handlers from .contracts import FutureBlockCall class cached_property(object): """ Decorator that converts a method with a single self argument into a property cached on the instance. Optional ``name`` argument allows you to make cached ...
""" Usage: ProcessingFilteredData.py <year> (--SP500 | --SP1500 | --all) """ import pandas as pd from glob import glob from docopt import docopt import json if __name__ == "__main__": opt = docopt(__doc__) print(opt) year = opt["<year>"] # Dictionary of dictionary to save occurrance o...