text
stringlengths
8
6.05M
import numpy as np from scipy import special # import matplotlib.pyplot as plt # 生成(3,3)形状的数值在[-0.5,0.5]之间的矩阵 array = np.random.rand(3,3) - 0.5 print(array) l = [[1,2],[3,4]] print("origin l is {0}".format(l)) ll = np.array(l, ndmin=2) print(ll) #[[1 2] # [3 4]] print(ll.T) class Network(object): def __init__(se...
from selenium.webdriver.support.ui import WebDriverWait from time import sleep import os import time from selenium.webdriver.common.by import By class Page: def __init__(self, driver): self.driver = driver def find_element(self, *loc): # 查找单个元素 try: WebDriverWait(self.driver...
#import sys #input = sys.stdin.readline def main(): N = int( input()) T = input() if N == 1: if T == "0": print(10**10) elif T == "1": print(2*10**10) else: print(0) return if N == 2: if T == "11" or T == "10": print...
""" Module designed to align SRT core statistics obtained from receiver and sender as well as tshark datasets if necessary. """ import pathlib import pandas as pd from tcpdump_processing.convert import convert_to_csv from tcpdump_processing.extract_packets import extract_srt_packets, extract_umsg_handshake_packets, e...
import sublime from ._compat.typing import Optional, List, TypeVar, Collection from .flags import RegionOption __all__ = ['RegionManager'] T = TypeVar('T') def _coalesce(*values: Optional[T]) -> T: return next(value for value in values if value is not None) class RegionManager: """A manager for regions...
#! /usr/bin/env python # Core imports # #Our test script which we call the appropriate utility from. ##This program forms the main testing stream for calling test functions from the utilities class. import time import ev3dev.ev3 as ev3 import os import thread # Local Imports import utilities as U import openLoopContro...
from stdmodandoption import * import plot_setup as PS import collections from gasdenThis_out import gasdenThis_out import matplotlib.lines as mlines keystore=['plot1','plot2','plot3','plot4','plot5','plot6'] def gasdenThistestinput(subdict): startno=subdict['startno'] Nsnap=subdict['Nsnap'] snapsep=subdict...
# Generated by Django 3.1.4 on 2021-01-12 05:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('order', '0005_auto_20210112_0511'), ] operations = [ migrations.AlterField( model_name='order',...
''' Created on 28Oct.,2016 @author: Alex Ip ''' import os import dateutil.parser from datetime import datetime from dateutil import tz import pytz import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Initial logging level for this module def read_iso_datetime_strin...
import speech_recognition as sr from os import path # obtain path to "english.wav" in the same folder as this script AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "english.wav") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(...
#!/usr/bin/env python from sys import argv import numpy as np from skimage.filters import gaussian from skimage.segmentation import active_contour from skimage import io # parse input # argv[1] - images path like "./images/" # argv[2] - input image name (before processed) # argv[3} - output image name (after process...
#!/usr/bin/python #Example of P control from dxl_util import * from _config import * import time import math import numpy as np #Setup the device dxl= TDynamixel1(DXL_TYPE,dev=DEV) dxl.Id= DXL_ID dxl.Baudrate= BAUDRATE dxl.Setup() dxl.EnableTorque() #Move to initial position p_start= 2100 dxl.MoveTo(p_start) time.sl...
from django.shortcuts import render from account.models import Account def home_screen_view(request): context = {} context['accounts'] = Account.objects.all() return render(request,'personal/home.html',context)#render(request,reference,context//data or variables)"""
from os import path from codecs import encode, decode from pymongo import MongoClient conn = MongoClient() db = conn.foo with open("groceries.csv") as f: for line in f: text = [] for word in line.strip().split(','): word = decode(word.strip(),'latin2','ignore') text.append(word) d = {} ...
from django.db import transaction def disable_triggers(func, using=None): """ Disables all triggers before executing the function. Useful when performing bulk operations which don't require auditing to be performed. """ def _inner(*args, **kwargs): connection = transaction.get_connecti...
import os def main(): for filename in os.listdir('.'): if not filename.endswith('.txt'): continue with open(filename, 'r') as f_in, \ open(filename + '.processed', 'w') as f_out: items = {'group:' + s.strip().split(' ', 1)[0] for s in f_in} f_out...
#!/usr/bin/python3 def safe_print_integer_err(value): """ Print an integer """ try: print("{:d}".format(value)) return True except (TypeError, ValueError) as exc: print('Exception:', exc, file=__import__('sys').stderr) return False
from django.shortcuts import render from rest_framework import viewsets from .serializers import GovTableSerializer from .models import GovTable # Create your views here. class GovTableView(viewsets.ModelViewSet): serializer_class = GovTableSerializer queryset = GovTable.objects.all()
import random from gameData import data #print two random person initially followers store in variable dict_1 = random.choice(data) dict_1_follower_count = dict_1["follower_count"] is_game_over = False current_score = 0 while not is_game_over: dict_2 = random.choice(data) dict_2_follower_count = dict_2["follo...
class Solution: def toHex(self, num): """ :type num: int :rtype: str """ if num < 0: num += 2**32 remainders = [] while num//16 != 0: remainder = num%16 if remainder < 10: remainders.append(str(remainder)) ...
import hashlib import hmac import logging from datetime import datetime, timezone from operator import attrgetter from secrets import compare_digest from typing import Dict from pydantic import BaseModel, Protocol, ValidationError, validator from sqlalchemy import distinct, select from sqlalchemy.dialects.postgresql i...
try: from .__version__ import __version__ except ImportError: VERSION_STRING = '' DEVELOPMENT_VERSION = True else: VERSION_STRING = ' v{}'.format(__version__) DEVELOPMENT_VERSION = False from shutil import move, copytree, copy, rmtree, get_terminal_size from os import makedirs as make_directory, l...
from chapter3_case_study.Appartment import Appartment from chapter3_case_study.House import House from chapter3_case_study.Purchase import Rental, Purchase class HouseRental(Rental, House): def prompt_init(): init = House.prompt_init() init.update(Rental.prompt_init()) return init pro...
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Arbitrary precision 1-dimensional likelihood framework. Framework to estimate the parameters and the variance of the parameters of a given fitting_function one dimensional probability density function, by the method of the maximum likelihood. The fitting_function has two ...
import pandas as pd from sqlalchemy import create_engine education = pd.read_csv("education/API_SE.XPD.TOTL.GD.ZS_DS2_en_v2.csv", skiprows=4) education.drop(education.columns[[-1, 0, 2, 3]], axis=1, inplace=True) cashSurplusDeficit = pd.read_csv("cash surplus/deficit/API_GC.BAL.CASH.GD.ZS_DS2_en_v2.csv", skiprows=4) ...
import os, time, random # Constants alpha_coords = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'] # printataan ruudukon reunalle ja muutetaan input: a -> 0 jne # Variables misses = [] hits = [] ships = [] occupied = [] gameover = False debug = False # Classes class Ship: def __i...
import argparse from logger import L class Parser(argparse.ArgumentParser): def exit(self, status=0, message=None): L.debug("exit") pass
#import sys #input = sys.stdin.readline Q = 10**9+7 def main(): N = int( input()) T = list( map( int, input().split())) A = list( map( int, input().split())) ANS = [0]*N now = 0 AC = [False]*N for i in range(N): if now < T[i]: ANS[i] = T[i] AC[i] = True ...
#minimum cut palindrome def splitString(s): if s == '' or isPalindrome(s): print(s) return 0 cuts = float('inf') #cuts = min(1 + splitString(s[0 : 1]) + splitString(s[1: ]) , cuts) for i in range(len(s)): #pass #cuts = 1 + ...
#check the input while True: credit_card = input("Number: ") if (str.isdecimal(credit_card)): break digits = "" # Multiply every other digit by 2, starting with the number’s second-to-last digit for i in range(len(credit_card) -2, -1, -2): digits += str(int(credit_card[i]) * 2) #add products’ dig...
import os import time import torch import torch.nn as nn import torch.nn.functional as F from pykeops.torch import LazyTensor use_cuda = torch.cuda.is_available() dtype = 'float32' if use_cuda else 'float64' torchtype = {'float32': torch.float32, 'float64': torch.float64} def save_model(decoder, name, date, model_pat...
# ---------------------------------------------------------------------------- # Copyright 2014 Nervana Systems 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.o...
import cv2 as cv cap = cv.VideoCapture(0) if cap.isOpened() == False: print("카메라를 열 수 없습니다.") exit(1) while(True): ret, img_frame = cap.read() if ret == False: print("캡쳐 실패") break # hsv 색공간으로 변환 img_hsv = cv.cvtColor(img_frame, cv.COLOR_BGR2HSV) # 파란색 기준값을 120으로 상한, 하한값 ...
#String encoding decoding def encode(arr , sep): n = len(arr) res = '' 'hello world' for s in arr: res += s + sep res = res[0 : len(res) - 1] return res def decode(s , sep , res): print(s) if sep not in s: res....
import re class ResolvedIssues(object): def __init__(self): self.__alg_isc_name = "ISC -> Resolved Issues" self.__alg_csv_name = "CSV -> Resolved Issues" def list(self): return [self.__alg_isc_name, self.__alg_csv_name] def process(self, alg_name, input): i = self.list().i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 7 18:37:05 2021 @author: janeyalex """ import numpy as np from scipy import stats import plotly.graph_objs as go import plotly.express as px import pandas as pd import collections import urllib.request from string import punctuation def words_of...
""" Borrowed from HPLFlowNet Date: May 2020 @inproceedings{HPLFlowNet, title={HPLFlowNet: Hierarchical Permutohedral Lattice FlowNet for Scene Flow Estimation on Large-scale Point Clouds}, author={Gu, Xiuye and Wang, Yijie and Wu, Chongruo and Lee, Yong Jae and Wang, Panqu}, booktitle={Computer Vision and Patter...
def factorial(): f, n = 1, 1 while True: # First iteration: yield f # yield 1 to start with and then f, n = f * n, n+1 # f will now be 1, and n will be 2, ... for index, factorial_number in zip(range(51), factorial()): print('{i:3}!= {f:65}'.format(i=index, f=factori...
# -*- coding: utf-8 -*- import math class Model(): def __init__(self, corpus): self.corpus = corpus self.movie_num = len(self.corpus['movie_title']) class TermSelection(Model): def __init__(self, corpus, w2v_model): super().__init__(corpus) self.w2v_model = w2v_model self.word_info = self.corpus['word_inf...
#!/usr/bin/env python import json import string def compass(): from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC adblock = webdriver.FirefoxProfile() ...
#!/usr/bin/python import ldap import sys import uuid import hashlib import binascii # MySQL functions import MySQLdb # Function to generate the salt via MySQL def gen_mysql_salt(conn_host,conn_usr,conn_pwd,conn_db): try: # Open database connection db = MySQLdb.connect(conn_host,conn_usr,conn_pwd,conn...
#!/usr/bin/python from programs import trap from math import exp as e, sin, cos, sqrt, pi, log as ln print("Problem 1a -- m = 16") f = lambda x: e(x**2) print(trap(f, 16, 0, 1)) print("Problem 1a -- m = 32") print(trap(f, 32, 0, 1)) print("Problem 1b -- m = 16") f = lambda x: sin(x**2) print(trap(f, 16, 0, sqrt(pi)...
import torch from generateDictionary import loadStateDict model_file = '../../EdgePixel_Results/Experiments/ResultBlock/modelBlock_test.pth.tar' modelBlock_state = torch.load(model_file) modelBlock = loadStateDict(modelBlock_state)
# -*- coding: utf-8 -*- import pytest, time from os.path import join from airtest_selenium.proxy import WebChrome from selenium.webdriver.chrome.options import Options from utils.operation_portal import portal_attachment from utils.operation_path import get_picture_path from utils.operation_log import Loggings from u...
# SURF and SIFT is only supported in older version # pip install opencv-contrib-python==3.4.2.17 # pip install opencv-python==3.4.2.17 import numpy as np import glob,os,sys,time import cv2 as cv from scipy.spatial.transform import Rotation as R class SFM_Params: def __init__(self,img_dir,n_images=None,maxFeatures...
#!/usr/bin/python # -*- coding: UTF-8 -*- class Sentence(object): def __init__(self): self.id = '' self.languages = [] def get_id(self): return self.id def set_id(self, id): self.id = id def get_languages(self): return self.languages def set_languages(s...
from channels.routing import ChannelNameRouter, ProtocolTypeRouter, URLRouter from django.conf.urls import url from .consumers import ClientConsumer, MainConsumer, WorkerConsumer from .protocol import CHANNEL_MAIN, CHANNEL_WORKER application = ProtocolTypeRouter( { # Client-facing consumers. 'webs...
class Solution(object): def numSpecialEquivGroups(self, A): """ :type A: List[str] :rtype: int """ from collections import defaultdict res = [] for a in A: a_len = len(a) odd = defaultdict(int) even = defaultdict(int) ...
#!/usr/bin/env python # # Copyright 2013 Google 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 requir...
from sklearn.model_selection import StratifiedKFold import pandas as pd skf = StratifiedKFold(n_splits=10, random_state=48, shuffle=True) def CV(predictors,target): for fold, (train_index, test_index) in enumerate(skf.split(predictors, target)): x_train, x_valid = pd.DataFrame(predictors.iloc[train_i...
# -*- coding:UTF-8 -*- from rest_framework import serializers from . import models from delivery.models import InitDwdOrder class NotifyOrderSerializer(serializers.ModelSerializer): class Meta: fields="__all__" model=models.NotifyOrderModel class InitDwdOrderSerializer(serializers.ModelSerializ...
import unittest from time import sleep from src.librecatastro.scrapping.parsers.parser_xml import ParserXML class ParserXMLTests(unittest.TestCase): def test_search_by_coordinates_creates_and_stores_in_elasticsearch(self): cadaster_list = ParserXML.process_search_by_coordinates(-3.47600944027389, 40.537...
from rest_framework import serializers from user.models import User class UserDetailSerializer(serializers.ModelSerializer): """ Serializer for User Model """ password = serializers.CharField( style= {'input_type':'password'} ) class Meta: model = User fields = ('id', ...
#!/usr/bin/python import sys import operator oldKey = None maxCount = 0 hotCount = 10 # this can be set to 100 for checking if 100 replies/ comments are there, I am just using 10 for ease # Loop around the data; we are actually doing left outer join here of node with users. for line in sys.stdin: thisKey = lin...
from .task import TaskRepository REPOSITORIES = [TaskRepository]
from src.settings.load import * from src.coords import * from src.imageio import * from src.mappoint import * import sys class Observation: def __init__(self, frame, x, y): self.mappoint = None self.cx = x self.cy = y self.frame = frame self.leftx = int(x) - HALF_PATCH_SIZE ...
# -*- coding: utf-8 -*- # Author: Eduardo Vannini # Date: 22-02-2020 import numpy as np from Simulator import Simulator class BBSimulator(Simulator): """ Classe qui represente un simulateur "general" pour un systeme ball and beam decrit comme suit: - Vecteur d'etat : [position, vitesse] ...
import xlsxwriter from xlrd import open_workbook from scipy import signal row = 0 col = 0 list = [] wb = open_workbook('data_PC_NBC_UTPC_UTPC.xlsx') sheet = wb.sheet_by_index(0) workbook = xlsxwriter.Workbook('data_PC_NBC_UTPC_UTPC_u.xlsx') worksheet = workbook.add_worksheet() i = 0 for row_num in range(sheet.nrows): ...
# this will be a module def print_app(): #Get the name of the file __name__ and store it in name name = (__name__) return name # __main__ gets printed # print(print_app())
# # Death Blossom strategy module # import itertools from logger import * from playbook import * from sudoku import * from almost_locked_set import * class DeathBlossom(AlmostLockedSet): __metaclass__ = StrategyMeta """ Death Blossom is yet another variation of the strategies based on the Almost Loc...
import subprocess, pickle, os, sys, getopt, shutil, logging, glob, re import math, joblib, argparse, copy, time, contextlib, functools, itertools import numpy as np import threading from types import ModuleType from functools import partial mpl_logger = logging.getLogger("matplotlib") mpl_logger.setLevel(logging.ERROR...
#!env python3 # -*- coding: utf-8 -*- import unittest class Calc: def add(self, a, b): return a + b def sub(self, a, b): return a - b def is_even(self, num): return num // 2 class TestSetUpTearDown(unittest.TestCase): @classmethod def setUpClass(cls): print("setU...
""" compare the efficiency of list comprehension and append """ import time n_list = [10**3, 10**4, 10**5] for n in n_list: t1 = time.time() a1 = [i for i in range(n)] t2 = time.time() a2 = [] for i in range(n): a2.append(i) t3 = time.time() del a1, a2 print("length={}, list compre...
def calculate(s): """ :type s: str :rtype: int """ s += "+0" num, stack, op = 0, [], "+" for i in range(len(s)): if s[i].isdigit(): num = num * 10 + int(s[i]) elif not s[i].isspace(): if op == "+": stack.append(num) elif o...
import matplotlib matplotlib.use('Agg') import pandas as pd import numpy as np import math from sklearn.metrics import roc_curve, roc_auc_score import matplotlib.pyplot as plt def convertSeq(inputMat): res = {} for c, i in enumerate(range(len(inputMat)), 1): curMat = inputMat[i] curSeq = np.ar...
from __future__ import print_function import configargparse import torch import torch.nn as nn from torch.autograd import Variable import torch.backends.cudnn as cudnn import torchnet as tnt from torchnet.engine import Engine from torchnet.logger import VisdomPlotLogger, VisdomLogger from tqdm import tqdm from models i...
from .constants import * class Soldier: def __init__(self, is_me=False, face=UP, pos_h=0, pos_w=0): self.is_me = is_me self.face = face self.pos_w, self.pos_h = pos_w, pos_h self.last_post_w, self.last_pos_h = pos_w, pos_h self._set_matrix() def _set_matr...
class BaseFormatterException(Exception): def __init__(self, *args): if args: self.message = args[0] else: self.message = self.__doc__ def __str__(self): return self.message class NoMedia(BaseFormatterException): """The given media directory cont...
# coding:utf-8 from django.conf.urls import include, url from flashsale.dinghuo import views from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required from .views import DailyDingHuoStatsView, StatsByProductIdView, DailyWorkView from django.views.d...
import logging log = logging.getLogger('onegov.fsi') log.addHandler(logging.NullHandler()) from onegov.fsi.i18n import _ from onegov.fsi.app import FsiApp __all__ = ('FsiApp', 'log', '_')
import socket import spaceking.net as net import asyncio import spaceking.log as log EVT_CLIENT_CONNECTED = 17500 EVT_CLIENT_DISCONNECTED = 17501 class ClientConnection(net.Connection): """ Low level Cliet Connection Implements the low level connection routines. API has enqueue for TX data and deque...
from enum import IntEnum from more.webassets import WebassetsApp from onegov.core.orm import orm_cached from onegov.pay import log from onegov.pay import PaymentProvider from onegov.pay.errors import CARD_ERRORS from onegov.pay.models.payment import ManualPayment from onegov.pay.utils import Price from typing import ...
#Write a function named square that takes a number n and a parameter and returns that number squared def square(n): return n ** 2
default_app_config = 'computations.apps.ComputationsConfig'
import numpy as np import pandas as pd #Initializing Parameters: Temporary: The matrix would ideally be extracted from the CSV file Swetha provides #matrix is n x 10, n = 11 param = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] for i in range(10): param += [list(np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) * np.random.randint(2, 10...
# Generated by Django 3.0.3 on 2020-02-22 14:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_websites', '0007_auto_20200222_1432'), ] operations = [ migrations.AddField( model_name='pages', n...
from mangum import Mangum from app import app import logging logging.basicConfig() mangum_handler = Mangum(app) def lambda_handler(event, context): logging.info(f"Event: {event}") resp = mangum_handler(event, context) logging.info(f"Response: {resp}") return resp
import requests # pip install requests from bs4 import BeautifulSoup # pip install beautifulsoup4 import urllib.request from urllib.error import HTTPError from urllib.error import URLError from datetime import datetime from socket import timeout from requests.exceptions import ConnectionError import json, errn...
print('Общество в начале XXI века') x = int(input('Сколько Вам лет?')) def myfunc(x): if x >= 0 and x <= 7: t = 'Вам в детский сад' elif x > 7 and x <= 18: t = 'Вам в школу' elif x > 18 and x <= 25: t = 'Вам в профессиональное учебное заведение' elif x > 25 and x <= 60: t...
import requests # Class which describes main functionality of the bot class BotHandler: # Class constructor. Parameter "token" is your bot token def __init__(self, token): self.token = token self.api_url = 'https://api.telegram.org/bot{}/'.format(token) self.getUpdates = 'getUpdates' ...
from sys import argv script, filename = argv ifile = open(filename) print ifile.read() ifile.close
from selenium import webdriver from selenium.webdriver.common.keys import Keys from flask import Flask, render_template app = Flask(__name__) @app.route("/") def hello_world(): return "Hello! this is flask" @app.route("/hello/<bro>") def hello(bro): return "hello " + str(bro) @app.route("/template/<foo>") de...
#! /usr/bin/env python3 import os import sys import shutil def doesFolderExist(folderName): if os.path.isdir(folderName): return True return False def createMainCMakeLists(folderName): projectName = 'projectName' ## Create file filePath = folderName + '/CMakeLists.txt' os.mknod(filePath) # Ope...
linenum = int(input()) counter = 0 cmessages = [] while counter != linenum: smessage = str(input()) cmessages.append(smessage) counter += 1 ccounter = 1 fmessages = [] for x in range(0, len(cmessages)): fmessage = cmessages[x] tempmessages = [] for x in range(1, len(fmessage)): if fme...
import matplotlib.pyplot as plt import numpy as np import matplotlib matplotlib.rc('font', family='Arial') matplotlib.use('GTK') # Load data mjd_g, google = np.loadtxt('hw_2_data/google_data.txt', unpack=True, skiprows=1) mjd_n, ny_temp = np.loadtxt('hw_2_data/ny_temps.txt', unpack=True, skiprows=1) mjd_y, yahoo = np....
import os import urllib2 from django.conf import settings class LotteryTicketDataProviderFeedException(Exception): pass class LotteryTicketDataProvider(object): """ This class is responsible for retrieving the data feed """ PROVIDER_URL = "http://www.lotterynumbersxml.com/lotterydata/yoolotto.co...
# -*- coding: UTF-8 -*- import os import bencode import random import string from bencode import BTFailure video_ext = ['.avi', '.rmvb', '.rm', '.asf', '.divx', '.mpg', '.mpeg', '.mpe', '.wmv', '.mp4', '.mkv', '.vob'] key_str = ['#', '@', '_', '-', 'sexinsex', 'sis', 'sex8', '6ytk', '第一会所','第一會所'...
def commission_cal(pLock,pStock,pBarrel): sumPrice = 0.0 commission = 0.0 checkQuantity = True lock = 45.0 stock = 30.0 barrel = 25.0 pLock = int(pLock) pStock = int(pStock) pBarrel = int(pBarrel) if pLock <= 70.0 : sumPrice = sumPrice + (pLock*lock) else : ...
#-*- coding:utf-8 ''' save_result.py 这个文件的作用是保存结果 ''' import traceback def save_similarity_matrix(matrix, output_path): try: outfile = open( output_path, "w" ) for row_list in matrix: line = "" for value in row_list: line += ( str(value) + ',' ) ...
''' Created on 2016/05/22 /** <(?<tag>[^\s>]+)[^>]*>(.|\n)*?</\k<tag>> */ @author: hadoop ''' import re regexStr = "<(S*?)[^>]*>.*?|<.*?/>" htmlContent = """ <div style="background-color:gray;" id="footer"> </div> """ result = re.search(regexStr, htmlContent, re.M|re.I) print(result.groups())
import time import pyautogui import tkinter as tk def screenshot(): name =int(round(time.time()*1000)) name = 'C:/Users/Dell/Desktop/Courses and Certification/Python/Python 20+/screenshot data/{}.png'.format(name) #time.sleep(2) img = pyautogui.screenshot(name) img.show() root=tk.Tk() ...
import json import numpy as np import ast from test import newApproach, save_tf_model, add_assertion, add_solver from json_parser import parse, parse_solver from run_refinepoly import refinepoly_run INPUT_BOUND = (-3,3) EPS = 1 def create_model(len_in, no_layers, no_neuron): model = {} model["shape"] = str((1,...
#! /usr/bin/env python from scipy import linalg from sklearn.utils.extmath import safe_sparse_dot import numpy as np def randomized_krylov_svd(A, n_components, n_iter=8): m, n = A.shape # oversample a bit num_sample = n_components + 12 # Random block initialization G = np.random.normal(size=(A....
import os import sys import numpy as np scatter_list = [[0,1,2,3,4],[0,1,2,3,4]] scatter_list = np.array(scatter_list) matrix = np.zeros((4,4,1)) lists = [[] for i in range(25)] weight_lists = [0.0 for i in range(25)] sort_lists = [[] for i in range(25)] result_lists = [[] for i in range(25)] # print(all_list[:3])...
import random def single_random_scoop(pool): dict = pool.supply summer = sum(dict.values()) rand_val = random.randint(1,summer) total = 0 for k, v in dict.items(): total += v if rand_val <= total: return k def multi_scoop(pool, to_pool, size): for x in range(size): ...
# Copyright (C) 2016 Nokia Corporation and/or its subsidiary(-ies). # -*- encoding: utf-8 -* import unittest from deployment import notification class TestNotifierCollection(unittest.TestCase): def test_notifier_collection(self): class DummyNotifier(object): def __init__(self): ...
from django import forms class UploadSrtForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() #cloud_img = forms.ImageField()
#!/usr/bin/env ############################################ # testpackage.py # Author: Paul Yang # Date: June, 2016 # Brief: ############################################ from mypackage.subpackage1 import element1 from mypackage.subpackage1 import element2 from mypackage.subpackage2 import element1 from mypackage.su...
import re def findTargets(): file = open("ch3.txt"); text = ""; for line in file: text += line.strip(); file.close(); matches = re.findall("[a-z]{1}[A-Z]{3}[a-z]{1}[A-Z]{3}[a-z]{1}", text); return "".join([sub[4] for sub in matches]); if __name__ == '__main__': print(findTarge...
from __future__ import absolute_import from __future__ import print_function import os import logging from . import inference_proxy_client from . import messages from . import client_base log = logging.getLogger(__name__) class InferenceProxyAPI(client_base.InferenceClientBase): def __init__(self, intent_model_...