text
stringlengths
8
6.05M
NM = input() N, M = int(NM.split()[0]), int(NM.split()[1]) dms = set([]) bms = set([]) for _ in range(N): dms.add(input()) for _ in range(M): bms.add(input()) dbms = dms & bms dbms = list(dbms) print(len(dbms)) dbms.sort() for i in dbms: print(i) # Done
import pygame import setup import constants as c import time class Coin(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.sprite_sheet = setup.picture['item_objects'] self.frame = [] self.set_frame() self.frame_index = 0 #TODO ...
import asyncio import mqttools import logging async def handle_messages(client): while True: topic, message = await client.messages.get() print(f'Got {message} on {topic}.') if topic is None: print('Connection lost.') break async def reconnector(): client = m...
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('publico.urls', namespace="publico")), path('admin/', admin.site.urls), path('usuario/', include('usuario.urls')), path('v...
import threading import Globals from Connect import * class Motor(threading.Thread): # Initialize thread and Motor instance attributes def __init__(self): threading.Thread.__init__(self) self.killReceived = False self.x = 0 self.y = 1 self.rightMotor = 0 self.leftMotor = 1 self.port = 0 self.serial =...
# -*- coding: utf-8 -*- import networkx as nx import nx_multi_shp import os from osgeo import ogr def convert_shp_to_graph(input_shp, directed, multigraph, parallel_edges_attribute): """Converts a shapefile to networkx graph object in accordance to the given parameters. It can directed or undirected, simp...
# Generated by Django 2.2.6 on 2019-11-05 09:56 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('work', '0012_remove_shiftedqtyextra_site'), ] operations = [ migrations.CreateModel( name='Site...
import time, pytest import sys,os sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib'))) from clsCommon import Common import clsTestService from localSettings import * import localSettings from utilityTestFunc import * import enums class Test: #=========================...
# string1 = "hello" # string2 = "o" # #print(string1[1:] + string1[0]) # #print(string1[0]) # print(string2[1:]) # array1 = [5, 12, 4, 6, 7, 21, 34, 6, 7, 32, 4] # biggest = array1[0] # for i in array1: # # print(i) # if i > biggest: # biggest = i # print(biggest) # racecar = "racecar" # print(raceca...
# -*- encoding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import from __future__ import division import os import sys reload(sys) sys.setdefaultencoding("utf-8") import numpy as np import unittest import poketto.metrics as metrics class TestBinaryMetrics(unittest.TestCase): ...
from django.conf.urls.defaults import * import apiserver as api import organization class TOC(api.TOC): class Meta: route = '' resources = [organization.resources.Organizations] v1 = api.API('v1') v1.register(TOC) v1.register(organization.resources) v1.register(api.explorer.Explorer) urlpatterns...
import unittest from moviesnotifier import (UrlLibHtmlRetriever) class UrlLibHtmlRetrieverTest(unittest.TestCase): def setUp(self): self.retriever = UrlLibHtmlRetriever() def test_retrieveHtml(self): url = "http://example.com/" html = self.retriever.get(url) self.assertIn("<h1>Example Domain</h1>...
from entity.item import Item from entity.product import Product from typing import Optional class Basket: def __init__(self): self._items = [] def add_item(self, item: Item) -> None: exist_item = self.get_item_from_product(item.product) # if exist_item: # exist_item.add_qu...
from django.shortcuts import render,redirect from django.http import HttpResponse from .models import Post from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib import messages from django....
import sys from datetime import datetime from multiprocessing import Pool, cpu_count from pathlib import Path from functools import reduce from fbprophet import Prophet import pandas as pd from tqdm import tqdm def split_series(df): """Splits DataFrame into one DataFrame for each time series.""" series = [] ...
from .block_loader import BlockLoader # noqa F401 from .investigator_loader import InvestigatorLoader # noqa F401 from .observation_loader import ObservationLoader # noqa F401 from .observing_window_loader import ObservingWindowLoader # noqa F401 from .proposal_loader import ProposalLoader # noqa F401
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'testParametrow.ui' ## ## Created by: Qt User Interface Compiler version 5.14.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ###########...
""" File: proj04_short.py Author: Abraham Aruguete Purpose: So this project contains three functions which will be called by Russ' testcases. I'm actually working on writing down a pre-plan for my code instead of just rushing in there coding this time! How pleasant. I think I'm maturing. """ def compare_front(...
# -*- coding: utf-8 -*- """ Created on Thu Mar 7 01:35:39 2019 @author: Anubhav """ import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split from sklearn import metrics from sklearn import preprocessing from sklearn.preprocessing import LabelEncoder #Classificatio...
from string import maketrans DNA = maketrans('ACGT', 'TGCA') def DNA_strand(string): """ dna_strand == PEP8 (forced naming by CodeWars) """ return string.translate(DNA)
#!/usr/bin/python3 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib def sendMail(): msg = MIMEMultipart() # General settings msg['from'] = 'form@example.com' msg['to'] = 'to@example.com' msg['subject'] = 'your_subject' message = 'your_messages...
from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views app_name = 'books' urlpatterns = [ # ex: /readospher/ path('', views.IndexView.as_view(), name='index'), path('books/', views.BookSearchListView.as_view(), name='book-search-list...
import random import scrabble_points from wordlist import get_wordlist FREQUENCY = { 'A': 9, 'B': 2, 'C': 2, 'D': 4, 'E': 12, 'F': 2, 'G': 3, 'H': 2, 'I': 9, 'J': 1, 'K': 1, 'L': 4, 'M': 2, 'N': 6, 'O': 8, 'P': 2, 'Q': 1, 'R': 6, 'S': 4, '...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). """Generates a JSON schema file to be uploaded to the JSON schema store (https://www.schemastore.org/json/). The schema file is used by IDEs (PyCharm, VSCode, etc) to provide intellisense w...
from django.contrib import admin from .models import Board, User, SelectKnight, Election, Expedition, Game, GameHistory # 추가 from .models import Knight # 추가 # Register your models here. class KnightAdmin(admin.ModelAdmin): list_display = ('knightId', 'name', 'evlYn',) class UserAdmin(admin.ModelAdmin): ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-30 11:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalogues', '0003_auto_20170830_1430'), ] operations = [ migrations.AlterF...
from __future__ import unicode_literals from django.db import models import re, bcrypt NAME_REGEX = re.compile(r'^[a-zA-Z\s]+$') USERNAME_REGEX = re.compile(r'^[\w\s]+$') SPACE_REGEX = re.compile('.*\s') class UserManager(models.Manager): def validate_reg(self, input): errors = [] name = input['na...
from marshmallow import Schema, fields, validate from settings.database import session from utils.serializers import BaseSchema # Create your serializers here. class AuthenticationSchema(Schema): username = fields.Str( required=True, allow_none=False, validate=validate.Length(min=4) )...
import os,sys,time,traceback as tb,re,json from pprint import pprint data = ''.join(sys.stdin.xreadlines()) def get_tuple(cursor, name, tup, skip_ws=True): if skip_ws: ws,cursor = get_ws(cursor) ret = {} cursor0 = ret['start'] = cursor while data.startswith(tup, cursor): cursor += 1 pas...
# -*- coding: utf-8 -*- """ Created on Thu Mar 20 19:00:59 2014 @author: jgr42_000 """ from __future__ import division import numpy as np #import operator as op import itertools #from collections import OrderedDict import copy import os import argparse import cPickle from mpl_toolkits.mplot3d.axes3d import Axes3D ...
def dijsktra_sparso(nodo, grafo): from heapq import heappop, heappush from math import inf distanze = [inf for _ in grafo] distanze[nodo] = 0 visitati = {nodo} # Inizializzo heap. heap = [] for adiacente, costo in grafo[nodo]: distanze[adiacente] = costo heappush(heap,...
import sys, os import Sorting_Algorithm #If decide to start without input array array = [10, -9, 8, -7, 6, -5, 4, -3, 2, -1, 0] # Main definition - constants menu_actions = {} # Main menu def main_menu(): os.system('CLS') print("Welcome,\n") print("Please choose the menu you want to start:...
""" Week 1, Day 2: Jewels And Stones You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all ch...
import pygame from pygame import * from pygame import display from pygame import movie import sys import time from random import * #Colors Aqua = (0, 255, 255) Black = (0, 0, 0) Blue = (0, 0, 255) CornflowerBlue = (100, 149, 237) Fuchsia = (255, 0, 255) Gray = (128, 128, 128) Green = (0, 128, 0) Lime = (0, 255, 0) Ma...
a,b=map(int,input().split(" ")) l=list(map(int,input().split(" "))) r=[[abs(i-b),i]for i in l] r=sorted(r) r=r[1:] r=[i[1] for i in r[ :3]] print(*r)
import os import re import sys import _pickle as cPickle from sklearn.metrics.pairwise import linear_kernel from collections import OrderedDict from module import ProcessQuery as pq domain=sys.argv[1] userUtterance=sys.argv[2] scriptDir=os.path.dirname(__file__) picklePath=os.path.join(scriptDir,'model',domain+'_') ...
# coding:utf-8 from __future__ import absolute_import, unicode_literals __author__ = "golden" __date__ = '2018/7/20' from jspider.web.app import app_creator from jspider.utils.config import Config from jspider.manager.spider import SpiderManager if __name__ == '__main__': config = Config() config.from_pyfile('...
import boto3 import logging import botostubs from botocore.exceptions import ClientError boto_session = boto3.Session(profile_name='personal') ec2: botostubs.EC2 = boto_session.client('ec2', region_name='ap-south-1')
import codecs import json file_cidades = codecs.open('cidades.json', encoding='utf-8') cidades_texto = file_cidades.read() cidades_json = json.loads(cidades_texto) for cidade in cidades_json: print(cidade)
# -*- coding: utf-8 -*- """ Created on Tue May 12 14:58:16 2020 @author: logam """ import matplotlib.pyplot as plt import numpy as np import cv2 img = cv2.imread('test3.jpg') plt.figure(dpi=300) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) print(img) hist, bins = np.histogram(img.flatten(), 256,[0,256]) equ = cv...
origin = open('idf_sample/simple.idf', 'r') new = open('idf_sample/simple.idf.tmp', 'w') for line in origin: new.write(line.replace('@@Height@@', '1000')) origin.close() new.close()
import os from unittest import TestCase, mock from src import env MONGODB_CONNECTION_STRING = 'a mongodb connection string' class TestEnv(TestCase): def setUp(self): self.addCleanup(mock.patch.stopall) mock_env = { 'MONGODB_CONNECTION_STRING': MONGODB_CONNECTION_STRING } ...
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS from os import environ import json import datetime import requests app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db =...
import os import sys import shutil def find_family_index(alignments_info_file, alignment_name): lines = open(alignments_info_file).readlines()[1:] for i in range(0, len(lines)): if "/" + alignment_name in lines[i] or lines[i].startswith(alignment_name): return i return -1 def extract_line(input_file, ...
import os, sys import argparse import subprocess # return output from bash pipe cmd as decoded string def run_cmd(cmd): bash_cmd = cmd process = subprocess.Popen(bash_cmd.split(), stdout=subprocess.PIPE) output = process.stdout.read() return output.decode('utf-8') # return branches list def get_branches(): unwa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @copyright 2016 TUNE, Inc. (http://www.tune.com) # @version $Date: 2016-07-07 12:45:28 PDT $ import sys from pprintpp import pprint import pytz from pytz_convert import ( convert_tz_abbrev_to_tz_offset, convert_tz_abbrev_to_tz_seconds, convert_tz_name_t...
# -*- coding: utf-8 -*- """ Created on Sat Jun 22 21:32:15 2019 @author: HP """ T=int(input()) while(T): N=int(input()) A=input() sum=0 for i in range(N): if int(A[i])==1: k=0 for j in range(i,N): if int(A[j])==1: k=k+1 su...
"""Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. """ from mininet.topo import Topo class M...
import factory from colossus.apps.templates.models import EmailTemplate class EmailTemplateFactory(factory.DjangoModelFactory): name = factory.Sequence(lambda n: f'campaign_{n}') class Meta: model = EmailTemplate
#!/usr/bin/env python3 ######################################### ### CUAUV Hydrophones sample generator (modeled after code written by Patrick Dear # @ author Patrick Dear (translated to Python3 from Matlab by Noah Levy) ######################################### #Multipathing channel model taken from here: Underwater...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/20 15:05 # @Author : Jason # @Site : # @File : keras_test.py # @Software: PyCharm from keras.models import Sequential from keras.layers.core import Dense ,Dropout,Activation from keras.optimizers import SGD model = Sequential() #模型初始化 model...
# Generated by Django 2.2 on 2019-04-12 19:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('yohbiteapp', '0010_auto_20190412_0953'), ] operations = [ migrations.AddField( model_name='restau...
import datetime import unittest from collections import OrderedDict from unittest.main import main from wta.app import MatchScrapper def init_scrapper(build=False): instance = MatchScrapper(filename='test_page.html') if build: instance.build('player-matches__tournament') return instance class T...
class Solution: # @param A : list of integers # @return an integer import sys def findMinXor(self, A): mini = int(sys.float_info.max) n = len(A) for i in range(0,n-1): res = A[i] ^ A[i+1] mini = min(mini,res) return mini
from router_solver import * import game_engine.constants from game_engine.constants import * import game_engine.spritesheet from game_engine.spritesheet import * # Clase usada para rockas y moscas class Item(pygame.sprite.Sprite): def __init__(self, x, y, width, height, type): super().__init__() ...
#import import pygame import sys import time import math import random import shelve from random import randrange #Constants white = (255,255,255) lightgreen = (168,192,50) green = (97,178,56) darkgreen = (52,151,78) blue= (70,126,145) lblue = (153,217,234) yellow = (242,250,87) score_=0 distan...
#!/usr/bin/python3 s = 'Hello, Runoob' print(str(s)) print(repr(s)) print(str(1/7)) x = 10 * 3.25 y = 200 * 200 s = 'x的值为: ' + repr(s) + ', y的值为: ' + repr(y) + '...' print(s) # repr() 可以转义字符串中的特殊字符 hello = 'hello, runoob\n' hellos = repr(hello) print(hellos) # repr() 函数的参数可以是python的任何对象 print(repr((x, y, ('Googl...
from django.contrib import admin from django.urls import path, include, re_path from django.views.decorators.csrf import csrf_exempt from rest_auth.registration.views import VerifyEmailView from django.views.generic import TemplateView from django.conf import settings urlpatterns = [ path(r'admin/', admin.site.url...
import pyaudio import wave from scipy.fftpack import fft, ifft import numpy as np import matplotlib.pyplot as plt import cv2 from scipy import signal from swan import pycwt CHUNK = 1024 FORMAT = pyaudio.paInt16 # int16型 CHANNELS = 1 # 1;monoral 2;ステレオ- RATE = 22100 # 22.1kHz 44.1kHz RECORD_SECO...
#!/usr/bin/python import sys import lfc import commands import os # # test entry # directory = "/grid/dteam/my_test_dir/" name = "/grid/dteam/my_test_dir/my.test" replica1 = "sfn://my_se.in2p3.fr/hpss/in2p3.fr/group/sophie/tests_python/dir/my.test" replica2 = "srm://my_other_se.cern.ch/castor/cern.ch/grid/sophie/te...
while True: n=input if n%2==0: print'Congrats u entered an even no' break; else: continue
import cv2 cap = cv2.VideoCapture('video.mp4') #videos are read by frames we can give 0,1 to on front cam while(True): #capture frame by frame ret, frame = cap.read() #Display the resulting frame cv2.imshow('frame', frame) if cv2.waitKey(25) & 0xFF == ord('q'): #25 normal speed, extra code to ...
from apps import App, Response, TemplateResponse, JSONResponse from wsgiref.simple_server import make_server app = App() @app.route('^/$', 'GET') def hello(request): return Response('Hello World') @app.route('^/user/$', 'POST') def create_user(request): return Response('User created', status=201) @app.r...
""" This file is used in get_video.py The main function extracts a frame from a ts video """ import glob import cv2 def extract_frame_from_video_url(video_link): frame_is_read, frame = cv2.VideoCapture(video_link).read() if frame_is_read: return frame_is_read, frame else: pr...
#!/usr/bin/env python3 import rospy import math import time import py_trees import py_trees.console as console from std_msgs.msg import String from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry from tf import transformations from sensor_msgs.msg import LaserScan # Global pose variables global curr...
# -*- coding: utf-8 -*- import unittest import sys sys.path.append('../../../python') from testecono.sileg.testsileg import TestSileg def suite(): """ Gather all the tests from this module in a test suite. """ test_suite = unittest.TestSuite() test_suite.addTest(TestSileg('test_create_dat...
import sys import csv import json import optparse import collections parser = optparse.OptionParser() parser.add_option( '-i', '--input', dest='input_file', help='input file name', default='globe/data/locations.tsv', ) parser.add_option( '-c', '--coalesce_time_interval', type='int', dest='coalesce_time_interva...
def getN(): return int(input()) def getNM(): return map(int, input().split()) def getList(): return list(map(int, input().split())) def getArray(intn): return [int(input()) for i in range(intn)] def input(): return sys.stdin.readline().rstrip() def rand_N(ran1, ran2): return random.randint(ran1,...
#!/usr/bin/env python import logging, os, sys, unittest import Test_pycosat, Test_sniper_logic, Test_z3 ##################### # UNITTEST DRIVER # ##################### def unittest_driver() : print print "***********************************" print "* RUNNING TEST SUITE FOR SNIPER *" print "**************...
from django import forms from posts.models import Post, PostAttachment from posts.utility import POST_FILTER_CHOICES, POST_TEXT_PLACEHOLDER, MAX_FILES_COUNT, MAX_FILES_COUNT_ERROR class PostCreateForm(forms.Form): post_text = forms.CharField(widget=forms.Textarea( attrs={ 'class': 'form-control...
# -*- coding: utf-8 -*- """ @author: Stephanie McCumsey CIS 472 WINTER 2015 Naive Bayes ./nb <train> <test> <beta> <model> the input I use to test : "run nb.py spambase-train.csv spambase-test.csv 1 nb.model" """ from __future__ import division import sys import pandas as pd import numpy as np import pdb import m...
# 224. Basic Calculator class Solution: def calculate(self, s: 'str') -> 'int': inBrac = [] BracCount = 0 res = 0 left = [] ops_sign = 1 count , length = 0, len(s) for term in s: count += 1 if term == '': continue ...
import codecs import geeknoteConvertorLib import unittest from orgAnalyzer import OrgTable from enmlOutput import OrgTableHTMLWriter import utils class TestGeeknoteConvertor(unittest.TestCase): def test_replaceChar(self): source = "* this is a bulletpoint" target = "# this is a bulletpoint" ...
""" Created by Alex Wang on 2019-09-09 """ import numpy as np import sklearn from sklearn.metrics import average_precision_score, precision_recall_curve from eval_util import EvaluationMetrics def cal_accuracy(predict_all, tags_all): predict_all = np.concatenate(predict_all, axis=0) tags_all = np.concatenate(...
# -*- python -*- # Optional Assignment: Underscore # Your own custom Python Module! # Did you know that you can actually create your own custom python module similar # to the Underscore library in JavaScript? That may be hard to believe, as the things # you've learned might seem simple (again, we try to make it look ...
from helpers import SetUp #self.MEM = memory.Memory(self.R, self.postMemBuff, self.preMemBuff, opcodeStr, arg1, arg2, # arg3, dataval, address, self.numInstructions, self.cache, self.cycleList) class Memory: def __init__(self, R, postMemBuff, preMemBuff, opcodeStr, arg1, arg2, arg...
import Plugin class LogPlugin(Plugin.Plugin): registeredCommands="" priority=5 def init(self): self.file=open('logs/backend.log','a') def shutdown(self): self.file.close() def recvCommand(self, conElement): self.file.write("{0}\n".format(str(conElement))) self.file.flush() return 'continue'
#!/usr/bin/env python3 from ev3dev2.motor import MoveSteering, MoveTank, MediumMotor, LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D from ev3dev2.sensor.lego import TouchSensor, ColorSensor, GyroSensor from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4 import xml.etree.ElementTree as ET import threading ...
import colorsys import random import numpy as np from skimage.measure import label, regionprops, find_contours from matplotlib.patches import Polygon from matplotlib import patches, lines import matplotlib.pyplot as plt from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask def random_colors(N, ...
from torch.utils.data import Dataset from torchvision import transforms from skimage import io import os import json import numpy as np import torch from PIL import Image, ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True class CLEVR3(Dataset): def __init__(self, root, mode): # path = os.path.join(root, mo...
from django.apps import AppConfig class UnchockapiConfig(AppConfig): name = 'unchockapi'
#------------------------------------------------------------------------------ # Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN) # # Licensed under the EUPL, Version 1.1 only (the "Licence"). # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: ...
# Generated by Django 3.2 on 2021-07-12 17:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('film', '0018_auto_20210712_2012'), ] operations = [ migrations.RemoveField( model_name='film', name='actor', ), ...
#!/usr/bin/env python from __future__ import print_function import json import logging import os import shutil import subprocess import sys import time from shlex import split def configure_logging(): logging.basicConfig(level=logging.DEBUG) for handler in logging.root.handlers[:]: logging.root.remov...
from rubicon_ml.exceptions import RubiconException from rubicon_ml.sklearn.estimator_logger import EstimatorLogger from rubicon_ml.sklearn.utils import log_parameter_with_warning class FilterEstimatorLogger(EstimatorLogger): """The filter logger for sklearn estimators. Use this logger to either select or igno...
from concurrent import futures from concurrent.futures import ProcessPoolExecutor import os import sys import threading import time from . import slurm from .remote import INFILE_FMT, OUTFILE_FMT from .util import random_string, local_filename, call from . import pickling import logging import importlib import re impor...
# -*- coding: utf-8 -*- # 卷积神经网络训练mnist # 训练20000次后,再进行测试,测试精度可以达到99%。 import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x = tf.placeholder(tf.float32,[None,784]) y_actual = tf.placeholder(tf.float32,shape=[None,1...
# Generated by Django 3.1.7 on 2021-04-17 11:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20210416_0251'), ] operations = [ migrations.AddField( model_name='room', name='current_song', ...
# from evennia import create_object from typeclasses import rooms, exits, characters from features import radio_objects from evennia.utils import search radio = create_object(radio_objects.RadioObj, key="Radio", location=caller.location) radio.db.radio_switch = True channel = search.search_channel("Public")[0] channe...
#!/usr/bin/env python3 from ev3dev2.motor import MoveSteering, MoveTank, MediumMotor, LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D from ev3dev2.sensor.lego import TouchSensor, ColorSensor, GyroSensor from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4 from ev3dev2.button import Button import xml.etree.E...
from direct.showbase.ShowBase import ShowBase from panda3d.core import WindowProperties from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import OnscreenImage from direct.gui.DirectGui import * import ctypes class UserInterface: def __init__(self, fullscreen : bool = False): ...
# Tamanho de strings. # Faça um programa que leia 2 strings e informe o # conteúdo delas seguido do seu comprimento. # Informe também se as duas strings possuem o mesmo # comprimento e são iguais ou diferentes no conteúdo. if __name__ == '__main__': mensagem_1 = input('Digite uma frase: ').strip() ...
#!/usr/bin/python3 # -*- coding: UTF-8 -*-# import cgitb import cgi; cgitb.enable() # opcional para debug import logging import inject import re import psycopg2 import codecs import sys sys.path.insert(0, '../../python') sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) logging.basicConfig(level=logging.DE...
import numpy as np import math import matplotlib.pyplot as plt def main(): # We format the data matrix so that each row is the feature for one sample. # The number of rows is the number of data samples. # The number of columns is the dimension of one data sample. X = np.load('q1x.npy') N = X.shape...
def iTR(num): #dr={0:'',1:'I',2:'II',3:'III',4:'IV',5:'V',6:'VI',7:'VII',8:'VIII',9:'IX',10:'X',40:'XL',50:'L',90:'XC',100:'C',400:'CD',500:'D',900:'CM',1000:'M'} dr={0:'',1:'I',2:'II',3:'III',4:'IV',5:'V',6:'VI',7:'VII',8:'VIII',9:'IX'} q=num//1000#千位 b=(num-1000*q)//100#百位 s=(num-1000*q-100*b)//1...
import matplotlib.pyplot as plt import numpy as np import pandas as pd # Natoms = 1500 RF = [5,10,25,50,100,150,200,250,300,400,500,600] #path = r"C:\\Users\\Daniel White\\RF_data500000.csv" # 5 0's def Data(a): '''[0] is data, [1] is RF value''' df = pd.read_excel('RF_data{}00000.xlsx'.format(a)) return...
from pathlib import Path from typing import Any, Callable, Optional, Tuple import PIL.Image from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg from .vision import VisionDataset class Flowers102(VisionDataset): """`Oxford 102 Flower <https://www.robots.ox.ac.uk/~vgg/da...
################ ИМПОРТ МОДУЛЕЙ ################ import pygame from pygame.locals import * from pygame.math import Vector2 from math import sqrt, atan2, cos, sin from data import * from camera import * ################ НАСТРОЙКИ ОКНА ################ pygame.init() screen = pygame.display.set_mode((WIDTH,...
import heapq def sortAkSorted(iterable, k): largest = [] sortedArray = [] for value in iterable: heapq.heappush(largest, value) if len(largest) > k: sortedArray.append(heapq.heappop(largest)) if (len(largest) < k): return None for elm in largest: sortedA...
import numpy as np def gradient_descent(grad_f,x_init,learning_rate): grad_is_zero_flag = 1 counter = 0 while grad_is_zero_flag >= 1: grad_is_zero_flag = 0 grad_value = grad_f(x_init) for sub_value in grad_value: if sub_value >= 0.0001: grad_is_zero_flag += 1 if grad_is_zero_flag >= 1: x_init...