text
stringlengths
38
1.54M
from .c_attack import CAttack from .c_attack_mixin import CAttackMixin from .evasion import * from .poisoning import *
from __future__ import absolute_import from __init__ import ForceBalanceTestCase import unittest import forcebalance import os, sys from forcebalance.parser import parse_inputs from forcebalance.forcefield import FF from forcebalance.objective import Objective from forcebalance.optimizer import Optimizer from forcebala...
import os import json import time import requests import click from kryptos.data.manager import AVAILABLE_DATASETS from kryptos.scripts.build_strategy import load_from_cli from kryptos.scripts.kill_strat import kill_from_api from kryptos.settings import REMOTE_BASE_URL, LOCAL_BASE_URL @click.command(help="Launch mu...
def swapfiledata(): file1= input() file2= input() with open(file1, 'r') as a: data_a= a.read() with open(file1, 'w') as a: a.write(data_b) swapfiledata()
#Fibonacci sequence 0,1,1,2,3,5,8,13........... fir,sec=0,1 n=int(input("Enter the limit")) if n==1: print(fir) elif n==2: print(fir,sec) else: print(fir,sec,sep=" ",end=" ") for i in range(3,n+1): next=fir+sec fir,sec=sec,next print(next,end=" ")
# zadanie 3.5 print "\n Zadanie 3.5" jednostka = "|...." koniec = "|" dlugosc = int(raw_input("Podaj dlugosc \n")) miarka = jednostka * dlugosc + koniec podzialka = "" for item in range(dlugosc +1): if item == 9 : podzialka = podzialka + str(item).ljust(4) else: podzialka = podzialka + str(i...
from sympy import solve, sympify from Commands.AbstractCommand import AbstractCommand class EquationSolveCommand(AbstractCommand): def __init__(self): self.equation = None @property def name(self): return 'SOLVE' @property def help(self) -> str: return 'Решает вводимые по...
from line_event_handlers import abstract_line_event_handler from line_event_handlers import exchange_rate_event_handler from line_event_handlers import mops_event_handler from line_event_handlers.abstract_line_event_handler import * from line_event_handlers.exchange_rate_event_handler import * from line_event_handlers...
# -*- coding: utf-8 -*- """ Created on Sat Jun 6 23:43:12 2020 @author: MMOHTASHIM """ from main_agent import agent from agent_play import * import params def run(train=True,play=True): champ=agent() champ.sample_from_evnironment(params.SAMPLE_SIZE) if train: champ.main_model_train(total_iteratio...
"""Implementation of Multidictionaries """ def multidict(single_dict): """Splits a single dictionary into multiple dictionaries. Parameters ---------- single_dict : dict A python dictionary. Each key should map to a list of values. Returns ------- list A list, where the f...
import sys T = int(sys.stdin.readline().rstrip()) N = list(map(int,sys.stdin.readline().split())) # 런타임 에러 # def bubble_swap(x,i,j): # x[i], x[j] = x[j], x[i] # # def bubblesort(x): # for size in reversed(range(len(x))): # for i in range(size): # if x[i] > x[i+1]: # bubble_...
# Copyright (c) 2021 Qualcomm Technologies, Inc. # All Rights Reserved. import os import sys import time import random import numpy as np import torch import torch.nn as nn from quantization.range_estimators import RangeEstimators def seed_all(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = st...
import functools print( functools.reduce( lambda x, y: x * y, list( map( int, input().split() ) ) ) ** 5 ) На вход подаётся последовательность натуральных чисел длины n≤1000.Посчитайте...
# a variation of bubble sort but faster def cocktailsort(arr): n = len(arr) swap = True start = 0 end = n-1 while (swap == True): swap = False for i in range(start, end): if (arr[i] > arr[i+1]): arr[i], arr[i+1] = arr[i+1], arr[i] swap =...
import os import docente as d import secretaria as s class menuCadastro(): docente = d.docente() secretaria = s.secretaria() #def __init__(self): def exibir(self): while True : os.system('cls' if os.name == 'nt' else 'clear') print('-'*40) print('''M...
import wave import os import numpy as np import matplotlib.pyplot as plt from numpy import random import scipy.io as sio import pandas as pd def LoadSoundSet(path): filename= os.listdir(path) #得到文件夹下的所有文件名称 data = [] for i in range(len(filename)): f = wave.open(path+filename[i],'rb') par...
#python code goes here #python version :3 n = int(input("Enter the number of elements :")) k = int(input("Enter No. of rotations : ")) array = [] new_array = [] for i in range(n): array.append(int(input())) while k>0: for i in range(n): new_array.append(array[i-1]) for i in range(n): ...
import tensorflow as tf import tensorflow.keras as keras import matplotlib.pyplot as plt (train_images, train_labels), (test_images, test_labels) = keras.datasets.fashion_mnist.load_data() train_images, test_images = train_images / 255.0, test_images / 255.0 # show images for test # plt.figure(figsize=(5, 5)) # for ...
from haystack.indexes import * from haystack import site import djangobb_forum.models as models class PostIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) author = CharField(model_attr='user') created = DateTimeField(model_attr='created') topic = CharField(model_attr='top...
from multiprocessing.pool import ThreadPool # uses threads, not processes import feedparser import sqlite3 from sumy.parsers.html import HtmlParser from sumy.nlp.tokenizers import Tokenizer from sumy.summarizers.lsa import LsaSummarizer as Summarizer from sumy.nlp.stemmers import Stemmer from sumy.utils import get_sto...
__author__ = 'xx' if __name__ == '__main__': states = ['hot', 'cold'] observation_options = ['1', '2', '3'] start_transitions = [.8, .2] # start -> hot, cold transitions = [[.7, .3], # hot -> hot, cold [.4, .6]] # cold -> hot, cold observation_probs = [[.2, .4, .4], # hot -> ...
# 연습문제 5-1 # 리스트의 요소를 직접 나열해 정의하기 multiples_of_8_list = [0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96] # 결과 확인 print(multiples_of_8_list) # 레인지를 이용해 정의하기 multiples_of_8_list = list(range(0, 100, 8)) # 결과 확인 print(multiples_of_8_list)
import sys sys.path.append('../../Engine') from analyzer import * from tokenizer import * from features import * root = '../../Test' analyzer = Analyzer() filesList = analyzer.createCorpus(root) happyRaw = filesList.raw(fileids = 'happy.txt') happySent = filesList.sents(fileids = 'happy.txt') sentProc = SentenceProc...
import time import serial from stockfish import Stockfish import os white = False black = True ser = serial.Serial(port='COM3', baudrate=9600) # need to write a diff wrap function that waits for arduino to send ack def send(data : str): global ser ser.write(data.encode()) ack = ser.readline().decode() ...
# Generated by Django 3.1.5 on 2021-02-19 03:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auctions', '0015_comments_title'), ] operations = [ migrations.AlterField( model_name='comments', name='user', ...
from torchvision import transforms as T from torch import Tensor def default_transformer(input_size): data_transforms = { 'train': T.Compose([ T.Resize(int(input_size * 1.1)), # transforms.ColorJitter(0.1, 0.1, 0.1, 0.05), T.RandomHorizontalFlip(), T.RandomVe...
''' Given the head of a linked list, rotate the list to the right by k places. Eg. Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3] ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rota...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys,os import httplib import time import tradeManger import urllib2 import timetool httpClient = None tradetool = tradeManger.TradeManger() #btcc:https://data.btcchina.com/data/ticker?market=ltccny def getTickerurl2(): try: req = urllib2.Request...
def score_change(level, rows_cleared, points): point_system = {1 : 40 * (level + 1), 2 : 100 * (level + 1), 3 : 300 * (level + 1), 4 : 1200 * (level + 1), None : 0} return points + point_system[rows_cleared]
#!/usr/bin/env python3 s = "\\374\\375\\352\\300\\272\\354\\350\\375\\373\\275\\367\\276\\357\\271\\373\\366\\275\\300\\272\\271\\367\\350\\362\\375\\350\\362\\374" s = s.replace("\\352", "a") s = s.replace("\\353", "b") s = s.replace("\\354", "c") s = s.replace("\\355", "d") s = s.replace("\\356", "e") s = s.replace...
# -*- coding: utf-8 -*- # Copyright 2015 LIP - INDIGO-DataCloud # # 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 app...
import pytest from os import environ from selenium import webdriver from django.core import mail browsers = { 'firefox': webdriver.Firefox, } @pytest.fixture(scope='session', params=browsers.keys()) def web_browser(request): ''' Sets up and tears down browser instance ''' if 'DISPLAY' not in ...
def solve(n): if n == 0: return "INSOMNIA" i, N, digits= 1, n, [] while True: digits += [int(m) for m in str(n) if not int(m) in digits] if all(k in digits for k in range(10)): return n n += N i += 1 def a(): T = int(raw_input()) for t in range(1,T+1): ...
# ysoftman # locals() test def print_locals(): # 이 위치에서는 __name__ 키가 없음 print(locals()) # 로컬 변수 추가 a = 123 b = "lemon" print(locals()) # **으로 a, b 키값만 가져올 수 있다. print("{a} {b}".format(**locals())) # 현재 로컬 symbol 테이블(dictionary)을 담고 있다. # 이 위치에서는 __name__ 키가 있음 print("{__name__}".format...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-18 21:30 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pagina', '0001_initial'), ] operations = [ migrations.RemoveField( model_...
# -*- coding: utf-8 -*- """RSS feed reader module for Maraschino""" from flask import render_template import feedparser import time import hashlib import urllib import os from maraschino import logger, DATA_DIR from maraschino.tools import * import maraschino DISPLAYED_FEEDS = 5 INCREMENT_FEED = 1 def create_dir(t...
""" Mobility Model """ import numpy as np from pykdtree.kdtree import KDTree import math import pyximport import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties MonoFont = FontProperties('monospace') old_get_distutils_extension = pyximport.pyximport.get_distutils_extension def new_get_dis...
import numpy as np import os,json,sys from typing import Dict, Sequence, Type, Callable, List, Optional import torch from torch import nn sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from modules.transformers import BertModel,BertConfig,BertTokenizer from modules.MLP import MLP from mo...
def comb2(numlist): if len(numlist) == 2: return [numlist] else: head = numlist[0] tail = numlist[1:] combs = [] for x in tail: combs.append([head, x]) return combs + comb2(numlist[1:]) x = [1, 2, 3, 4] result = comb2(x) # print(result) def comb3(...
from django.apps import AppConfig class ValuationCalcConfig(AppConfig): name = 'valuation_calc'
# -*- coding: utf-8 -*- """ Created on Mon Jan 30 16:40:29 2017 @author: Marco """ from collections import namedtuple from pkg_resources import resource_filename from os.path import join import os.path import numpy as np import numpy.ma as ma import matplotlib.pyplot as plt import rasterio from itertools import combin...
from django.db.models import fields from rest_framework import serializers from .models import Drawings, Comments # class DrawingsSerializer(serializers.HyperlinkedModelSerializer): class DrawingsSerializer(serializers.ModelSerializer): class Meta: model = Drawings fields = '__all__' ...
# TODO: Re-enable once interoperability is a design goal again """ from unittest import TestCase import logging.config from uuid import uuid4 from py4j.java_gateway import JavaGateway from cadence.tests import init_test_logging from cadence.worker import Worker from cadence.workflow import workflow_method init_test_...
#!/usr/bin/python # -*- coding: utf-8 -*- """ """ import os import sys import time import re import datetime REGEX_HEAD_1 = re.compile(r'RetroEntreAmigos \d{1,2}x\d{1,2} - .*? \(\d{4}-\d{2}, \d{1,2}h \d{1,2}m \d{1,2}\.\d{3}s\)') # Line: 2 Concurso B-MOVE (3m 53.708s -- 7m 6.829s) REGEX1 = re.compile(...
n = 16 n = int(input()) if n< 0: print("Enter a positive number") else: sum = 0 while(n > 0): sum += n n-= 1 print("The sum is",sum)
from replay_processing.parseargs import parse_params from replay_processing.sc2files import parse_replays def main(): # Get params and environment variables params = parse_params() logger = params["logger"] # Parse replays using params logger.info("Parsing Replay Files") output_path = params...
T = int(raw_input()) def intersect(a, b, c, d): if a > c and d > b: return True if a < c and d < b: return True return False for test in xrange(1, T + 1): N = int(raw_input()) wires = [] ans = 0 for i in range(0, N): a, b = [int(i) for i in raw_input().split(" ")] ...
# -*- coding:utf-8 -*- from django import forms from django.forms import ModelForm from polls.models import * from django.core.exceptions import ValidationError from django.contrib.auth import authenticate # from django.db import models # import re # from django.core.exceptions import ValidationError class LoginForm(...
# -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from django.contrib.admin.models import LogEntry from cmdb.models import * import json import datetime from django.views.decorators.csrf import csrf_exempt from django.contrib i...
import argparse from yolo import YOLO, detect_video, detect_live from PIL import Image from io import BytesIO import tensorflow as tf import requests from flask import Flask, request from flask_restful import Resource, Api from flask_restful import reqparse from werkzeug import secure_filename import cv2 app = Flask...
from torch.utils.data import Dataset import json import os import cv2 def text_to_seq(text, abc): seq = [] for c in text: seq.append(abc.find(c) + 1) return seq class TextDataset(Dataset): def __init__(self, data_path, mode="train", transform=None): super().__init__() self.data...
# coding = utf-8 class Node: def __init__(self, elem, next_ = None): self.elem = elem self.next = next_
from termcolor import colored from Databases.PostgreSQL import run_server from global_param import user_agent from http_request import fetch from ipv4_generator import * random_ip, ip_data = gen_ipv4() print(colored(ip_data, 'cyan', attrs=['underline'])) random_sid = run_server() url = 'http://in.eu.adopexchange.com...
from MyModule import gcd from MyModule import Fraction print(gcd(10,5)) x = Fraction(1,2) y = Fraction(2,3) print(x+y) print (x==y)
class Solution: def twoSum(self, nums, target): lookup = {} for i in range(len(nums)): diff = target - nums[i] if lookup.get(diff, None) is not None and lookup.get(diff, None) != i: return [i, lookup.get(diff)] lookup[nums[i]] = i
#!/usr/bin/env python # vim:fileencoding=utf8 from pprint import pprint import requests import json # import sys from datetime import date, timedelta from dateutil.rrule import rrule, DAILY from dateutil.rrule import MO, TU, WE, TH, FR # from dateutil.rrule import SU, SA import random import copy from itertools impor...
from __future__ import print_function """ pie - Python Interactive Executor Enables a user to execute predefined tasks that may accept parameters and options from the command line without any other required packages. Great for bootstrapping a development environment, and then interacting with it. """ __VERSION__='0.3.0...
#화물도크 T = int(input()) for tc in range(T): N = int(input()) tlist = [list(map(int, input().split())) for _ in range(N)] temp = sorted(tlist, key = lambda x:x[1]) count = 1 now = 0 n = 1 while n < len(temp): if temp[n][0] < temp[now][1]: n += 1 else: count += 1 ...
from bigchaindb_driver.exceptions import BadRequest def get(query, connection): query = "\"{}\"".format(query) print('bdb::get::query:{}'.format(query)) assets = connection.assets.get(search=query) metadata = connection.metadata.get(search=query) print('bdb::result:: #assets: {} - #metadata: {}' ...
import binascii # Code has been imported from Star20.py # Function that performs the knot hash def knot_hash(lengths): # Initializes the 0-255 list complete_list = [] for i in range(256): complete_list.append(i) current_index = 0 skip_size = 0 # Repeat the hash 64 times for repea...
#!/usr/bin/python3 tempin = input("Enter the temperature: ") val,unit = tempin.split(" ") val = float(val) if (unit =='c' or unit =='C'): tempout = (val*9/5) + 32 print("Tempratur in farenheit is : {} F".format(tempout)) elif (unit =='f' or unit == 'F'): tempout = (val-32)*5/9 print("Tempratur in celcius is : {} C"...
from __future__ import unicode_literals from __future__ import print_function import random import inout from inout import ask import sql # region SQL SQL_SPEELBARE_KARAKTERS = "SELECT naam FROM personages WHERE speelbaar = 1" SQL_VRIENDEN = "SELECT met FROM vriendschappen WHERE naam == ?" SQL_VREEMDEN = "SELECT naam...
# Pygame based on https://github.com/JCLOH98/Hangman-Pygame import pygame import sys import random import time import re from pygame.locals import * pygame.init() pygame.display.set_caption("Hangman") BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) GREY = (200, 200...
import numpy as np def exist(p1,p2,p3,p): u=np.subtract(p2,p1) v=np.subtract(p3,p1) w=np.subtract(p,p1) n=np.cross(u,v) mag=sum(map(lambda x:x*x,n)) g_cross=np.cross(u,w) b_cross=np.cross(w,v) gamma=float(np.dot(g_cross,n))/mag beta=float(np.dot(b_cross,n))/mag alpha=1-gamma-beta x=np.multiply(p1,alpha) ...
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError from django.db import transaction from tina.projects.attachments.models import Attachment import logging logger = logging.getLogger(__name__) class Command(BaseCommand): @transaction.atomic def handle(self, *args, **o...
import vk_api import random from vk_api.utils import get_random_id from vk_api.bot_longpoll import VkBotLongPoll from vk_api.bot_longpoll import VkBotEventType TOKEN = "b24e5b10bb881b1eb586d1b193544ab6d03bbdde8a2b3bb9333601196ae97fe2be2e191f443f58691c2a9" vk_session = vk_api.VkApi(token=TOKEN) vk = vk_sessio...
import json import logging import os from pathlib import Path log = logging.getLogger(__name__) FWV0 = Path.cwd() def get_and_log_environment(): """Grab and log environment to use when executing command lines. The shell environment is saved into a file at an appropriate place in the Dockerfile. Return...
import unittest import itertools from functools import partial from hash_tables import HashTable from linked_lists import LinkedList class TestHashTable(unittest.TestCase): def test_init_container_type_must_have_search_insert_delete_if_resolution_is_not_overwrite(self): # Arrange class Foo():...
import tkinter as tk from tkinter import * from tkinter import messagebox # window = Tk() def Login(): root = Tk() root.geometry('420x200') root.title("Welcome to Login") label_1 = Label(root, text="Username",fg="red") label_2 = Label(root, text="Registration no",fg="red") ...
# _*_ coding: utf-8 _*_ from accounts.models import UserProfile from models import Book, Branch, BookComment, BranchLike, Bookmark, BranchComment from forms import BookCreationForm, BranchCreationForm, BookCommentForm, BranchCommentForm from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.sh...
import pygame import time pygame.init() #Sets the size of our display - (width, height) #And will display it for a second as well displayWidth = 800 displayHeight = 600 black = (0,0,0) white = (255,255,255) red = (255,0,0) car_width = 73 gameDisplay = pygame.display.set_mode((displayWidth, displayHeight)) pygame....
import sys sys.setrecursionlimit(5000) T = int(raw_input()) # string is an array of letters that represent the codeword def produce_codeword(string): if len(string) == 1: return string[0] elif len(string) == 0: return '' max_letter = max(string) next_index = len(string) - string[::-...
from django.contrib import admin from .models import School, Performance # Register your models here. admin.site.register(School) admin.site.register(Performance) # Register your models here.
from django.urls import include, path, reverse from rest_framework import status from rest_framework.test import APITestCase, URLPatternsTestCase from api.models import * import requests class Bike: def create(self): data = { "serialnumber": "191919191", "framesize": 52.0, ...
n=int(input("enter the value of 'n': ")) a=0 b=1 sum=0 count=1 print("fibonacci series:",end=" ") while(count<=n): print(sum,end=" ") count +=1 a =b b =sum sum=a+b
#!/usr/bin/env python # -*- coding: utf-8 -*- """ spider """ __author__ = 'shiyu.feng' import common.http_util as http from bs4 import BeautifulSoup import re def __find_page(html_text): soup = BeautifulSoup(html_text, 'html.parser') return int(soup.find(class_='fanye').find('span').string.replace(u'共', u'...
from django.conf.urls import url from login import views urlpatterns = [ url(r'^login/$', views.login_page, name='login_page'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^register/$', views.register_page, name='register_page'), url(r'^profile/$', views.profile, name='profi...
### ############################################################################################################ ### # ### # Project: # Url Tester ### # Author: # The Highway ### # Description: # ### # ### #####################################################################################################...
import json import urllib import re import requests import sys def download_image(detail_list): for index, data in enumerate(detail_list): result = re.search(r'http://image3.photochoice.net/r/tn_(\d+_\d+_\d+_\d+_[\d\w]+_\d+)', data) imageUrl = r'http://image3.photochoice.net/r/tn_{0}/pc_watermark_1...
# -*- coding: utf-8 -*- # Copyright 2011-2016 by Luc Saffre. # License: BSD, see LICENSE for more details. """ - `intersphinx_mapping` : The intersphinx entries for projects managed in this atelier. Atelier gets this information by checking for an attribute `intersphinx_urls` in the global namespace of each p...
#!/usr/bin/python3 import sys import argparse import timeit START_TIME = timeit.default_timer() DFA = { 0:{'5':1}, 1:{'7':2, '8':3}, 2:{'p':4}, 3:{'a':4}, 4:{'8':3, '7':5}, 5:{'p':4} } class BColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\0...
import csv import os from BefreeBingo.settings import BASE_DIR from django.core.management import BaseCommand from user.models import UserTraffic class Command(BaseCommand): def handle(self, *args, **options): csv_target_path = os.path.join(BASE_DIR, 'media', 'user_traffic.csv') if os.path.exist...
#!/usr/bin/env python import sys import subprocess import time from datetime import datetime ############################################# # Define script variables ############################################# log_filename = "./remote-execute.log" default_username = "bettychen" num_pass = 0 num_fail = 0 def LOG(me...
""" Copyright 2019 EUROCONTROL ========================================== 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 and...
arr=[10,20,30,40,50] print(arr[0]) print(arr[-1]) print(arr[-2]) brands = ["Coke", "Apple", "Google", "Microsoft", "Toyota"] num_brands = len(brands) print(num_brands) add=['a','b','c'] add.append('d') print(add) colors=["violet","indigo","blue","green","yellow","orange","red"] del colors[4] ...
#!/usr/bin/python3 from LinkedList.LinkedList import LinkedList linked_list = LinkedList() linked_list.insert_start(23) linked_list.insert_start(33) linked_list.insert_start(36) linked_list.traverse() print('\n\n ==== ') linked_list.remove(23) print(linked_list.size()) linked_list.traverse() print('\n\n ==== ') l...
""" Development of FTIR processing algorithm To Do: - Improve baseline and area normalization - Improve gaussian peak fitting (maybe restrict peak widths and movement) - Improve file open to enable opening in any directory, not just current directory B.Kendrick modifications to file in April 2018 include: ...
import abc from typing import List, Dict class TrainingCallback(metaclass=abc.ABCMeta): """Abstract Train callback class.""" def handle_result(self, results: List[Dict], **info): """Called every time train.report() is called. Args: results (List[Dict]): List of results from the t...
import tensorflow as tf import numpy as np # a = tf.Variable(tf.random_normal([1,5,5,3])) # b = tf.Variable(tf.random_normal([3,3,3,1])) # c = tf.nn.conv2d(a, b, strides = [1,1,1,1], padding='SAME') # init = tf.initialize_all_variables() # with tf.Session() as sess: # sess.run(init) # print(sess.run(c)) a =...
infile = open('VPres.txt', 'r') vicePresList = {line for line in infile} infile.close() infile2 = open('USPres.txt','r') presList = {line for line in infile2} outfile = open('Both2.txt', 'w') outfile.writelines(vicePresList.intersection(presList)) infile2.close() outfile.close()
import torch import torch.nn.functional as F from torch.nn.modules.loss import _Loss from torch.distributions import kl_divergence from .utils import shuffle_code class FactorVAELoss(_Loss): def __init__(self, args): super().__init__() self.args = args @property def loss_components(self)...
# !/usr/bin/env python # -*- coding:utf-8 -*- from time import sleep import pytest @pytest.fixture() def setup_module(): print('所有用力执行前清理一次') def test_1(cl): dr = cl dr.get('https://www.douban.com') dr.find_element_by_link_text('豆瓣读书').click() sleep(2) dd = dr.window_handles print(dd) dr...
import numpy as np from interfaces import pre_processing, activity_detection, feature_extraction, classificator import pandas as pd # noinspection INSPECTION_NAME def init_pre_processing(by_pass=False, bands = 8): global pre_processing_by_pass global n_bands n_bands = bands pre_processing_by_pass = by...
# -*- coding: utf-8 -*- from functools import wraps from flask import make_response def allow_cors(fn): @wraps(fn) def wrapped(*args, **kwargs): response = make_response(fn(*args, **kwargs)) response.headers["Access-Control-Allow-Origin"] = "*" response.headers["Access-Control-Allow-...
import os import os.path import glob import numpy as np np.random.seed(1) from keras.preprocessing.image import img_to_array from keras.utils import np_utils from keras.preprocessing import image from keras.applications.vgg19 import VGG19 from keras.applications.imagenet_utils import preprocess_input from keras.models ...
import cv2 import os from os.path import isfile, join import numpy as np dir_path1 = 'fore1' dir_path2 = 'back1' def SplitVideobyFrame(): out = cv2.VideoCapture('forground_video.mp4') frame_count = 1 while(True): retur, frame = out.read() file_name = './Foregound_Images/frame' + str(fr...
''' Created on 2016/08/26 @author: Brian ''' import re if __name__ == '__main__': pass #Value regex valueTagCheck = re.compile('(<Value>)(.*)(</Value>)') keyTagCheck = re.compile('(<Key>)(.*)(</Key>)') valueExample = '''<Key>Fried Egg</Key> <Value>-5 1/10 10/194/default</Value> ...
#!/usr/bin/python3 """ 50. Pow(x, n) Difficulty: Medium Success Runtime: 144 ms, faster than 5.92% of Python3 online submissions for Pow(x, n) Memory Usage: 14.3 MB, less than 49.63% of Python3 online submissions for Pow(x, n) """ from typing import List import time class Solution: def myPow(self, x: float, n: ...
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: tmp = "" res = [] wordDict = set(wordDict) self.dfs(s, tmp, res, wordDict) return res def dfs(self, s, tmp, res, wordDict): if self.wordBreakI(s, wordDict): if not ...
from PIL import Image from colorsys import hsv_to_rgb from ledcontrol.animationcontroller import AnimationController import ledcontrol.animationfunctions as animfunctions import ledcontrol.colorpalettes as colorpalettes import ledcontrol.pixelmappings as pixelmappings import ledcontrol.driver as driver import ledcontro...