text
stringlengths
38
1.54M
from django.shortcuts import render, redirect from django.http import HttpResponse, request, HttpResponseRedirect, HttpResponseForbidden from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.views.generic.base import View from django.contrib.auth.models import User from django.contrib.a...
from daq import daqDevice from daqh import DgainX1, DafBipolar,DafUnsigned dev = daqDevice('DaqBoard2K0') chan = 0 gain = DgainX1 flags = DafBipolar|DafUnsigned read = dev.AdcRd(chan, gain, flags) read = (20.0/2**16)*read -10 print read dev.Close()
#!/usr/bin/python import paramiko, time, sys class SetFirewall: def __init__(self, brand, ssh_ip, ssh_port, ssh_username, ssh_password): self.brand = brand self.ssh_ip = ssh_ip self.ssh_port = int(ssh_port) self.ssh_username = ssh_username self.ssh_password = ssh_password ...
from tkinter import * from tkinter import ttk root = Tk() root.title("Learn To Code") root.iconbitmap('favicon.ico') root.geometry("500x500") my_notebook = ttk.Notebook(root) my_notebook.pack() def hide(): my_notebook.hide(1) def show(): my_notebook.add(my_frame2, text="Red Tab") def select(): my_noteb...
# Copyright 2016 Brocade Communications 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.org/licenses/LICENSE-2.0 # Unless required by applicable law or ...
''' create binary tree: https://www.youtube.com/watch?v=XV1ADVV6FbQ&list=PL-Jc9J83PIiHYxUk8dSu2_G7MR1PaGXN4&index=3 display binary tree: https://www.youtube.com/watch?v=sYU6AnSJyjo&list=PL-Jc9J83PIiHYxUk8dSu2_G7MR1PaGXN4&index=4 ''' class Node: def __init__(self, data, left, right): self.data = data ...
# -*- coding: utf-8 -*- """ Created on Fri Mar 27 18:07:30 2020 @author: willi """ #Test file for generalized SSA #import rSNAPsim as rss import numpy as np import time import matplotlib.pyplot as plt import ssa_translation_generic_lowmem def generate_additional_ks(enters,pauses,jumps,stops,L): def frame_...
import sys from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QSpinBox from design import Ui_MainWindow class MyWidget(QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) self.pushButton.clicked.connect(self.run) def run(self): s...
import csv import os gameName = [] with open("./1000.csv", "r", newline='',encoding="gb18030") as csvfile: #读取csv文件,返回的是迭代类型 read = csv.reader(csvfile) for inx, item in enumerate(read): print('item', item) print('inx', inx) if item[0] and item[0] != '产品名称': # obj...
#!/usr/bin/python # # $Id: kfsshell.py 24 2007-09-27 07:17:06Z sriramsrao $ # # Copyright 2007 Kosmix Corp. # # This file is part of Kosmos File System (KFS). # # 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...
from django.db import models from django.db import transaction from .settings import THUNDERING_FRAME_WIDTH import time class ImportProcessManager(models.Manager): """ Manager used to create import process and handling thundering herd problem. """ def create_process(self): """ Method ...
#!/usr/bin/python import unittest from parquet.schema import SchemaParser, SchemaHelper, RecordAssembler, RecordDissector d1 = { 'DocId': 10, 'Links': { 'Forward': [20, 40, 60] }, 'Name': [ {'Language':[ {'Code': 'en-us', 'Country': 'us'}, {"Code": "en"} ], 'Url': 'http://A'}, {'Url': 'ht...
from flask import Flask, session from .config import Config from datetime import timedelta from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app, db) login = LoginM...
from init_database import * def user_id_exist(user_id): cursor = session.query(User).filter(User.user_id == user_id).first() if (cursor is None): return False else: return True # 查询书店是否有某类书 def book_id_exist(store_id, book_id): cursor = session.query(Store_detail).filter(Store_detail...
""" Module proving a standard way to carry various options """ import typing try: from . import constants as _constants except ImportError: import constants as _constants class Namespace(dict): """ Subclassed dict that allows accessing its items like attributes """ def __getattr__(self, key...
#-------INCIANDO--------- #Importa e incia as biblietecas import pygame import random from config import * from assets import * from sprites import * def battle_screen(window): # Variveis de ajuste de velocidade clock = pygame.time.Clock() assets = load_assets() all_sprites = pygame.sprite.Group() ...
# encoding: utf-8 from __future__ import print_function import sys import datetime def write(message): time = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") print('[{}] {}'.format(time, message)) def debug(message): time = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") print('[{}] [DE...
class BaseMatrix(object): def __init__(self, type1, rows, columns): self.n = rows self.m = columns self.t = type1 self.data = [] types = [int, complex, float] if type1 in types: for a in range(columns): row = [] ...
#%% 09 - Numeros impares 1 a 50 """ Faça um programa que imprima na tela apenas os números ímpares entre 1 e 50. """ numero = 50 for i in range(1, numero+1, 2): print(i)
# -*- coding: utf-8 -*- # code for console Encoding difference. Dont' mind on it import imp import sys from popbill import EasyFinBankService, PopbillException import testValue imp.reload(sys) try: sys.setdefaultencoding("UTF8") except Exception as E: pass easyFinBankService = EasyFinBankService(testValue.L...
# Copyright (C) 2017 Leandro Lisboa Penz <lpenz@lpenz.org> # This file is subject to the terms and conditions defined in # file 'LICENSE', which is part of this source code package. """Common functions used by tests""" import tempfile import omnilint import omnilint.reporters as reporters def checkthis(checkername,...
async def test1(x): await x def test2(): return 3 import inspect def test3(): yield 1 print(inspect.iscoroutine(test1(1)))
import geargrip import cv2 import numpy as np from networktables import NetworkTable cam = cv2.VideoCapture("http://10.14.3.24/mjpg/video/mjpg") if cam.isOpened(): print("yes") ret, frame = cam.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cam.release()
# import Autoencoder import operator import pickle import itertools import math import numpy import logging logger = logging.getLogger(__name__) from sklearn.feature_extraction.text import CountVectorizer from .DBN import train_DBN from ..Utils import preprocess as pr class SAmodel(object): ##################...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html #import json import mysql.connector from scrapy import item class ShengouPipeline(object): # 仅仅输出到控制台 #...
#!/usr/bin/env python3 import os.path as osp import argparse from baselines.common.cmd_util import mujoco_arg_parser from baselines import bench, logger def train(env_id, num_timesteps, seed, network, r_ex_coef, r_in_coef, lr, reward_freq, begin_iter, model_train_num, K_model_num, regularize, selection_type)...
from movements.forms import MovementsForm from sqlite3.dbapi2 import connect from flask_wtf import form from movements import app from flask import render_template, request, redirect, url_for import csv import sqlite3 DBFILE = app.config['DBFILE'] def DBconsulta(query, params=()): conn = sqlite3.connect(DBFILE) ...
class Constants(object): CONFIG_FILE_NAME = 'config.ini' DEFAULT_CONFIG_FILE_NAME = 'default_config.ini' CONFIG_SECTION_GLOBAL = 'Global' CONFIG_OPTION_ACTIVE_USER = 'ActiveUser' CONFIG_OPTION_ACTIVE_MODE = 'ActiveMode' CONFIG_USERNAME_PREFIX = 'User_' CONFIG_OPTION_PASSWORD_PREFIX = 'Passwo...
# by Kush (more added in debugging by Stuart) from main import * import pickle def askForPeriod(periodNum): print("What class is your period "+periodNum) period = input() return period def setup(adminYN): userInfo = pickle.load(open('userinfo.txt', 'rb')) if adminYN == 'yes' or adminYN == '...
class Solution(object): prev = None def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return self.prev = root self.flatten(root.left) tmp = ro...
# -*- coding: utf-8 -*- """ Created on Wed Aug 28 14:28:36 2019 @author: ZhuangChi """ """ 给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线, 使得它们与 x 轴共同构成的容器可以容纳最多的水。 说明:你不能倾斜容器,且 n 的值至少为 2。 示例: 输入: [1,8,6,2,5,4,8,3,7] 输出: 49 """ height = [1,8,...
from functools import reduce n=int(input("n=")) a=[int(input("a="))for i in range(n)] positive_el=filter(lambda x: x//3,a) sum=reduce((lambda x,sum: x+sum ),positive_el) print(sum)
#!/usr/bin/python #-*- encoding:utf-8 -*- import jieba def splitSentence(inputFile,outputFile): fin=open(inputFile,'r') fout=open(outputFile,'w') for eachLine in fin: line=eachLine.strip().decode('utf-8','ignore') worldList=list(jieba.cut(line)) outStr='' for word in world...
# -*- coding: utf-8 -*- ### # Copyright (c) 2010 by Elián Hanisch <lambdae2@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) an...
import random, os, sys import numpy as np from tensorflow.keras import backend as K from tensorflow.keras.models import * from tensorflow.keras.layers import * from tensorflow.keras.callbacks import * from tensorflow.keras.initializers import * import tensorflow as tf from tensorflow.python.keras.layers import Layer t...
from abc import ABC, abstractmethod from typing import List, Tuple import copy from moviepy.editor import VideoClip,CompositeVideoClip import mugen.utility as util import mugen.video.sizing as v_sizing import mugen.video.effects as v_effects from mugen.mixins.Filterable import Filterable from mugen.mixins.Persistable...
# -*- coding: utf-8 -*- #!/usr/bin/python import sys from PyQt4 import QtGui, QtCore from datetime import datetime, date class Window(QtGui.QMainWindow): def __init__(self): super (Window,self).__init__() self.setGeometry(50,50,500,500) self.setWindowTitle(" ¡Viva Mexico!") self.setWindowIcon(QtGui.QIcon('ba...
s, t = map(str,input().split()) num_s, num_t = map(int,input().split()) del_target = input() data = {s:num_s,t:num_t} data[del_target] = data[del_target]-1 print(data[s],data[t])
#!/usr/bin/env python2 from decimal import Decimal from enum import Enum import random SAPLING_ACTIVATION_HEIGHT = 400 SIMULATION_END_HEIGHT = 600 ZATOSHIS_PER_ZEC = 100000000 ZATOSHIS_PER_BLOCK = 10 * ZATOSHIS_PER_ZEC MIN_COINBASE_DISTRIBUTION = ZATOSHIS_PER_ZEC // 20 SHIELDED_PROBABILITY = 0.2 # Assume 20% of co...
def sum(*MyData): sum = 0 for data in MyData: sum += data return sum def average(*MyData): sum = 0 i = 0 for data in MyData: sum += data i += 1 average = sum/i return average def maks(*MyData): #maks = 0 maks = -(float("inf")) ...
# -*- coding: utf-8 -*- #------------------------------------------------- # File Name: ExportUserDict # Author : fengge # date: 2019/3/27 # Description : 将词和原始的字典合并成新的词典 #------------------------------------------------- from config import data_dir import os def ExporUserDict(words,infile...
#!/usr/bin/env python3 import struct from scapy.packet import Packet, Raw, RawVal from scapy.compat import raw from scapy.fields import IntField, XIntField, StrFixedLenField, Field class PacketFieldOffset(Packet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields_...
import logging import json from itertools import chain import pandas as pd from wash import Washer class AggregateBar(Washer): """ 1. 聚合各种周期的数据,并存库 2. 基于清洗完成后的 1min bar 来聚合 3. 一般情况下这个 bar 聚合是跟 washer 一起运行的。就不需要再向 slavem 汇报了 """ def run(self): """ :return: """ ...
# for loop # users=[ # ['ram','sita','gita','hari'], # ['jonish','gauri','alisha','anuj'], # ['q','w','e','r'] # ] # for user in users: # for name in user: # print(name) # while Loop # i=1 # while i<=50: # if i%2==0: # print(i) # i+=1 # while loop result num=int(input("E...
#Sako Haji #04/21/2019 avail_edges = {"0": ["1", "2", "3"],"1": ["4", "5"], "2": ["5"], "3": ["6"], "4": ["7"], "5": ["7"], "6": ["7"], "7": []} graph = {} def flow(): counter = 0 graph = avail_edges pointer = "0" while BFS(pointer, graph): next_child = graph[...
import torch import torch.nn as nn import torch.nn.functional as F class CoreNetwork(nn.Module): def __init__(self, glimpse_hid_dim, location_hid_dim, recurrent_hid_dim): super().__init__() self.i2h = nn.Linear(glimpse_hid_dim+location_hid_dim, recurrent_hid_dim) self.h2h = nn.Linear(recur...
''' lesson 2 - building a movie website build a site that hosts movie trailers and their info steps: 1. we need: title synopsis release date ratings this means we need a template for this data, ex: avatar.show_info(), toyStory.show_trailer() but we dont want to use s...
import os import sys from radon.complexity import cc_rank, cc_visit from radon.visitors import Function, Class # Get a list of all python files in the project print('Compiling list of modules...') MODULES = [] for i in os.walk(os.path.abspath(os.path.join(os.path.abspath(__file__), '..'))): path, folders, files = ...
one={'O':1,'N':1,'E':1} two={"T":1,"W":1,"O":1} three={"T":1,"H":1,"R":1,"E":2} four={"F":1,"O":1,"U":1,"R":1} five={"F":1,"I":1,"V":1,"E":1} six={"S":1,"I":1,"X":1} seven={"S":1,"E":2,"V":1,"N":1} eight={"E":1,"I":1,"G":1,"H":1,"T":1} nine={"N":2,"I":1,"E":1} zero={"Z":1,"E":1,"R":1,"O":1} lst=[zero,one,two,...
import tkinter as tk from tkinter.messagebox import showwarning import subprocess root = tk.Tk() root.geometry("600x500") label = tk.Label(root, text="Example of xterm embedded in frame") label.pack(fill=tk.X) xterm_frame = tk.Frame(root) xterm_frame.pack(fill=tk.BOTH, expand=True) xterm_frame_id = xterm_frame.winf...
#if __name__ == '__main__': # print('Hello Heimid!') import fritzconnection as fc #print(fc.get_version()) connection = fc.FritzConnection(password='butt2740') info = connection.call_action('WANIPConnection', 'GetInfo') Uptime = info['NewUptime'] #print(Uptime) import fritzhosts as fh #print(fh.get_ve...
def time_for_playing(learning,eating,sleeping,others): time_for_playing=24-learning - eating - sleeping - others print "Time for playing today is %d." %time_for_playing time_for_playing(2,2,8,3)
import zmq from zmq.log.handlers import PUBHandler class ZMQPUBHandler(PUBHandler): """Custom class for zmq pub handler""" def __init__(self, sock, root_topic): """ :param string sock: zmq address :param string root_topic: prefix for log message topic """ context = zmq...
s1=input().split() n=int(s1[0]) a=4 check=True def test(a): for i in range(2,a): if a%i==0: return True return False while (check==True): if test(a)==True: b=n-a if test(b)==True: check=False print(a,b) a=a+1
# This file is part of pyrerp # Copyright (C) 2012-2013 Nathaniel Smith <njs@pobox.com> # See file COPYING for license information. import os.path import struct import os import string from collections import OrderedDict import bisect import numpy as np import pandas from pyrerp.data import DataFormat, DataSet from ...
from django.conf.urls import url from . import views urlpatterns = ( # urls for Author url(r'^authors/author/$', views.AuthorListView.as_view(), name='authors_author_list'), url(r'^authors/author/create/$', views.AuthorCreateView.as_view(), name='authors_author_create'), url(r'^authors/author/...
from pathlib import Path from typing import Dict, Union from pydantic import BaseModel from cored import CfgObj class NodeInfo: pass class DirInfo: name: str = '' path: str = '' nodes_cnt: int = 0 nodes_map: Dict[str, str] = {} @staticmethod def from_path(path): path = Path(pat...
import pandas as pd # defines a function for reformating world bank data def reformatDF(DF, *, feature_name='', round_to=2): ''' a function to reformat world bank data ''' # removes unnecessary columns DF.drop(columns=['Indicator Name', 'Indicator Code', 'Unnamed: 63'], inplace=True) # o...
from django.http import HttpResponse from django.shortcuts import render def home_view(request,*args, **kwargs): print(args, kwargs) print(request.user ) #return HttpResponse ("<h1>Welcome to cvmaker</h1>") return render(request,"home.html",{}) def login_view(request,*args, **kwargs): print(args, kwargs) ...
# In combinatorial mathematics, a derangement is a permutation of the # elements of a set, such that no element appears in its original # position. # # There's originally an array consisting of n integers from 1 to n in # ascending order, you need to find the number of derangement it can # generate. # # Also, ...
import sys from tqdm import tqdm from pubsub import MessageQueue m = MessageQueue() m.connect() m.subscribe('random') for i in tqdm(range(int(1e6)), desc='Benchmarking', file=sys.stdout, unit_scale=True, unit=' msg'): m.get_message(timeout=None)
# use ls /dev/tty* to detect the arduino port import serial import time arduino = serial.Serial("/dev/ttyACM0", baudrate=115200, timeout=3.0) while True: val = arduino.readline() print(val) arduino.close()
#!/usr/bin/env python from utils import getDatasetPresence import json import sys url='cmsweb.cern.ch' presence = getDatasetPresence(url, sys.argv[1]) print json.dumps( presence, indent=2)
# -*- coding: utf-8 -*- """ Created on Fri Apr 03 19:28:12 2015 Non Intrusive Load Monitoring for Energy Disaggregation for the REDD data Class project for CS446: Machine Learning @ University of Illinois at Urbana-Champaign REDD Reference: "J. Zico Kolter and Matthew J. Johnson. REDD: A public data set for energy dis...
# Copyright 2015, Pinterest, 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.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
from django.shortcuts import render import requests from .models import City # Create your views here. def index(request): url = 'https://api.openweathermap.org/data/2.5/weather?q={}&appid=8af2aa7fa978da0c3dc608a85406875c' # city = 'kaneohe' cities = City.objects.all() # print(cities) weather_data...
import sys, os import argparse from Converter import Converter def main(): parser = argparse.ArgumentParser(description='IC file converter to larcv format') parser.add_argument('-i','--input',required=True, dest='ic_fin', help='Input IC file (Required)') ...
#!/usr/bin/env python # # Author: Oscar Benjamin # Date: Feb 2021 # Description: # Command line script to find integer roots of polynomials with # integer coefficients. #-------------------------------------------------------------------# # # # ...
from django.urls import path from .views import ResultView, ResultDataTable app_name = 'event' urlpatterns = [ path('', ResultView.as_view(), name='result'), path('data/', ResultDataTable.as_view(), name='resultdatatable'), ]
""" This file is part of the openPMD-updater. Copyright 2018 openPMD contributors Authors: Axel Huebl License: ISC """ from openpmd_updater.backends.IBackend import IBackend import packaging.version try: import h5py as h5 except: h5 = None class HDF5(IBackend): """HDF5 File handling.""" def __in...
# import os # import subprocess # # def batch_ping(host): # result = subprocess.call('ping -c2 %s' % host, shell = True) # if result: # print('%s is down' % host) # else: # print('%s is up' % host) # # if __name__ == '__main__': # ip_addrs = ['192.168.4.%s' % i for i in range(1,10)] # ...
############################################################################### # Way to use this: # cmsRun runSens_cfg.py geometry=Run3 # # Options for geometry Run3, D88, D92, D93 # ############################################################################### import FWCore.ParameterSet.Config as cms import os, ...
# ------------------------------------------------------------------------ # # Title: Assignment 07 # Description: Research Exception Handling & Pickling in Python # ChangeLog (Who,When,What): # Kstevens,11-20-19,Modified code to complete assignment 7 # -------------------------------------------------------------...
from django.urls import path from vkrb.activity.views import (GiListView, SiListView, FavoriteGiCreateView, FavoriteSiCreateView, FavoriteGiDeleteView, FavoriteSiDeleteVie...
class Solution(object): def closeStrings(self, word1, word2): return len(word1) == len(word2) \ and set(word1) == set(word2) \ and Counter(Counter(word1).values()) == Counter(Counter(word2).values())
#coding: utf-8 import math import heapq import bisect import numpy as np from collections import Counter, deque #from scipy.misc import comb X = int(input()) ans = 0 i = 1 while 1: ans += i if X <= ans: print(i) break i += 1
# -------------------------------------------------------- # (c) Copyright 2014, 2020 by Jason DeLaat. # Licensed under BSD 3-clause licence. # -------------------------------------------------------- """ Adds operators to the Either monad. """ from typing import Any, TypeVar import pymonad.either import pymonad.monad...
# -*- coding: utf-8 -*- import psycopg2 conn = psycopg2.connect("dbname='ocrjpn' user='siena' host='localhost' password='unicorns'") cur = conn.cursor() def main(): cur.execute("SELECT entries.kanji, entries.readings, senses.blob FROM entries INNER JOIN senses ON (entries.sense_id = senses.id) where entries.looku...
from rest_framework.views import APIView from rest_framework import generics from rest_framework import permissions from django_filters.rest_framework import DjangoFilterBackend from django.db.models import Avg, Count, Min, Sum from rest_framework.response import Response import datetime from .models import ( ...
import shared_buffer from shared_buffer import * import sys import os import threading import logger from logger import Logger from defines import * import socket from datetime import datetime class proxyNetworkServiceLayer(threading.Thread) : def __init__(self,logFile,powerSimIP) : threading.Thread.__init__(self...
# -*- coding: utf-8 -*- from flask import Flask, render_template, request, flash, redirect, url_for, make_response from sentimentator.meta import Message, Status from sentimentator.database import init, get_random_sentence, save_annotation, get_score, get_username, count from flask_login import LoginManager, current_...
import asyncio import logging import time import os import urllib.parse from asyncio.exceptions import CancelledError import pyppeteer import aiofiles import ipwhois import tldextract import hashlib import dns.resolver import dns.rdatatype import whois import redis import datetime import json from ipwhois import IPWho...
#! /usr/bin/env python import sys import json import xml.etree.ElementTree as ET from file_object import file_object from datetime import datetime new_files = set() renamed_files = set() moved_files = set() changed_metadata = set() deleted_files = set() def get_file_objects_dict (root): file_objects_dict = {} for ...
# import time # import multiprocessing # # # def basic_func(x): # if x == 0: # return 'zero' # elif x % 2 == 0: # return 'even' # else: # return 'odd' # # # def multiprocessing_func(x): # y = x * x # time.sleep(2) # print('{} squared results in a/an {} number'.format(x, b...
N = int(input()) L = list(map(int, input().split())) cnt = 0 for i in range(N): for j in range(i+1, N): for k in range(j+1, N): big, small = max(L[i], L[j]), min(L[i], L[j]) cnt += big - small < L[k] < big + small and L[i] != L[j] != L[k] != L[i] print(cnt)
1. Let _target_ be _F_.[[BoundTargetFunction]]. 1. Assert: _target_ has a [[Construct]] internal method. 1. Let _boundArgs_ be _F_.[[BoundArguments]]. 1. Let _args_ be a new list containing the same values as the list _boundArgs_ in the same order followed by the same values as t...
from functools import partial from tensorflow.keras.layers.experimental.preprocessing import TextVectorization from tensorflow.keras import Model from tensorflow.keras.layers import Embedding, LSTM, Dense from tensorflow.keras.activations import sigmoid from tensorflow.keras.losses import BinaryCrossentropy from tenso...
def linear_two_points(p1, p2): x1, y1 = p1 x2, y2 = p2 slope = (y2-y1)/float(x2-x1) return lambda x: slope*(x-x1)+y1
#!/usr/bin/env python import sys base_idx = {'A': 0, 'G': 1, 'C': 2, 'T': 3 } PTR_NONE, PTR_GAP1, PTR_GAP2, PTR_BASE = 0, 1, 2, 3 def multiseqalign1DP(seq1, seq2, subst_matrix, gap_penalty): """ Return the score of the optimal Needdleman-Wunsch alignment for seq1 and seq2. Note: gap_penalty should b...
from flask_restful import Resource from flask import request from app import api from flask_jwt_extended import ( get_jwt_identity, get_jwt_claims, jwt_required, get_raw_jwt ) from app.models.user import UserSchema, UserModel from app.models.organisation import OrganisationModel, OrganisationSchema use...
""" byceps.blueprints.common.authentication.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from functools import wraps from flask import g from ....util.framework.flash import flash_notice from ....u...
''' Created on Oct 24, 2012 @author: Gary ''' from Tkinter import Tk, Frame, BOTH, W, E, N, S class Display(object): ''' classdocs ''' TITLE = 'House Monitor' TIME_COLUMN = 0 NAME_COLUMN = 1 VALUE_COLUMN = 2 mainframe = None proxy = None current_row = 0 current_values ...
import sys from functools import partial from returns.contrib.pytest.plugin import _DesiredFunctionFound class DesiredValueFound(_DesiredFunctionFound): def __init__(self, value): self.value = value def trace_func(function_to_search, frame, event, arg): if event == "return" and frame.f_code.co_nam...
from donation import app from flask import render_template, url_for ,redirect,url_for,flash, request, jsonify, json from donation.models import user, category, district, govt_pvt, blood_bank, userbank, doctor, blood from donation.forms import change, registerform , loginform, Blood_bank, registerbankform, registerdocto...
# encoding: utf-8 from api.results import result_service print 'Importing results from the web...' result_service.import_results('http://www.cccc.cat/rss-resultats') print 'Successfully imported'
import sys import unittest test_suite = sys.argv[1] loader = unittest.TestLoader() suite = loader.discover(start_dir=test_suite) results = unittest.TextTestRunner(verbosity=2).run(suite) if not results.wasSuccessful(): sys.exit(1)
from selenium import webdriver from time import sleep from tiktok import title, description from video_editor import editing from downloader import downloader downloader() sleep(5) print("i'm fucking working") editing() print("editing done !") url = "https://www.instagram.com/" username = "" passwor...
import sys from collections import Counter from typing import Collection, List, Dict from traceutils.as2org.as2org import AS2Org from traceutils.bgp.bgp import BGP from traceutils.progress.bar import Progress from traceutils.utils.utils import max_num, peek from bdrmapit.bdrmapit_parser import Updates from bdrmapit.b...
"""All invalid/not found like url specific errors go here""" from pygmy.exception.error import PygmyExcpetion class URLNotFound(PygmyExcpetion): def __init__(self, url): super().__init__() self.url = url def __str__(self): return '{0} url not found'.format(self.url)
import math class Piramide: largura = 0 volume = 0 comprimento = 0 area_base = 0 altura = 0 def __init__(self, largura=None, volume=None, comprimento=None, area_base=None, altura=None)...