text stringlengths 38 1.54M |
|---|
from flask import Flask, request, jsonify
# from backend.model import acc_binary
import joblib
import numpy as np
import pickle
import os
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
data = request.get_json()
print(data)
age = i... |
# Assignment 1
import math
class DTNode:
def __init__(self, decision):
self.decision = decision
self.children = None # cant have no children and a callable decision
def predict(self, feature_vector):
if self.is_decision_node():
return self.children[self.decision(feature_... |
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
table = []
cur = head
while cur:
table.append(cur.val)
cur = cur.next
i = 0
j = len(table) - 1
... |
from typing import List
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False
def binarySearch(array, target):
lo, hi = 0, len(array) - 1
while lo < hi:
mid = lo ... |
import os
import pandas as pd
from data_pipeline.core import DataPipeline
from multiprocessing import Process, Lock
from util.daemon import MyPool
from util.dataset import load_dataset
from util.logger import init_logger
class Worker:
def __init__(self, load, destination, outer_loop, inner_loop):
self.l... |
import tkinter
import sys
from .ctk_canvas import CTkCanvas
from ..theme_manager import ThemeManager
from ..settings import Settings
from ..draw_engine import DrawEngine
from .widget_base_class import CTkBaseClass
class CTkSwitch(CTkBaseClass):
def __init__(self, *args,
text="CTkSwitch",
... |
# def char_codes(string):
# # result = list(string)
# result = list(string).ord()
# return result
#
# print(char_codes('Create'))
# def char_codes(string):
# char = list(string)
# result = []
#
# for i in char:
# result.append(ord(i))
# return result
#
# print(char_codes('Create'))
... |
counts = [
{'school_class': '4a', 'scores': [3,4,5,5,2]},
{'school_class': '4b', 'scores': [2,3,4,5,4]},
{'school_class': '4c', 'scores': [3,4,2,2,2]}
]
summa_class = 0
summa_school = 0
quantity = 0
for s_class in range(len(counts)):
for count_number in counts[s_class]['scores']:
summa_cla... |
import scrapy
from scrapy.crawler import CrawlerProcess
class TrainSpider(scrapy.Spider):
name = "trip"
start_urls = ['http://baike.wdzj.com/list-letter-a-1.html']
def parse(self, response):
''' do something with this parser '''
next_page = response.xpath('//div[@id="fenye"]/a[contains(text... |
import pandas as pd
Q1_2015 = pd.read_csv("C:/Users/Daniel/Desktop/Capital Bike Share Data/2015-Q1-Trips-History-Data.csv")
|
import math
a = int(input('Nhap a = '))
b = int(input('Nhap b = '))
c = int(input('Nhap c = '))
if a == 0:
print('phuong trinh bac 2 thanh bac 1 bx+c=0 ')
if b == 0:
print('phuong trinh vsn')
else:
print('phuong trinh co 1 nghiem ',(-c/b))
else:
deta = b*b - 4*a*c
if deta < 0:
... |
from DnaData import get_db
class Batchlist:
def __init__(self):
self.__list_all_batch=[]
def execute(self):
data = get_db()
try:
for name in data["batch"]:
self.__list_all_batch.append(name)
print(self.__list_all_batch)
except:
... |
#
# @lc app=leetcode.cn id=1115 lang=python
#
# [1115] 交替打印FooBar
#
# @lc code=start
import threading
empty = threading.Semaphore(1) # empty信号量初始值设为1 空缓冲区数量
full = threading.Semaphore(0) # full 信号量初始值设为0 满缓冲区数量
'''信号量为0时,不可被减,同时信号量不设上限
所以需要两个信号量empty、full共同监测两个边界[0,1]'''
class FooBar(object):
d... |
import argparse
import time
from copy import deepcopy
from pathlib import Path
import numpy as np
import pandas as pd
import sklearn
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
import qiqc
from qiqc.datasets import load_qiqc, build_datasets
from qiqc.preprocessing.modules import load_pr... |
t=int(input())
while t:
t-=1
l=['h','a','c','k','e','r','r','a','n','k']
l=l[::-1]
x=0
s=input()
for i in s:
if len(l)==0:
x=1
break
elif i==l[-1]:
l.pop()
if x==0:
if len(l)==0:
print('YES')
else:
pr... |
#!/usr/dev/env python3
#coding utf-8
usename = input("account:")
password = input("password:")
if usename == 'hy' and password == '123456':
print('auth success' )
else:
print('auth failed, please try again') |
from django.db import models
from .region import Region
class State(models.Model):
"""Esta classe define um estado (unidade federativa) que pertence à uma região"""
name = models.CharField('Nome', blank=False, max_length=20)
initials = models.CharField('Sigla', blank=False, max_length=2, null=True)
... |
# 사전에서는 키 중복 허용되지 않음
# 같은 값의 키로 추가하면 덮어 씌워지는 구조
cabinet = {3:"유재석", 100: "김태호"}
print(cabinet[3])
print(cabinet.get(3))
# print(cabinet[5]) # 프로그램 종료됨 5라는 키 없기 때문에
print(cabinet.get(5)) # 값이 없어도 오류 출력 안함
print(cabinet.get(5, "사용가능")) # 값이 없으면 기본값 출력
print(3 in cabinet) # 3이라는 키가 캐비넷이 있으면 True
# 새 손님
str_cabinet = {... |
from mymed.setup.loggers import LOGGERS # import loggers will also initialize the loggers
log = LOGGERS.Setup
log.debug(f'__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__, __name__, str(__package__)))
if any(__name__ == case for case in ['__main__', 'mymed']):
from mymed.app import cre... |
import pymx
import numpy as np
scfoutfile = 'Bi2Se3.scfout'
pm = pymx.PyMX(scfoutfile,ver='3.8')
pm.default_setting()
center = (pm.a1+pm.a2+pm.a3)/2.
I_mat = pymx.inversion_mat()
gamma = 0.*pm.b1
L = 0.5*pm.b1
X = 0.5*pm.b1+0.5*pm.b2
print('inversion pair')
print(pm.Crystal_symmetry_pair(I_mat,center=center))
pri... |
import scipy.io as sio
import numpy as np
import json
import heapq
def generate_axis(wordcnt_path, n, word_tag=None):
with open(wordcnt_path) as f:
wordcnt = f.readlines()
indices = []
values = []
for i in range(len(wordcnt)):
line =wordcnt[i].split('\n')[0]
tokens = line.split('... |
from keras.datasets import mnist
import keras.utils.np_utils as ku
import keras.models as models
import keras.layers as layers
from keras import regularizers
import numpy as np
import matplotlib.pyplot as plt
(tr_im, tr_label), (te_im, te_label) = mnist.load_data()
class_names = ['0', '1', '2', '3', '4',
... |
##############################################################################
# Copyright (c) 2016 Max Breitenfeldt and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is avai... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 29 15:53:49 2020
@author: karth
"""
#---------importing packages---------------
import re
import pandas as pd
import matplotlib.pyplot as plt
import emoji
import numpy as np
#---------reading file---------------
file = open(r"C:\\Users\\karth\\Desktop\\... |
LOG_SUM256 = 'sum256'
LOG_SHA256 = 'sha256'
LOG_BCONCAT = 'bconcat'
LOG_TO_BYTES = 'to_bytes'
# log: call method
def clog(caller, func, msg):
if func == LOG_SHA256:
print('[CALL] ' + func + '(' + str(msg) + ')')
elif func == LOG_BCONCAT:
print('[CALL] ' + func + ': '+ str(msg))
elif func ==... |
#!/usr/bin/env python3
import os, subprocess, sys, time
from subprocess import PIPE
def sleep(seconds):
print(f"Waiting {seconds} seconds")
time.sleep(seconds)
def exec(cmd):
print("Executing", cmd)
p = subprocess.run(cmd, stdout=PIPE, stderr=sys.stderr)
if p.returncode != 0:
raise Asse... |
import pygame
import os
import sys
import random
import neat
W_WIDTH = 1500
W_HEIGHT = 900
F_HEIGHT = 50
BIRD_X = 300
pygame.init()
screen = pygame.display.set_mode((W_WIDTH, W_HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.SysFont('Comic Sans MS', 30)
ff_font = pygame.font.SysFont('Comic Sans... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import time
import threading
import matplotlib.pyplot as plt
import librosa
import librosa.display
import numpy as np
import wave
import pyaudio
def waveplot():
#y为长度等于采样率sr*时间的音频向量
y, sr = librosa.load("/Users/mash5/Documents/python3-workspace/python-rosa/music/... |
names = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE",
"SIX", "SEVEN", "EIGHT", "NINE"]
letters_list = [list(set(s)) for s in names]
order = [0, 2, 6, 7, 8, 3, 5, 4, 1, 9]
unique = ['Z', 'W', 'X', 'S', 'G', 'H', 'V', 'R', 'O', 'I']
def replace_num(num, cnt, s):
letters = letters_list[num]
for c in le... |
from django.db import models
from jsonfield import JSONField
from ckeditor.fields import RichTextField
# Create your models here.
class MarkedText(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
text = models.TextField()
data = JSONField(blank=True, null=True)
analysis = RichTextFie... |
import os
import sys
import codecs
import chardet
#from subFunc_tools import *
def convert(file, in_enc="GBK", out_enc="UTF-8"):
in_enc = in_enc.upper()
out_enc = out_enc.upper()
if(in_enc == 'UTF-8'):
return
try:
f = codecs.open(file, 'r', in_enc)
new_content = f.read()
... |
try:
from osgeo import ogr
except ImportError:
import ogr
import sys, os
def subtract(sourceFile, maskFile):
outputFileName = 'difference'
driver = ogr.GetDriverByName("ESRI Shapefile")
source = driver.Open(sourceFile,0)
sourceLayer = source.GetLayer()
if source is None:
pri... |
"""Import objects"""
import re
import urllib
from flask import render_template, url_for, request, flash, redirect, session
from flaskapp import APP
from flaskapp.models import *
from flaskapp.helpers import *
# an instance of Account class (responsible for user registration and login)
REGISTRANT = Account()
LIST = Li... |
#!/usr/bin/env python2.7
import sys
import urllib2
import xml.dom.minidom as xml
import shelve
import logging
#Load bot settings
from settings import (app_key, app_secret, access_token, refresh_token, user_agent, scopes, subreddit, log_path, db_path)
#Configure logging
logging.basicConfig(filename=log_path, format='%... |
from enum import IntEnum
from typing import List, Tuple
from UE4Parse.BinaryReader import BinaryStream
class EExportCommandType(IntEnum):
ExportCommandType_Create = 0
ExportCommandType_Serialize = 1
ExportCommandType_Count = 2
class FExportBundleHeader:
FirstEntryIndex: int
EntryCount: int
... |
#!/usr/bin/env python
from multiprocessing import Process
import time
class new_process(Process):
"""继承父类multiprocessing.process"""
def __init__(self, arg):
super().__init__()
self.arg = arg
def run(self):
print("start:", self.name)
print("asas", self.arg)
time.s... |
a = input("digite a string")
n = ""
for i in range(len(a)):
if(a[i] != "a" and a[i] != "A"):
n = n + a[i]
print(n)
|
#! /usr/bin/python3
# Written by Bill Ballard January 2018 for MightyOhm Geiger counter
# interface to Raspberry Pi with a Pimoroni scrollpHat or scrollpHatHD
# Designed to run in python3
# python3 geiger.py &
#
# Hardware setup
# connect scrollpHat to the GPIO, then connect
# Pi GPIO pin 6 to Geiger J7 pin 1
# Pi GPI... |
# Dependencies
from random import random
import matplotlib.pyplot as plt
import numpy as np
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.sem.html
from scipy.stats import sem
# "Will you vote for a republican in this election?"
sample_size = 100
# Like a nested for-loop, there is a list comprehens... |
from unittest import mock
import pytest
import requests
from celery.exceptions import Retry
from project.users.factories import UserFactory
from project.users.tasks import task_add_subscribe
def test_post_succeed(db_session, monkeypatch, user):
mock_requests_post = mock.MagicMock()
monkeypatch.setattr(reque... |
from rest_framework.serializers import HyperlinkedIdentityField, ModelSerializer, ValidationError, SerializerMethodField
from account.models import User
from rest_framework import status, serializers
|
from socket import *
import sys, time
if len(sys.argv) <= 1:
print 'Usage: "python proxy.py server_ip"\n[server_ip : It is the IP Address of the Proxy Server'
sys.exit(2)
# Create a server socket, bind it to a port and start listening
tcpSERVERPort = 8080
tcpSERVERSock = socket(AF_INET, SOCK_STREAM)
fp = open... |
import pygame
class Color_Ball:
def __init__(self, color, radius, x, y, x_speed, y_speed):
self.color = color
self.radius = radius
self.x = x
self.y = y
self.x_speed = x_speed
self.y_speed = y_speed
def move(self):
self.x += self.x_speed
self.y ... |
import abc
import datetime
import uuid
from typing import Callable, TypeVar, Union, Mapping
from pyservices.utilities.exceptions import ModelInitException, MetaTypeException
from pyservices.data_descriptors.meta_model import MetaModel
class Field(abc.ABC):
""" Abstract class which represents a field in a MetaMod... |
import JavaScriptCore
from PyObjCTools.TestSupport import TestCase
class TestJSStrintRefCF(TestCase):
def testFunctions(self):
v = JavaScriptCore.JSStringCreateWithCFString("hello world")
self.assertIsInstance(v, JavaScriptCore.JSStringRef)
o = JavaScriptCore.JSStringCopyCFString(None, v)... |
class Player:
def __init__(self, name):
self.name = name
self.gestures = ['Rock', 'Paper', 'Scissors', 'Lizard', 'Spock']
self.score = 0
self.chosen_gesture = 0
def set_name(self):
self.name = input("What is your name?")
return self.name
def choosing_gesture... |
#!/usr/bin/env python
# File name: projecteuler040.py
# Author: Matt McGranaghan
# Date Created: 2014/05/12
# Date Modified: 2014/05/12
# Python Version: 2.7
def solution040():
target_dec = 10**6
dec = ''
count = 1
while len(dec) < target_dec:
dec = dec + str(count)
count += 1
product = 1
for i in... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
bs = BeautifulSoup(html.read(),'html.parser')
nameList = bs.findAll('span', {'class':'green'})
#print(nameList)
for name in nameList:
print(name.get_text())
tags = bs.find_all('... |
"""
See https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/sample_guide.md
"""
from azure.template import template_main
def simple_sample():
print("Running simple sample")
template_main()
print("Completed running simple sample")
if __name__ == "__main__":
simple_sample()
|
def main(n):
maxcount = 0
maxp = 0
for p in xrange(1, n + 1):
count = 0
print '', p
for a in xrange(1, (p + 1) / 3):
if (p * p - 2 * p * a) % (2 * p - 2 * a) == 0:
b = (p * p - 2 * p * a) / (2 * p - 2 * a)
c = p - a - b
print a, b, c
count += 1
if count > maxcount:
maxcount... |
#!/usr/bin/python3
"""
Contains the route for delivering a list of states using an HTML file
"""
from flask import Flask, render_template
from models import storage
app = Flask(__name__)
@app.route('/states_list', strict_slashes=False)
def deliver_states_html():
""" Gets the list of states located within the db... |
# Example 8-1. Variables a and b hold references to the same list, not copies of the list
a = [1, 2, 3]
b = a
a.append(4)
print(a, b) |
# pylint: disable=too-many-branches
from __future__ import absolute_import, division, print_function, unicode_literals
import urllib
# import tldextract as _tldextract
import urlparse4 as urlparse
from pyfaup.faup import Faup
from . import py2_unicode
def tld_extract(domain):
if "_faup" not in __builtins__:
... |
try:
n=int(raw_input())
except ValueError:
print("Enter only integers")
else:
for i in range(1,6):
print(n*i) |
from .dump import EnsemblFungiBioMart
from .upload import (EnsemblFungiPrositeUploader, EnsemblFungiPfamUploader,
EnsemblFungiInterproUploader, EnsemblFungiGenomicPosUploader,
EnsemblFungiGeneUploader, EnsemblFungiAccUploader)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/4/12 22:00
# @Author : zengsk in HoHai
'''
FTP批量下载数据
'''
import os
import sys
from ftplib import FTP
class FtpDownloadCls:
def __init__(self, ftpserver, port, usrname, pwd):
self.ftpserver = ftpserver # ftp主机IP
self.port = port ... |
#!/usr/bin/env python
from functools import reduce
from copy import deepcopy
# fileIn = "dataSet/a_example.txt"
# fileIn = "dataSet/b_read_on.txt"
# fileIn = "dataSet/c_incunabula.txt"
# fileIn = "dataSet/d_tough_choices.txt"
# fileIn = "dataSet/e_so_many_books.txt"
# fileIn = "dataSet/f_libraries_of_the_world.txt"
... |
from files_treatment_new.xls_gen_bank_rast import Xls_gen_bank
from files_treatment_new.fasta_contigs_RAST import Fasta_contigs_RAST
from files_treatment_new.genbank_file_RAST import Genbank_proteic_RAST
from files_treatment_new.fasta_contigs_RAST import Fasta_contigs_RAST
import glob
import os
from configuratio... |
import unittest
from programy.clients.events.console.config import ConsoleConfiguration
from programy.config.bot.splitter import BotSentenceSplitterConfiguration
from programy.config.file.yaml_file import YamlConfigurationFile
from programy.utils.license.keys import LicenseKeys
class BotSentenceSplitterConfiguration... |
import socket
import argparse
from icmp import ICMPSocket
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='send ICMP ECHO_REQUEST to network hosts')
parser.add_argument('-c', metavar='count', dest='count', default=5, type=int, help='Stop after sending count ECHO_REQUEST packets.')
... |
from django.db import models
from django.core.cache import cache
from django.utils.translation import ugettext_lazy as _
from mezzanine.conf import settings
from mezzanine.core.models import Slugged, RichText
from mezzanine.core.fields import FileField, RichTextField
from mezzanine.utils.models import AdminThumbMixin
f... |
import pygame
import sys
import numpy as np
pygame.init() # intializing the pygame module
WIDTH = 600
HEIGHT = 600
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
LINE_WIDTH = 10
BOARD_ROWS = 3
BOARD_COLS = 3
CIRCLE_RADIUS = 60
CIRCLE_WIDTH = 10
CROSS_WIDTH = 15
CROSS_SPACE = 50
SQUA... |
target = "PCDHG"
file_path = "/home/kwangsookim_lab/joonhyeong_park/Practice/"
input_target_site = open(file_path + target + ".Selected.CpGsites.txt", 'r')
data = input_target_site.read().splitlines()
gene_index = data[0].split().index("UCSC_RefGene_Name")
target_site = list(map(lambda x : data[x].split()[0], range(1,... |
n = int(input()) # the number of relationships of influence
influences = [input().split() for i in range(n)]
length = 0
people_left = {x for (x, _) in influences}
while len(people_left) > 0:
people_left = {y for (x, y) in influences if x in people_left}
length += 1
print(length)
|
import sys
import re
from solver.game import Game
from solver.actions.add import Add
from solver.actions.append import Append
from solver.actions.button_add import ButtonAdd
from solver.actions.divide import Divide
from solver.actions.inv10 import Inv10
from solver.actions.invert import Invert
from solver.actions.mirr... |
from django.contrib import admin
from live.models import Profile,Hotel,Room,Booking
# Register your models here.
admin.site.register(Profile)
admin.site.register(Hotel)
admin.site.register(Room)
admin.site.register(Booking) |
from gmlConvert import txttogml
import sys
#takes input graph from text file
textInput=sys.argv[1]
#converting graph to gml format
g=txttogml(textInput)
influence=[]
k={}
nodes=[]
#Controlled Iterative Depth First Search
def idfs(g,start):
stack=[start]
k={}
a=[]
k.update({start:0})
count=0
... |
from typing import List
class Solution:
def calculate(self, s: str) -> int:
ret, _ = self.eval(s + "\0", 0, [])
return ret
def eval(self, s: str, start: int, stk: List[int]) -> int:
prev_op = "+"
operand = 0
i = start
while i < len(s):
... |
import shelve
import os
def all_files_exist(*f):
"""True when all files in the list exist on disk
Args:
*f:
Returns:
"""
for file in f:
if not os.path.isfile(file):
return False
return True
|
from yahoofinancials import YahooFinancials
import pandas as pd
import datetime as dt
def get_downloader(start_date,
end_date,
granularity='daily',):
"""returns a downloader closure for yahoo
:param start_date: the first day on which dat are downloaded
:param end_date: the la... |
import os
from selenium import webdriver
driver = webdriver.Chrome("C:/Program/pythonpackage/chromedriver.exe")
driver.maximize_window()
from os import path
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import UnexpectedAlertPresentException
import time,unittest, re
... |
from skimage import io,transform
import numpy as np
from keras.models import *
from keras.layers import *
import keras
import os
from keras import backend as K
np.set_printoptions(threshold=np.inf)
def read_data(dir_str):
data_temp=[]
with open(dir_str) as fdata:
while True:
line=fdata.rea... |
import sys
import dbf
import os
# get parameters from file
parameter_file = open('parameters.txt','r')
prms = parameter_file.readlines()
for line in prms:
txt = line.split('=')
if txt[0] == 'pluvio_folder':
pluvio_folder = txt[1].rstrip('\n')
if txt[0] == 'daily_folder':
daily_folder = txt[... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os.path as pth
from timeit import default_timer as timer
from koala import *
import matplotlib.pyplot as plt
plt.ion()
DO_PLOTTING = False
DATE = "20180310"
GRATING = "385R"
PIXEL_SIZE = 0.6 # Just 0.1 precision
KERNEL_SIZE = 1.25
OBJECT = "POX4"
... |
like_num = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
}
print(like_num
)
like_num = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
}
A_like = like_num['A']
B_like = like_num['B']
C_like = like_num['C']
D_like = like_num['D']
E_like = like_num['E']
like = [A_like,B_lik... |
import threading
import serial
import sys
import time
class DataObject(object):
"""Base class for Data Objects"""
def __init(self):
pass
def Write(self, buf, bytes):
pass
def signalwhenReady(self, callback):
self.callback = callback
#
# TODO: check how threading works i.... |
from django.shortcuts import render,redirect
from django.core.mail import send_mail
# Create your views here.
def contact_info(request):
return render(request,'contact/contact.html')
def send(request):
if request.method=='POST':
name=request.POST.get('name')
print(name)
mail =request.POS... |
from fabric.api import task, local, settings
import sys
import os
import time
browser = "firefox"
if sys.platform == 'darwin':
browser = "open"
@task
def all():
html()
pdf()
epub()
@task
def clean():
pass
@task
def view(kind='html'):
if kind == 'html':
"""view the documentat... |
"""@package sqp_linsearch
Implements the SQP linesearch method.
"""
from .sqp_solver import SqpSolver
import numpy as np
import numpy.linalg as la
from quadprog import solve_qp
from .modified_cholesky import modified_cholesky
from collections import OrderedDict
class SqpLinesearch(SqpSolver):
def __init__(self, ... |
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.encoders import jsonable_encoder
from fastapi.middleware.cors import CORSMiddleware
import cgi
a_pi = FastAPI()
class info(BaseModel):
name: str
course_name: str
join_date: str
ph_no: str
srn: str
@a_pi.get("... |
from __future__ import annotations
from typing import Any
import jax.numpy as jnp
from jax import grad, vmap
from jax.tree_util import tree_map
from numpy.random import Generator
from tjax import assert_tree_allclose
from efax import HasConjugatePrior, HasGeneralizedConjugatePrior
from .distribution_info import Dis... |
'''
DQ1 Battle Simulator - App
'''
from view import View
from controller import Controller
from model import model
if __name__ == "__main__":
view = View()
controller = Controller(model, view)
controller.view.mainloop()
|
# (c) 2015, Ian Clegg <ian.clegg@sourcewarp.com>
#
# winrmlib is 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 l... |
#!/usr/bin/python
import os, argparse
parser = argparse.ArgumentParser(prog='python PiStation.py', description='Broadcasts WAV/MP3 file over FM using RPI GPIO #4 pin.')
parser.add_argument("song_file")
parser.add_argument("-f", "--frequency", help="Set TX frequency. Acceptable range 87.1-108.2", type=float)
arg = par... |
$NetBSD: patch-setup.py,v 1.1 2019/01/28 08:40:07 adam Exp $
Allow newer pytest.
--- setup.py.orig 2019-01-28 08:19:14.000000000 +0000
+++ setup.py
@@ -23,7 +23,7 @@ classifiers = [
install_requires = ['pytest-fixture-config',
'pytest-shutil',
- 'pytest<4.0.0',
+ ... |
def fun(array):
sum = 0 # This has a time complexity of O(1)
product = 1 # This has a time complexity of O(1)
for i in array: # This has a time complexity of O(n)
sum += i ... |
# Imports ###########################################################
from django import http
from django.conf import settings
from django.utils import simplejson as json
# View Mixins #######################################################
class JSONResponseMixin(object):
def render_to_response(self, context,... |
from torchvision import datasets, transforms
from torch.utils.data import Dataset, DataLoader
import torchvision
import numpy
from utils import *
def imagenet_transformer():
transform=transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTe... |
import sqlite3
#Conexion con la base de datos, usa una base de datos en memoria
#Se pierde cuando se termina el programa
conn = sqlite3.connect(':memory:')
#Creacion de un cursor
cursor = conn.cursor()
#Creacion de una tabla
cursor.execute("""CREATE TABLE divisas (
id INTEGER PRIMARY KEY, nombre TEXT, simbolo TEXT)... |
########################################################################
## Dataloader and Code
########################################################################
import Code
import numpy as np
import torch
Times=15
'''
kernels = [Code.DoGKernel(3, 3 / 9, 6 / 9),
Code.DoGKernel(3, 6 / 9, 3 / ... |
class AuthenticationManager:
def __init__(self, timeToLive: int):
self.ttl = timeToLive
self.et = dict() # expire time
def generate(self, tokenId: str, currentTime: int) -> None:
self.et[tokenId] = currentTime + self.ttl
def renew(self, tokenId: str, currentTime: int) -> None:
... |
#!/usr/bin/env
"""
class definitions for ctd profile plots
limit to four variables
"""
import datetime
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
from matplotlib.dates import (DateFormatter, DayLocator, HourLocator,
M... |
import socket;
from tools import parseHttpHeader;
from iterator2 import *;
svrScoket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
svrScoket.bind(("localhost", 8080));
svrScoket.listen(10);
while True:
con, addr = svrScoket.accept();
buf = con.recv(1024);
request = parseHttpHeader(buf);
reques... |
__author__ = "Gil Ortiz"
__version__ = "1.0"
__date_last_modification__ = "4/28/2019"
__python_version__ = "3"
# This application generates scratch off tickets in batches (Double Dollars NY Lottery style)
# Results are currently being printed on-screen but the output can be easily tweaked to a TXT file output instead
... |
#! usr/bin/python3
# -*- coding:utf-8 -*-
import os
import sys
from cx_Freeze import setup, Executable
local_files = []
# if os.path.exists("log/"):
# local_files.append("log/")
# elif os.path.exists("userdata/"):
# local_files.append("userdata/")
# elif os.path.exists("config/"):
# local_files.append("co... |
#!/usr/bin/python
import argparse, logging, sys
import zmq
import communication
import configuration
import serialization
import payload
class Commander(object):
def __init__(self, config = configuration.Config(), serializer = serialization.Serializer(), payload = payload.Payload()):
self.context = zmq.Context(... |
n = int(input())
cityState = dict()
for _ in range(n):
line = input().split()
for k in range(1, len(line)):
cityState[line[k]] = line[0]
m = int(input())
for _ in range(m):
print(cityState[input()])
|
from bisect import bisect_right
from itertools import accumulate
N = int(input())
A = list(map(int, input().split()))
X = int(input())
tA = list(accumulate(A))
ans = N * (X // tA[-1]) + bisect_right(tA, X % tA[-1]) + 1
print(ans)
|
# MIT License
# Copyright (c) 2018 Nathan Wilson
import os
import re
import sys
from time import (
sleep,
time,
)
from log_parser.block_summary import BlockSummary
from log_parser.traffic_event_block import TrafficEventBlock
from log_parser.traffic_watcher import TrafficWatcher
from log_parser.utils import (
... |
# 8) Defina uma função que, dado um valor e uma lista, insira esse valor de forma ordenada na
# lista.
def ehMaior(a, b):
return a > b
def ehMenor(a, b):
return a < b
def insereOrdenado(x, lista):
lMenorX = list(filter(lambda y: y < x, lista))
lMaiorX = list(filter(lambda y: y > x, lista))
lInser... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.