text
stringlengths
38
1.54M
""" Tools for validating input streams. """ import logging logger = logging.getLogger(__name__) class SequencingError(Exception): """ Error raised when a message contains an invalid sequence value. """ class InvalidPublisher(SequencingError): """ Error raised when a message is received from an...
import os def funcs(node): func = None # lambda scope if "_" + node.name in node.program[1]: func = node.program[1]["_" + node.name] # local scope elif node in node.program[1]: func = node.program[1][node] # external file in same folder else: for program in node...
import http.client conn = http.client.HTTPSConnection("quillbot.p.rapidapi.com") payload = "{\t\"text\":\"Researchers in the field of HCI both observe the ways in which humans interact with computers and design technologies that let humans interact with computers in novel ways. Humans interact with computers in many ...
from Bio import SeqIO from Bio.Align.Applications import ClustalwCommandline from Bio import AlignIO from Bio import Phylo TARGET = "Ebola.fas" DEST = "Ebola.aln" DND = "Ebola.dnd" """ command = ClustalwCommandline("clustalw", infile=TARGET) command() print(command) """ align = AlignIO.read(DEST, "clustal") pr...
from rest_framework.renderers import JSONRenderer from rest_framework.views import APIView class EdtechAPI(APIView): renderer_classes = (JSONRenderer,)
#!/usr/bin/env python import sys import crocoddyl import curves import eigenpy import example_robot_data import hppfcl import multicontact_api import numpy as np import pinocchio import tsid with open("/dist") as f: dist = f.read() if "20.04" in dist: print("*" * 74) print("{: <6s}".format(sys.version.split...
#!/usr/bin/env python import sys,string,os sys.path.insert(1, os.path.join(sys.path[0], '..')) ### import parent dir dependencies import numpy as np import numpy.polynomial.polynomial as poly import matplotlib import matplotlib.pyplot as plt def disp(hgvfile): lab={} me=[] std=[] for line in open(hgv...
from pybullet_envs.scene_abstract import SingleRobotEmptyScene from pybullet_envs.env_bases import MJCFBaseBulletEnv import numpy as np import pybullet import real_robots from .robot import Kuka import os from gym import spaces def DefaultRewardFunc(observation): return 0 class Goal: def __init__(self, init...
import json import requests import numpy as np import pandas as pd import inflect import matplotlib.pyplot as plt from datetime import datetime from scipy import stats # We use inflect to convert 1 into "1st", 2 into "2nd" etc integer_engine = inflect.engine() #######################################################...
from lexer import tokenize, Token, TokenInfo import expr as E # TOP ::= <EXPR> EOF # EXPR ::= <FACTOR> | <FACTOR> + <EXPR> # FACTOR ::= <ATOM> | <ATOM> * <FACTOR> # BINDING ::= let ID := <EXPR> in <EXPR> end # ATOM = NUM | ID | BINDING | ( <EXPR> ) class Parser: def __init__(self, tokens): self._tokens = ...
# The MIT License (MIT) # # Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the...
#!/usr/bin/python def data2(): with open('input') as input: buf = '' for c in iter(lambda: str(input.read(1)), b''): if c == ' ': yield int(buf) buf = '' else: buf += c with open('input') as input: line = input.readline()....
#!/usr/bin/env python # Name: 004-Largest_palindrome_product # Auther: cRamey # # Problem #################################################### # A palindromic number reads the same both ways. The largest palindrome made from the # product of two 2-digit numbers is 9009 = 91 x 99. # # Find the largest palind...
import time from threading import Thread def playNote(i): print 'playing notes' def detect(i): print "detecting punch" playNoteThread = Thread(target=playNote, args=(1,)) playNoteThread.start() detectPunchThread = Thread(target=detect, args=(2,)) detectPunchThread.start()
from setuptools import setup __version__ = "1.0" setup( name="synapse-s3-storage-provider", version=__version__, zip_safe=False, url="https://github.com/matrix-org/synapse-s3-storage-provider", py_modules=["s3_storage_provider"], scripts=["scripts/s3_media_upload"], install_requires=[ ...
def carga_lista(): li=[] for x in range(5): valor=int(input("Ingrese valor:")) li.append(valor) return li def retornar_mayormenor(li): ma=li[0] me=li[0] for x in range(1,len(li)): if li[x]>ma: ma=li[x] else: if li[x]<me: ...
bulx=dict() buly=dict() class bul(): def build(x,y): sz=len(bulx) bulx[sz]=x buly[sz]=y def bul_upd(): for j in range(len(bulx)): buly[j]=buly[j]+3
#!/usr/bin/python from Tkinter import * from tkFileDialog import askopenfilename import qrgenerator def openfile(): filename = askopenfilename(parent=root) text = entry.get() readabilityPriority = checkButtonValue.get() qrgenerator.create_qrcode(text, filename, readabilityPriority).show() root = Tk() root.wm_ti...
""" CoA Generation | Cannlytics Author: Keegan Skeate <keegan@cannlytics.com> Created: 2/6/2021 Updated: 7/15/2021 License: MIT LIcense <https://opensource.org/licenses/MIT> TODO: - Allow users to create CoA's with a myriad of templates! (.docx, .xlsx, etc.) - Import any docx template styed with Django format...
""" Testing that data in parsed instance's mongo_dict is properly categorized. """ from django.test import TestCase, Client from datetime import datetime class TestMongoData(TestCase): pass
import requests as r # xor 2 hex strings hexor = lambda a, b: hex(int(a, 16)^int(b,16))[2:] # divide block into 3 split_block = lambda s: [s[i:i+32] for i in range(0, len(s), 32)] # decrypt the ciphertext decrypt = lambda x: r.get('http://aes.cryptohack.org/ecbcbcwtf/decrypt/{ctxt}/'.format(ctxt=x)).json()['plaintext']...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication, QMainWindow from modbusMaster import init_modbus, InitGlobalParam from ui_py.ui_main_window import Main_Form if __name__ == '__main__': app = QApplication(sys.argv) app.setApplicat...
# Generated by Django 3.0.4 on 2020-08-13 20:10 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('quiz', '0002_auto_20200813_0637'), ] operations = [ migrations.AlterField( ...
from ..parser.Parser import Parser, ParserUtils from ..schema.PgFunction import PgFunction, Argument class CommentParser(object): @staticmethod def parse(database, statement): parser = Parser(statement) parser.expect("COMMENT", "ON") if parser.expect_optional("TABLE"): Com...
import os import torch from torch.utils.data import Dataset from hana.rindou.poser.dataset.three_step_data import load_three_step_data_tsv from hana.rindou.util import extract_pytorch_image_from_filelike class MorphRegressionFromThreeStepDataDataset(Dataset): def __init__(self, data_tsv_file_name: str, ...
import requests import threading import random def req(r, f): url = "http://localhost:9000/" + f if r == "GET": x = requests.get(url) elif r == "POST": x = requests.post(url) elif r == "HEAD": x = requests.head(url) #print("\n" + str(i)+" : " + str(x) + " ------> " + r + " /" + f + "/" + str(x.headers) + "...
# -*- coding: utf-8 -*- """ Created on Fri Jul 31 09:44:37 2020 @author: archi """ import scipy.io.wavfile as wav import pandas as pd import os import pyaudio import wave os.chdir('E:\\Sem 5\\PROJECTS\\Digital Signal Processing Project') def lengthfinder(file_path): (source_rate, source_sig) =...
""" stanCode Breakout Project Adapted from Eric Roberts's Breakout by Sonja Johnson-Yu, Kylie Jue, Nick Bowman, and Jerry Liao YOUR DESCRIPTION HERE """ from campy.graphics.gwindow import GWindow from campy.graphics.gobjects import GOval, GRect, GLabel from campy.gui.events.mouse import onmouseclicked, onmousemoved i...
txt1 = raw_input() txt2 = raw_input() start = 0 store = {} for j in xrange(len(txt2)): tmp = '' for i in xrange(1,len(txt2)+1): if txt2[j:i] in txt1: tmp = txt2[j:i] if len(tmp) > 0: store[tmp] = len(tmp) val = store.values() val.sort() if len(val) == 0: print 'Error!' ...
import pygame from pygame.draw import * pygame.init() FPS = 30 screen = pygame.display.set_mode((400, 600)) # colors white = (255, 255, 255) black = (0, 0, 0) eye_color = (0, 50, 255) corn_color = (106, 90, 205) # colors for upper hair blue1 = (0, 191, 255) blue2 = (30, 144, 235) blue3 = (0, 0, 128) blue4 = (138, ...
import json # javascript object notation data1 = '{"Name": "Lorem Ipsum", "Address": "A-15, Dolor Sit Amet, Adipscing, Voluptatem, Gonzara"}' # creating a json string data_python = json.loads(data1) # parsing over the data to convert json string to python object (dictionary) pr...
import math # Get the period of sinusoidal function. def get_sinusoidal_period(B): x = (2 * math.pi) B = abs(b) return x / B # Given an A return if function is stretched or compressed. def get_function_state(A): # TODO: ensure A is a number. A = abs(A) if abs(A) > 1: print('Function i...
# Author: Can Metan # GPL v3 License # ____________________________________________________________________________ # Zero padding can be used to increase the fft resolution. Initial signal is # 256 samples long. Second one was padded with 256 zeros = 512 samples. # The third signal is padded with 512 additional s...
# Databricks notebook source dbutils.widgets.text("DatabaseName", "default") # COMMAND ---------- from pyspark.sql.types import * from pyspark.sql.functions import * # COMMAND ---------- spark.sql("create database if not exists {}".format(dbutils.widgets.get("DatabaseName"))) # COMMAND ---------- spark.sql("USE {...
import cmd from pitcoin_modules.blockchain import Blockchain class MinerCLI(cmd.Cmd): intro = 'Welcome to pitcoin_modules miner-cli. Type help or ? to list commands.\n' prompt = '\n(pitcoin-miner-cli) ' blockchain = Blockchain() i = 0 def do_mine(self, arg): while True: result...
import unittest from pandas import DataFrame, Series from EvaluationEngine import Expression class TestObj(): def __init__(self, eersteregel = None,tweederegel = None, alleregels = None, var1 = None, var2 = None): self.eersteregel = eersteregel ...
import signal import shutil import sys if len(sys.argv) <= 1: exit(1) signal.signal(signal.SIGINT, lambda sig, frame: exit(0)) try: columns, lines = shutil.get_terminal_size((80, 20)) lines -= 3 with open(sys.argv[1], 'r') as fp: iterator = zip(range(lines), iter(fp.readlines())) it =...
# Copyright (c) Alibaba, Inc. and its affiliates. from typing import Optional import torch import torch.nn as nn def expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): r""" Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, ...
# wujian@2020 import os import random import argparse from .data_handler import ScpReader from .opts import str2tuple class UniformSampler(object): """ A uniform sampler class """ def __init__(self, tuple_or_str): if isinstance(tuple_or_str, (list, tuple)): self.min, self.max = t...
# Author:Lithlu import re print(re.search("\w+","1245@asd")) # <_sre.SRE_Match object; span=(0, 4), match='1245'> # \w 匹配非特殊字符 如匹配到 a-z A-Z 或者是数字 # \W 是只匹配特殊字符 # \s 匹配空白字符 如 \t \n \r # 分组匹配 a = re.search("(?P<id>[0-9]+)(?P<name>[a-zA-Z]+)","123456lithlu").groupdict() print(a) b = re.search("(?P<province>[0-9](4))...
import numpy as np import time #Elastic Net regularization algorithm # Function import import featureCM import prop import folding import fitElasticNet fOut = open("CM-EN.txt", "w") # 1. CM vector parsing CM_Path = "SupplementaryMaterials/CM" time0 = time.time() CM_vec = featureCM.parse_feature_CM(CM_Path) # print...
import string template = string.Template(""" [COLLECTOR] server_list=$__contrail_collectors__ """)
# Password-Generator-using-python user can generate the password as much as possible. print("hello world")
number = eval(input()) letter = True for n in range(len(number)): if number[n] == 7 and letter == True: print(n) letter = False if letter: print("Not found")
def protect(): #this function has a misleading name correct = False password = 'password' guess = '' loop = -1 while guess != password: guess = raw_input("Password: ") loop = loop + 1 print "You entered an incorrect password " + str(loop) + " times."
import scrapy from scrapy.loader import ItemLoader from itemloaders.processors import TakeFirst from datetime import datetime from northviewbank.items import Article import requests import json import re class northviewbankSpider(scrapy.Spider): name = 'northviewbank' start_urls = ['https://northviewbank.myho...
from telegram.ext import Updater, CommandHandler def start(update, context): update.message.reply_text('Hola, humano!')
from django.contrib import admin from .models import * # Register your models here. class CategoryAdmin (admin.ModelAdmin): list_display = ["name"] class Meta: model = Category # Register your models here. admin.site.register(Category,CategoryAdmin) class PostsAdmin (admin.ModelAdmin): list_display = ['...
#-*- coding: utf-8 -*- #!/usr/bin/env python3 #ServiceRoles #By Bertrick import logging import mysql.connector from mysql.connector import Error class Init: #save new role def create(self, role, connection, cursor): sql_insert_query = """ INSERT INTO roles (isbn_13, name, description, c...
#Client RPC from xmlrpc.client import ServerProxy # RPC do Python usa HTTP como protocolo de transporte cliente = ServerProxy('http://localhost:20064', allow_none=True) # criar uma instância cliente localhost e na porta do servidor while True: nome = input("Digite o nome para receber o número \n") cliente....
from datetime import datetime import os timetable = open("timetable.txt", 'r') datelist = timetable.readlines() for i in range(len(datelist)): datelist[i] = datelist[i].rstrip('\n') print(datelist) Found = True; while Found == True: current = datetime.now() currentStr = current.strftime("%H %M") for i in range(...
import controllers.controller as controller class Members(controller.Controller): async def process(self, params, message, client): data = "" server = client.get_server(message.server.id) for member in server.members: data += "`" + str(member.nick) + "`\n" await clien...
"""Common configure functions for lldp""" # Python import logging #Unicon from unicon.core.errors import SubCommandFailure log = logging.getLogger(__name__) def configure_lldp(device): """ Enables lldp on target device Args: device ('obj'): Device object Returns: ...
#Import libs #sci kit learn for transform docs in TF IDF vectors. from sklearn.feature_extraction.text import TfidfVectorizer #sci kit learn for cosine_similarities from sklearn.metrics.pairwise import linear_kernel import datetime import os import glob import sys #documents: List, contains the content o...
from __future__ import absolute_import from datetime import datetime, timedelta import feedparser from celery import shared_task from feeds.models import Feed, Entry @shared_task def fetch_feeds(): feeds = Feed.objects.all() for feed in feeds: rssfeed = feedparser.parse(feed.url) feed.save()...
n,m=map(int,input().split()) s=0 x=max(n,m) for i in range(1,x+1): if n%i==0 and m%i==0: s=i print(s)
#!/usr/bin/python # -*- coding: UTF-8 -*- import pymysql import datetime,time,re # start date for loading the data from wind INITDATE = '2015-01-01' # INITDATE = '1990-01-01' class DBConnect: def __init__(self, server, user, psd, database): self.server = server self.user = user self.psd = psd self.databas...
def unique(tup1: tuple, tup2: tuple, tup3: tuple) -> tuple: res = [] for i in tup1: if i not in tup2 and i not in tup2: res.append(i) for j in tup2: if j not in tup1 and j not in tup3: res.append(j) for k in tup3: if k not in tu...
from collections import OrderedDict from .exceptions import * VALID_OPERATORS_COMPARISON = '== != <= >= < >' VALID_OPERATORS_ASSIGNMENT = '= += -= *= /=' class Choice(): def __init__(self, label, next_snippet): self.label = label self.next_snippet = next_snippet self.from_snip = None ...
from django.shortcuts import render, redirect from django.core.urlresolvers import reverse # 反向解析 from django.core.cache import cache # 导入缓存 from django.core.paginator import Paginator # 导入数据分页 from django.views.generic import View # 类视图,而不是函数视图 from goods.models import GoodsType, GoodsSKU, IndexGoodsBanner, IndexProm...
from apps.extention.settings import config if config.SERVER_ENV != 'dev': from gevent import monkey monkey.patch_all() else: pass from apps.extention.views.cidata import cidata from apps.extention.views.tool import tool from library.api.tFlask import tflask def create_app(): app = tflask(config) ...
class Alumno: __max_inasistencias = 10 __total_clases = 50 @classmethod def getMax(cls): return cls.__max_inasistencias @classmethod def getTotal(cls): return cls.__total_clases @classmethod def setMax(cls, max_i): cls.__max_inasistencias = max_i d...
print("包含中文的str") print(ord('A')) #65 print(ord("中")) # 20013 print(chr(66)) # B print(chr(25991)) # 文 # 如果知道字符的整数编码,还可以用十六进制这么写str print('\u4e2d\u6587')
# -*- coding=utf-8 import xml.dom.minidom class CosException(Exception): def __init__(self, message): self._message = message def __str__(self): return str(self._message) def digest_xml(data): msg = dict() try: tree = xml.dom.minidom.parseString(data) root = tree.do...
#!/usr/bin/python3 """ module: class BaseModel creates new instance objects """ import uuid from datetime import datetime import models class BaseModel(): """ BaseClass model """ def __init__(self, *args, **kwargs): """ initializes all the instances with mapped with the attr...
#numberlines.py在文件中添加行号 import fileinput for line in fileinput.input(inplace=True): line=line.rstrip() num=fileinput.lineno() print('{:<50} # {:2d}'.format(line,num))
# Generated by Django 3.0.2 on 2020-02-16 15:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authentication', '0006_auto_20200121_2026'), ('comments', '0001_initial'), ] operations = [ migrati...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-17 03:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trips', '0002_auto_20170317_0306'), ] operations = [ migrations.AlterField(...
from django.forms import ModelForm from .models import Appointment from accounts.models import District, Hospitals, Departments, Doctor from django.http import request from accounts.models import User class AppointmentForm(ModelForm): class Meta: model = Appointment fields = ("user","Date", "provin...
from lxml import etree import shutil NS = {'rdf':"http://www.w3.org/1999/02/22-rdf-syntax-ns#", 'xsd':"http://www.w3.org/2001/XMLSchema#", 'rdfs':"http://www.w3.org/2000/01/rdf-schema#", 'dcterms':"http://purl.org/dc/terms/", 'owl':"http://www.w3.org/2002/07/owl#", 'crm':"http://www.cidoc-crm.org/cidoc-crm/", '...
#!/usr/bin/python3 from math import ceil def main(): number_of_solutions = dict((x,0) for x in range(1000)) # p must always be even. you can prove this by taking a+b+c=p and a^2+b^2=c^2 # and plugging in odd/even values of a and b. for p in range(2, 1000, 2): # the maximum potential c is half...
try: import cPickle as pickle except ImportError: import pickle import json try: import msgpack except ImportError: pass try: import yaml except ImportError: pass from django.utils.encoding import force_bytes, force_str class BaseSerializer(object): def __init__(self, **kwargs): ...
#While loops x = [10, 12, 15, 0, 10, 5] mean = sum(x)/len(x) print(mean) variance = [] for num in x: val = num - mean val = round(val, 2) variance.append(val) print(variance) variance2 = [] index = 0 while index < len(x): val = x[index] - mean variance2.append(val) index += 1 print(variance2) ...
''' MinneapolisFact Twitter Bot This is a short script that will randomly grab a line from a textfile and post it to Twitter. Feel free to use this for your own Twitter bot. To use this, hook it up to a cronjob. Since this outputs what it's going to tweet, pipe stdout to a log file. You will need to have a file nam...
#program to show how twitter augment works. We are going to read everything from this url. Oauth sends the signature back. Not actual secret stuff. import urllib from twurl import augment print '* Calling Twitter....' url = augment('https://api.twitter.com/1.1/statuses/user_timeline.json', {'screen_name': 'drchuc...
import random import networkx as nx import numpy as np import pylab from shapely.geometry import MultiPoint, Point def dist(p1, p2): """ Accepts 2 Vertices from the Vertex class and returns the distance between them :param p1: --> Tuple of coordinates :param p2: --> Tuple of coordinates """ ...
from pVIPRAM_inputBuilderClass import * import sys import random def GenerateInputsLoad(filename): inputP = inputBuilder("root/" + filename + ".root") inputP.initializeLoadPhase() N = int(sys.argv[2]) mult = (int(sys.argv[3])/10)+1 #offset = 0 nInfoFile = open("LocationStressInfoFile.txt", "a") #if N != 0: #o...
import pandas as pd import pathlib import csv import numpy as np import re import os from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import SGDClassifier from sklearn.feature_extraction.text import TfidfVectorizer train_path = "../resource/lib/publicdata/aclImdb/train/" # use ter...
#!/usr/bin/env python import argparse import logging import matplotlib.pyplot as plt import rosbag_pandas def build_parser(): """ Builds the parser for reading the command line arguments :return: Argument parser """ parser = argparse.ArgumentParser(description='Bagfile key to graph') parser....
from __future__ import absolute_import import pytz import six from django.core.urlresolvers import reverse from sentry.utils.compat.mock import patch from sentry.discover.models import KeyTransaction, MAX_KEY_TRANSACTIONS from sentry.utils.samples import load_data from sentry.testutils import APITestCase, SnubaTestC...
import time import threading import logging import tkinter as tk # Python 3.x import tkinter.scrolledtext as ScrolledText # taken from https://gist.github.com/bitsgalore/901d0abe4b874b483df3ddc4168754aa class TextHandler(logging.Handler): # This class allows you to log to a Tkinter Text or ScrolledText widget ...
from flask_restful import abort, Resource from data import db_session from flask import jsonify, request, url_for from models.users import * from rest_api.parsers import * from tests import abort_if_user_not_found, abort_if_user_email_equal_to_new_user_email class UsersResource(Resource): # ресурс для одного ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 18-1-24 下午6:39 # @Author : jianguo@zhugefang.com # @Desc : 小区数据层 from dao.BaseDao.BaseMongo import BaseMongo from apps.zhuge_borough.model.Borough_month_price import Borough_month_price from cache.LocalCache import LocalCache from cache.Pcache import Pcache...
from django.db import models # Create your models here. class Url(models.Model): url_id = models.AutoField(primary_key=True) link = models.CharField(max_length=100000000) short_link = models.CharField(max_length=10000)
"""LISTA1_Q15 Escreva uma função que recebe por parâmetro um valor inteiro e positivo N e retorna o valor de S. S = 2/4 + 5/5 + 10/6 + 17/7 + 26/8 + ... +(t^2+1)/(t+3)""" def formula(a): aux1 = 2 aux2 = 4.0 for i in range(aux1 - 1, a): aux1 = (i ** 2) + 1 aux2 = i + 3 print(f'{aux1...
#! /usr/bin/env python import argparse import sys import re import tree # class ParseError(Exception): # ''' print out context and point of error in context ''' # def __init__(self, info, ctxt="", point=-1): # Exception.__init__(self, info) # self.info=info # self.ctxt=ctxt # self.point=point # ...
import tensorflow as tf import tensorflow.keras.backend as K from tensorflow import keras import numpy as np from matplotlib import pyplot as plt import pickle class passwordLSTM: def __init__(self): """ Initializes model and tokenizer """ self._model = None self._tokenizer = keras.preproce...
from Database.mapAndPathData import MapData from InterfaceSubSystem.Window_design_management.window import WindowDesign from PyQt5.QtWidgets import * # 현재 시스템에 저장중인 맵 데이터를 보여주는 창을 띄워주는 클래스 class ShowMapData(WindowDesign): def __init__(self): super().__init__() self.mapSize=MapData.getMapSize() ...
# -*- coding:utf-8 -*- import numpy as np import pandas as pd import json from collections import Counter from matplotlib import pylab from matplotlib import pyplot as plt path = r"C:\pycharm\pydata-book-2nd-edition\datasets\babynames\yob1880.txt" names = ['name', 'gender', 'births'] baby_names1...
from helpers import util, visualize from script_cumulative_separation import get_feats import numpy as np import os import cooc from . import * from Kunz_Selector import Kunz_Selector from Base_Selector import Base_Selector from Cooc_Selector import Cooc_Selector from Collapsed_Selector import Collapsed_Selector
S = [list(input()) for i in range(3)] member = ['a', 'b', 'c'] turn = 0 while S[turn] != []: turn = member.index(S[turn].pop(0)) print(member[turn].upper())
import re from SpecCache import * class SpecL3Cache(SpecCache): "A class to aid in parsing spec L3 caches, which can be in a number of forms" def __init__(self, string): self.__size = "NA" SpecCache.__init__(self, string) for match in self.matches("(\d+)\s*([kmg]b)\s*(i\s*\+\...
#!/usr/bin/env python3 import sys import csv class Args: def __init__(self): l = sys.argv[1:] self.c = l[l.index('-c')+1] self.d = l[l.index('-d')+1] self.o = l[l.index('-o')+1] class Userdata(object): def __init__(self): self.userdata = self._read_users_data() ...
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui import random width=900 height=500 pos=[width/2,height/2] vel=[0,0] ball_r=7 color="blue" collist=["blue","white","green","red","yellow"] def draw(canvas): global vel, pos, color canvas.draw_circle(pos, ball_r, 1, color,color) pos[0]=pos[0]+vel[0] pos[1]=p...
from keras.models import Model from keras.layers import Input, Conv2D, MaxPooling2D, concatenate, BatchNormalization, UpSampling2D, ConvLSTM2D, \ Conv2DTranspose from keras.layers.wrappers import TimeDistributed, Bidirectional from keras.layers.advanced_activations import LeakyReLU from keras.optimizers import SGD ...
import tkinter.ttk as ttk from tkinter.font import Font from tkinter import messagebox from tkinter import * import sudoku_resevanje as sudoku_resevanje root = Tk() style = ttk.Style() style.theme_use('clam') root.option_add("*Font", ("comic sans MS",9)) root.title('Sudoku') root.geometry('255x310') okvir0 = Frame(r...
import os, re def find_files(folder, regex, remove_empty = False): """ Find all files matching the [regex] pattern in [folder] folder : string folder to search (not recursive) regex : string (NOT regex object) pattern to match """ files = os.listd...
import re def test_phones_on_home_page(app): contact_from_home_page=app.contact.get_contact_list()[0] contact_from_edit_page=app.contact.get_contact_info_from_edit_page(0) assert contact_from_home_page.all_phones_from_home_page==merge_phone_like_on_home_page(contact_from_edit_page) def test_phones_on_view...
while True: try: hora, minuto = map(int, input().split()) hora = str(hora // 30) minuto = str(minuto // 6) if len(hora) == 1: hora = f'0{hora}' if len(minuto) == 1: minuto = f'0{minuto}' print(f'{hora}:{minuto}') except EO...
from django.urls import path from blogs.views import index, root, new, show, edit, create, destroy urlpatterns = [ path('blogs/<int:numero>/delete/', destroy), path('blogs/create/', create), path('', root), path('blogs/', index), path('blogs/<int:numero>/edit/', edit), path('blogs/<int:numero>...