text stringlengths 8 6.05M |
|---|
from flask import Flask
from flask import request
app = Flask(__name__)
@app.errorhandler(404)
def not_found(error):
return '404 Not Found'
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello Page'
# @app.route('/user/<username>')
#... |
#-*-coding:utf-8-*-
#__author__='maxiaohui'
from test_device import terminal
from config import config
t=terminal.frDevice(config.deviceId)
t.updateDailyBuild()
if __name__ == "__main__": #当前脚本运行实例
pass |
from models import inference
class InferenceApp:
def __init__(self, graph_fp):
self.graph_fp = graph_fp
self.predictor = None
self.prediction = None
def _init_graph(self):
self.predictor = inference.Net(graph_fp=self.graph_fp)
def predict(self, img):
self.predic... |
import os
import sys
os.chdir(os.path.dirname(__file__))
command = '/home/ubuntu/virtual_environments/sku/bin/gunicorn'
pythonpath = '/home/ubuntu/frappe/extracter/django_wrapper'
bind = '127.0.0.1:8060'
workers = 2
user = 'nobody'
|
# ====== imports block ================================== #
from random import *
# ====== defining functions ============================= #
def get_word_rus(): # Возвращает случайное слово из функции набора слов для игры
return word_rus[randint(0, len(word_rus) - 1)]
def correct_answer(answer): # Проверят коррект... |
## Copyright 2013 Sean McKenna
##
## 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... |
from django.contrib import admin
from BreastCancerApp.models import Quotes
from BreastCancerApp.models import Stories
# Register your models here.
admin.site.register(Quotes)
admin.site.register(Stories)
|
from zutils.task.task_redis import TaskRedis
from zutils.logger import Logger
from zutils.utils import relative_project_path
import traceback
import time
import os
import importlib
from zutils.task.server.task_multi_template import TaskMultiTemplate
import queue
import threading
class TaskMultiThread:
def __init_... |
import cv2
import os
import time
import numpy
myPath="images/collect"
cameraNo =0
cameraBrightness= 190
moduleVal=10
minBlur = 500
grayImage = False
saveData= True
showImage=True
imgWidth = 180
imgHeight = 120
########################
global countFolder
cap=cv2.VideoCapture(cameraNo)
cap.set(3,640)... |
#!/usr/bin/python
# author fengjiening
# -*- coding: UTF-8 -*-
from ctypes import *
class FaceService:
def __init__(self,logger):
self.logger=logger
self.flag = False
#self.path = "lib"
self.path = "../lib"
logger.info("sdk加载路径:%s" % self.path)
try:
self... |
import serial
import requests
from ws4py.client.geventclient import WebSocketClient
ser = serial.Serial('COM8', 57600)
while True:
if ord(ser.read()) == 1:
print("sending")
try:
ws = WebSocketClient('ws://127.0.0.1:5050')
ws.connect()
ws.send('confirm')
except:
print("Could not connect to server"... |
import turbo_transformers.turbo_transformers_cxx as cxx
import torch
import numpy as np
from .return_type import convert_returns_as_type, ReturnType
from .utils import try_convert, convert2tt_tensor, to_param_dict_convert_tt, to_param_dict, create_empty_if_none, AnyTensor
from .modeling_bert import BertAttention, BertE... |
import pytest
from condor.util import LanguageGuesser
@pytest.fixture(scope='module')
def guesser(request):
return LanguageGuesser()
def test_language_guesser_can_be_instantiated(guesser):
assert guesser is not None
def test_language_guesser_counts_right(guesser):
es_counts = guesser.counts('hola, ¿q... |
import os
from auth.model.user import User
from flask_mail import Message
from exception import MyException
from extensions.extensions import mail, db
from flask_jwt_extended import create_access_token, decode_token, get_jwt
from datetime import timedelta
from flask import jsonify
def generate_email_token(email):
... |
import re
import socket
import datetime
import config
def parseTimeDelta(s):
"""Create timedelta object representing time delta
expressed in a string
Takes a string in the format produced by calling str() on
a python timedelta object and returns a timedelta instance
that would produce that st... |
#Bottle provies a simpe server that can run Python code and connect it to a website.
#Unlike Django and others, there's no database or other full-stack components, making it useful for quick display-based tools.
#Import the stuff we need first:
from bottle import route, run, template, view, debug
#Obviously you can i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Facebook idle status obfuscator for Libpurple via Pidgin/Finch
username = "zuck"
protocol_id = "prpl-facebook"
NAP_MIN = 15*60
NAP_MAX = 120*60
from pydbus import SessionBus
from time import sleep
from random import randint
bus = SessionBus()
purple = bus.get("im.pid... |
import pandas as pd
import numpy as np
import scipy.stats as stats
class machine:
def __init__(self, type, i, **kwargs):
self.type = type
self.id = type+str(i)
self.facility = kwargs.get('facility')
self.queue = pd.DataFrame(
{
'jb_color':None,
'j... |
import unittest
from katas.kyu_8.adam_and_eve import God, Man
class AdamAndEveTestCase(unittest.TestCase):
def test_equals(self):
self.assertIsInstance(God()[0], Man)
|
# macros for mkdocs-macros-plugin
import os
import requests
_inline_code_styles = {
".py": "python",
".sh": "bash",
".h": "cpp",
".cpp": "cpp",
".c": "c",
".rs": "rs",
".js": "js",
".md": None
}
def define_env(env):
@env.macro
def insert_zenodo_field(*keys: str):
""" This is the *released* v... |
#!/usr/bin/env python
"""
Author: Alberto Quattrini Li
Affiliation: AFRL - University of South Carolina
Date: 12/20/2016
Description:
Run the actual script for reading depth sensor and switch.
Needed for correctly killing that script, as it runs with sudo permission
for the FT232H API.
Usage:
pytho... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" Zimbra specific objects, handle (un)parsing to/from XML and other glue-code
Note that they do *not* handle themselves communication with
zimbra API. It is left to
ZimbraAdminClient/ZimbraAccountClient/ZimbraMailClient...
"""
fr... |
import testpaho.mqtt.client as mqtt
import random, string, sys
def gen_cli_id(size):
return ''.join([random.choice(string.ascii_letters + string.digits) \
for n in range(size)])
if __name__ == '__main__':
if len(sys.argv) != 5:
print('usage: python3 bad_sub.py HOST PORT TOPIC SY... |
#!/bin/python3
import sys
N=int(sys.argv[1])
a=0
b=1
s=0
for i in range(N):
print(a, end =" ")
s=a+b
a=b
b=s
|
# -*- coding: utf-8 -*-
# Author: Simone Marsili <simomarsili@gmail.com>
# License: BSD 3 clause
"""Utility functions."""
import functools
import logging
logger = logging.getLogger(__name__)
__all__ = [
'is_command',
]
def is_command(cmds):
"""Given one command returns its path, or None.
Given a list o... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import json
import sys
# In[113]:
filenames = sys.argv[1]
output_json = sys.argv[2]
fields = ["Time","Person","Message"]
list1 = []
def split_data(s):
temp = s.split()
ans = ''
k = ''
i = 1
while(temp[i][-1]!=':'):
k+=temp[i]
k+... |
# -*- coding: utf-8 -*-
"""Console script for dk_earth_engine_downloader."""
import click
import dateparser
import os
from enum import Enum
from imageCollection import ImageCollection
from DirectorRequestBuilder import DirectorRequestBuilder
from Invoker import Invoker
from HandlerSpecifyImageryCollection import Hand... |
# Generated by Django 2.2 on 2020-10-23 18:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='spares',
old_name='prise',
... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.constants as sc
""" Variables """
E0 = 90000
d = 2e7
B_0=0.000000001
def vgen(n):
'''Initial Velocities'''
lin = np.linspace(-0.015,0.017,n)
#lin = 0*np.ones((20,1))
return lin
def zgen(n):
'''Inital Positions'''
lin = np.linsp... |
import unittest
import os
import unfurl.manifest
from unfurl.yamlmanifest import YamlManifest
from unfurl.eval import Ref, mapValue, RefContext
manifestDoc = """
apiVersion: unfurl/v1alpha1
kind: Manifest
spec:
service_template:
decorators:
missing:
properties:
test: missing
my_ser... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Suppose you have a long flowerbed in which some of the plots are planted and some are not.
# However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
# Given a flowerbed (represented as an array containing 0 and 1, where 0 m... |
def fibonacci(n):
a = 0
b = 1
print(a)
print(b)
for i in range(2,n):
c = a+b
a = b
b = c
print(c)
fibonacci(int(input("Enter range: "))) |
import hashlib
import time
from datetime import datetime, timedelta
import redis
from pymongo import ASCENDING, DESCENDING, IndexModel, MongoClient
#redis set "urls" as a filter ignore duplicate urls
#use redis hashset "tmp_urls" to fetch urls and save to redis key-value as urls have send to client
class MongoRedisU... |
# Exercício 2.4 - Livro
a = 3
b = 5
print((2*a) * (3*b))
|
"""
Django settings for segmentoj project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
... |
input_variable1,input_variable2=map(int,input().split())
temp=0;
var1=[int(a)for a in input().split()]
for i in range(0,len(var1)-1):
for j in range(1,len(var1)):
if var1[i]+var1[j]==input_variable2:
temp=temp+1
break
break
if temp>=1:
print("yes")
else:
print("no")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Assignment in BMP course - Program Association Table parser
Author: Jakub Lukac
E-mail: xlukac09@stud.fit.vutbr.cz
Created: 16-10-2019
Testing: python3.6
"""
import sys
from psi import PSI
class PAT(PSI):
__PAT_TABLE = 0x00
__TABLE_EXTENSION_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-09-04 10:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('progress_analyzer', '0020_auto_20180723_1422'),
]
operations = [
migrations... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.jvm.resolve.jvm_tool import JvmToolBase
class JavaProtobufGrpcSubsystem(JvmToolBase):
options_scope = "protobuf-java-grpc"
help = "gRPC support for Java Protobuf (https... |
import numpy as np
grid = [
[9,0,0,0,0,2,0,0,0] ,
[1,0,0,5,0,0,0,0,4] ,
[0,0,3,0,0,0,5,7,0] ,
[0,0,0,0,0,8,6,9,0] ,
[6,0,0,0,0,0,0,0,2] ,
[0,1,4,9,0,0,0,0,0] ,
[0,5,9,0,0,0,4,0,0] ,
[2,0,0,0,0,1,0,0,6] ,
[0,0,0,3,0,0,0,0,5]
]
def possible(x, y, n):
for i in range(0, 9):
if grid[i][x] =... |
import re
count = 0
lst = []
start = int(input('start of working day: '))
end = int(input('end of working day: '))
f1 = open('/var/log/auth.log')
for line in f1:
count += 1
time = re.search(r"\w\w:\w\w:\w\w", line)
if int(time.group(0)[0:2]) < start or int(time.group(0)[0:2]) > end or (int(time.group(0)[0:... |
# Bài 04: Viết hàm
# def is_prime(n)
# để kiểm tra xem số tự nhiên n có phải số nguyên tố hay không, nếu có thì trả lại True, nếu không thì trả lại False
def is_prime(n) :
if n == 1 :
return False
run = int(n/2 + 1)
count = 0
for i in range(1,run) :
if n % i == 0 :
... |
# -*- coding: utf-8 -*-
import sys
sys.path.append('./service')
sys.path.append('./lib')
from data import data
class AAA:
def __init__(self):
#super(FightService, self).__init__()
print 'self.data= data'
self.data= data
#self.data= {}
#aaa= 'asdf'
def f(self):
self.data['s']= 's';
def ff(self):
p... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import json
import os.path
import tarfile
import textwrap
from textwrap import dedent
from typing import cast
import pytest
from pants.backend.javascri... |
"""
Copyright 1999 Illinois Institute of Technology
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 rights to use, copy, modify, merge, publis... |
def cabecalho():
print(10 * '-' + 'PROGRAMA EM PYTHON' + 10 * '-')
def validaCPF(cpf):
cabecalho()
if len(cpf) == 11:
print('cpf válido')
else:
print('cpf invalido')
cp = str(input('Digite seu CPF: '))
validaCPF(cp) |
from sanic import Sanic
from sanic.response import json
from datetime import datetime
import requests
app = Sanic()
@app.route('/')
@app.route('/<path:path>')
async def index(request, path=""):
url = "https://graphql.anilist.co"
months = ["", "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", ... |
#!flask/bin/python
import json
from flask import jsonify
import MySQLdb as MySQL
HOST = "127.0.0.1"
USER = "root"
PASSWORD = "cs411fa2016"
DB = "imdb"
def get_actors_by_movie_id(movie_id):
try:
conn = MySQL.connect(host=HOST, user=USER, passwd=PASSWORD, db=DB)
cursor = conn.cursor()
except My... |
from flask import Blueprint, jsonify, Response, request
from src.redis import Redis, CACHED_CARDS
import itertools
import random
blueprint = Blueprint('get_random_deck', __name__)
def get_card_output(card):
return {
'name': card['name'],
'colors': card['colors'],
'manaCost': card['manaCos... |
import sys
def read_file(textfile):
# Open sudoku file (text document)
f = open(textfile, 'r')
next(f)
i = 0
j = 0
matrix = [[0 for x in range(9)] for y in range(9)]
# print (matrix)
while True:
j = 0
char = f.readline()
for c in char:
matrix[i][j] = int(c)
# print (i, j)
j += 1
if j == 9:
... |
# -*- coding: utf-8 -*-
# flake8: noqa
from qiniu import Auth, put_data, etag, urlsafe_base64_encode
import qiniu.config
import logging
#需要填写你的 Access Key 和 Secret Key
access_key = 'kYadYeFySDHVmCzIBrvYLO6Kdb67TU-MbisQhHqc'
secret_key = 'zGIGRSFNyifqPXR4kUUYYPZO7mV50JdIYABnojyA'
def storage(file_data):
try:
... |
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
f = open("output.csv","w")
f.write("t,x,y\n")
start = time.time()
while(True):
ret, frame = cap.read()
hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
low_color = np.array([160, 75, 75])
upper_color = np.array([180, 255, 255])
ex_img = cv2.inRang... |
#!/usr/bin/env python3
import re
import bibtexparser
from bibtexparser.bparser import BibTexParser
from bibtexparser.customization import convert_to_unicode
month_index = {"jan": 1, "january": 1, "feb": 2, "february": 2, "mar": 3, "march": 3, "apr": 4,
"april": 4, "may": 5, "jun": 6, "june": 6, "jul": ... |
# -*- coding: utf-8 -*- #encoding of a python file
#PostfixExpression.py: wenlong
#Description: compute the value of the postfix [ (1+2)*3 => 1 2 + 3 * ]
#Notes: 1) the import way 2) in Stack class, pop method should have the return function
from datastructure.stack import Stack #the file is named stack too
... |
"""Dataclasses for storing and processing the samples."""
from __future__ import annotations
import itertools
from collections import defaultdict
from dataclasses import dataclass, field, replace
from typing import TYPE_CHECKING, Optional, cast
import numpy as np
from pulser.channels.base_channel import Channel
from... |
# A simple python script meant to show the potential damage a Rubber Ducky could do
# Frank Cerny
# 9/20/19
import pyfiglet
ascii_banner = pyfiglet.figlet_format("You have been H4cked")
print(ascii_banner)
# print('\nYou\nhave\nbeen\nh4cked\n')
|
# dcc constants
DCC_ID_ISIF_CSC = 0
DCC_ID_ISIF_BLACK_CLAMP = 1
DCC_ID_H3A_MUX = 2
DCC_ID_H3A_AEWB_CFG = 3
DCC_ID_IPIPE_DECMP = 4
DCC_ID_MESH_LDC = 5
DCC_ID_ISS_GLBCE = 6
DCC_ID_IPIPE_CFA = 9
DCC_ID_IPIPE_RGB_RGB_1 = 10
DCC_ID_NSF_CFG = 21
DCC_ID_AAA_ALG_AWB_TI3 = 40
|
# coding: utf-8
'''
Análise de Sentimentos em Textos
Apendisagem Máquina Supevisionado
Exemplo do curso de Mineração de Emoções em Textos
https://www.udemy.com/mineracao-de-emocao-em-textos-com-python-e-nltk/learn/v4/t/lecture/7317124?start=0
Data: 07/04/2018
'''
impo... |
from sklearn.model_selection import train_test_split
from preprocess import proces_dataset_faces
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
path_faces = "data/preprocess_faces/"
X,Y = proces_dataset_faces(path_faces)
print(X.shape)
print(Y.shape... |
# Python Substrate Interface Library
#
# Copyright 2018-2020 Stichting Polkascan (Polkascan Foundation).
#
# 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/LIC... |
import pymysql
user = 'admin'
password = 'Fxa@880202'
host = '47.112.213.237'
port = 3306
database = 'companynews'
def getAllNewsList():
db = pymysql.connect(host=host, port=port, user=user, password=password, database=database)
cursor = db.cursor()
sql = 'select * from news'
cursor.execute(sql)
a... |
import collections
import json
from functools import lru_cache
import dash_bootstrap_components as dbc
def get_component_metadata(component_path):
metadata = _load_metadata()
return metadata.get(component_path)
@lru_cache(maxsize=1)
def _load_metadata():
return _get_metadata(dbc._METADATA_PATH)
def _... |
def dont_learn_this_way():
print(len("xxxxx"))
print(f"{len('jjj')}")
def do_learn_this_way():
assert 1 != 1
assert 1 + 1 == 2
assert '1' + '1' == '11'
assert 2 * 3 == 6
assert 2 * '3' == '33'
assert len('jjj') == 3
def record_my_learning():
dont_learn_this_way()
do_learn_thi... |
#!/usr/bin/python3
import random
print("Jeu du nombre secret ")
n= random.randint(0,99)
print("J'ai choisi un nombre secret entre 0 et 99")
e=1
p = int(input("Devines "));
while(p != n):
e+=1
print("Incorrect")
if (p > n):
print("C'est un nombre plus petit")
else:
print("C'est un nombre plus grand");
p = int(... |
import os, argparse
import sqlite3
import pandas as pd
from util import util_newssniffer_parsing as unp
import warnings
warnings.filterwarnings("ignore")
data_path = '../data/diffengine-diffs/db'
if not os.path.exists(data_path):
data_path = '../data'
output_path = "output"
conn_mapper_dict = {
'nyt': os.pat... |
#!/usr/bin/env python3
import argparse
import collections
import itertools
import json
import logging
import os
import pickle
import warnings
import coloredlogs
import numpy as np
import pandas as pd
import sklearn.metrics.pairwise
from ismir2019_cifka.eval.style_profile import time_pitch_diff_hist
from ismir2019_cif... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 13 14:35:35 2021
@author: hirsh
"""
import pandas as pd
import openpyxl
import datetime as dt
import requests
from bs4 import BeautifulSoup as bs
# need to get turnovers from each player's page
# and iterate through table pages to get player url's and most... |
#!/usr/bin/python3
# classes.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
class Duck:
def quack(self):
print('Quaaack!')
def walk(self):
print('Walks like a duck.')
def bark(self):
... |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
#altered version of Tetris game using PyQt5 http://zetcode.com/gui/pyqt5/tetris/
#Key is class Shape.coordsTable ,by which we could know every shape's whole inforamtion
'''
The bottom line is we could calculate a specific shape's every square's cordinates (x,y,means the x'th... |
import pyodbc
import datetime
from faker import Faker
import Getname
import random
import string
from os import getenv
"""
CRUD Controller class, responsible for basic CRUD operations on our database.
"""
class Controller:
hostname = ''
login = ''
password = ''
database_name = ''
conn = ''
cu... |
import dash_bootstrap_components as dbc
carousel = dbc.Carousel(
items=[
{"key": "1", "src": "/static/images/slide1.svg"},
{"key": "2", "src": "/static/images/slide2.svg"},
{"key": "3", "src": "/static/images/slide3.svg"},
],
controls=True,
indicators=True,
)
|
#-*-coding:utf-8-*-
import argparse
from utils import str2bool
def get_config():
parser = argparse.ArgumentParser()
# Model configuration.
parser.add_argument('--mode', type=str, default='train', help='train|test')
parser.add_argument('--image_size', type=int, default=64, help='image load resolu... |
import os
import argparse
def main(argv=sys.argv[1:]):
pass
|
from tkinter import *
from tkinter.filedialog import askopenfilename
from math import sqrt, pow
from PIL import Image, ImageDraw, ImageFont, ImageTk
from time import sleep
# The basic interface is laid out. Not functionality yet.
# Additional Resources
# https://stackoverflow.com/questions/5501192/how-to-display-pict... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
result = 0
for length in range(1, len(arr) + 1, 2):
for i in range(len(arr) - length + 1):
result += sum(arr[i : i + length])
return result
... |
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import codecs
import nltk
import re
import pickle
# function to build the dictionary for words to be used for context features
def getContextDictionary(articles):
vectorizer1 = Co... |
import time
import random
from pylo import loader
DMPyJEMMicroscope = loader.getDeviceClass("DM + PyJEM Microscope")
class DMPyJEMTestMicroscope(DMPyJEMMicroscope):
def __init__(self, *args, **kwargs) -> None:
"""Get the microscope instance"""
self._lorentz_mode = False
super().__init__(*a... |
# -*- coding: utf8 -*-
# [학번] [이름]
# numpy 소개
# 각 행 주석 입력
# 배열, 행렬 관련 기능을 담고 있는 numpy 모듈을 불러 들여 np 라는 이름 아래 연결함
# import numpy as np
# r1 = np.array((1.0, 2.0))
# print("r1 = %s" % r1)
# r2 = np.array((-2.0, 1.0))
# print("r2 = %s" % r2)
# r3 = r1 + r2
# print("r3 = %s" % r3)
|
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 applica... |
# name generator exercise
# algorithmic narrative lab / (LNA in spanish)
# Variable random mixing from lists (made for soldiers in a RTS)
# by 220 & AA (2019) GPLv3 license
import random
lista_nombres = ["Alfredo", "Alejandro", "Armando", "Román", "Ramón", "Mario", "Antonio", "Eduardo", "Javier", "Ricardo", "Federico... |
import abc
from collections import deque
import hashlib
import io
import logging
import mimetypes
import os
import os.path as osp
import tempfile
import six
from smqtk.exceptions import InvalidUriError, NoUriResolutionError, \
ReadOnlyError
from smqtk.representation import SmqtkRepresentation
from smqtk.utils imp... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind = engine)
session = DBSession()
all_rest = session.query(Restaurant).all()
... |
def binarySearch(arr,num,l,r):
if(r-l>=1):
mid = (l+r)//2
if(num == arr[mid]):
return True
elif(num>arr[mid]):
return binarySearch(arr,num,mid+1,r)
else:
return binarySearch(arr,num,0,mid)
return -1
def fixedPoint(arr,l,r):
if(r-l>=1):
... |
# DEFLATE.py
# Compresses files with a DEFLATE-ish algorithm. (Working towards compliance.)
# NOTE: output NUMBER of length/literal/etc values before outputting huffman trees
# NOTE: rework length/distance -> code to utilize the pattern ?
# NOTE: change algorithm to only use next_char for non-repeated letters and dist/... |
from jobs import *
from json import *
from optimizer import *
from plots import *
from statistics import *
|
L=[]
for n in range(1,10001):
num=0
for i in range(1,n):
if n%i==0:
num=num+i
if num==n:
L.append(n)
print(L)
|
from time import sleep
import requests
import serial
# Configuration
# USB port - Adruino USB connection to PC
usb_serial_port = "COM3"
# Website host address
host= "http://localhost/Water-Quality-Monitoring-System-Website/" # End url with a slash '/'
ser = serial.Serial(usb_serial_port,9600)
while True:
getVal = s... |
# Generated by Django 2.0.5 on 2019-05-02 12:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('calculation', '0048_auto_20180807_1139'),
]
operations = [
migrations.AlterUniqueTogether(
name='dish',
unique_together=set(... |
from __future__ import unicode_literals
import re
from django.utils.six import text_type, string_types
from django.contrib.gis.db import models
from django.core import urlresolvers
from django.template.defaultfilters import slugify
from django.contrib.gis.geos import GEOSGeometry
from appconf import AppConf
from jso... |
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self, num_classes=10):
super(Net, self).__init__()
self.num_classes = num_classes
self.conv1 = nn.Conv2d(3, 32, 3) # 30
self.relu1 = nn.ReLU()
self.bn1 = nn.BatchNorm2d(32)
... |
import jinja2
templateLoader = jinja2.FileSystemLoader(searchpath="/")
templateEnv = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE = "./template.jinja"
template = templateEnv.get_template( TEMPLATE_FILE )
templateVars = { "title" : "Test Example",
"description" : "A simple inquiry of f... |
def LCs (x , y) :
global X,Y,dp
for i in range (x+1) :
for j in range (y+1) :
if (i == 0) or (j == 0) :
dp[i][j] = 0
else :
if (X[i-1] == Y[j-1]) :
dp[i][j] = 1 + dp[i-1][j-1]
else :
dp[i][j] = 0
return max ([max(i) for i in dp])
X = input()
Y = input()
x = X.__len__()
y = Y.__len__()
d... |
import os
import dj_database_url
from .base import *
DEBUG = False
TEMPLATE_DEBUG = False
# SSL Settings
# SESSION_COOKIE_SECURE = True
# CSRF_COOKIE_SECURE = True
# SECURE_SSL_REDIRECT = True
ADMINS = (
('Joao Figueiredo', 'joaonvfigueiredo@gmail.com'),
)
ALLOWED_HOSTS = [
'.joao-e-paola.xyz',
'ec2-52... |
#Red Neural Artificial Adaline
#Programado por: Pedro Bermeo
#Ing. Sistemas - IA2
'''
Ejemplo con valores:
| x1 | x2 | d |
-----------------
| 1 | 1 | -1 |
| 1 | -1 | 1 |
| -1 | 1 | -1 |
| -1 | -1 | -1 |
W = [0.2, 0.2]
θ = 0.2
α = 0.2
'''
#%matp... |
'''
Created on Oct 1, 2018
@author: root
'''
import paho.mqtt.client as mqtt
class MQTT_Client:
def __init__(self):
return mqtt.Client()
def on_connect(self, userdata, flags, rc):
print('Connected with result code' + str(rc))
|
def collatz(number):
if number % 2 == 0:
number = number // 2
print(str(number))
else:
number = (3 * number) + 1
return number
def output():
print ('Please enter a number.')
value = int(input())
num = collatz(value)
while num != 1:
num = collatz(num)
prin... |
from gtts import gTTS
import os
print("choose your language")
print("1: for Hindi")
print("2: for English")
print("3: for Spanish")
l=int(input("Enter your choice :"))
if l == 1:
tell = "hi"
text = open("hindi.txt","r").read().replace("\n","")
elif l == 2:
tell = "en"
text = open("english.txt","r").read().replace... |
from sys import argv
i , u = argv
txt = open ( u )
print txt.read()
txt.close() |
# amaranth: UnusedElaboratable=no
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" Helpers for clock domain crossings. """
import unittest
import warnings
from unittest import TestCase
from amaranth import R... |
import fourier
import pcf
import ioutils as io
from mathutils import *
import setup
#============================================================================
LOGS_DIR = "../fig8b-bnot/"
TARGET_DIR = "../targets/"
FILE_EXT = ".pdf"
#============================================================================
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.