text
stringlengths
8
6.05M
from threading import Thread class mythread(Thread): def __init__(self,saying): super(mythread, self).__init__() self.saying = saying self.__init = True def run(self): if not self.__init: print "init failed" exit(0) print se...
def foo(): print('Java') if __name__ == '__main__': print('Hello World')
#===== Write a program that tells you the following : # - how many hours in a year? # - how many minutes in a decade? # - how many seconds old are you? # - I'm 48618000 seconds old. calculate her age. #===== tougher question # - calculate # - how many days does it take for a 32-bit syatem to timeout, if it has a bug ...
from django.db import models from django.utils.dateformat import format class Appointment(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=255) email = models.CharField(max_length=255) date = models.CharField(max_length=50 , default=None) hour = models.Tim...
#!/usr/bin/env python """ There is a mass shooting on average every day in the United States. Here are the shootings on this day last year. https://twitter.com/mass_shoot_bot """ import argparse import csv import datetime import os.path import sys import webbrowser import inflect # pip install inflect import twitter ...
import pathlib from typing import List, Union, Dict T_QUERY = str T_QUERIES = List[T_QUERY] T_DOMAIN = str T_DOMAINS = List[T_DOMAIN] T_BASE_URL = str T_URL = str T_REQUEST_RESULT = Union[int, str] T_REQUEST_RESULTS = List[T_REQUEST_RESULT] T_RESULTS_FOR_DOMAIN = Dict[T_DOMAIN, T_REQUEST_RESULTS] T_RESULTS_FOR_DOMA...
import json import itertools from aiohttp import web, WSMsgType from responses import html_response routes = web.RouteTableDef() @routes.get('/') async def index(request): # отправка контента файла html return html_response('index.html') @routes.get('/ws') async def websocket_handler(request): ws = web....
import os import re import sys import json import math import datetime import shutil from ruamel.yaml import YAML yaml = YAML() from generalMoveNames import generalMoveNames from generateFrameGraph import getFrameGraph generatedAt = datetime.datetime.utcnow().strftime("%H:%M:%S UTC on %B %d, %Y") with open("moveNam...
#!/usr/bin/python3.6.8 # This module contains the routes # for the rest api import os import json from sqlalchemy import create_engine from sqlalchemy.orm import relationship, sessionmaker from flask import Blueprint, jsonify from databaseSetup import Base, Company, Cars, User # Database connection dbUser = os.enviro...
import os MONGO_URI = os.getenv('MONGODB_URI') MONGO_DATABASE_NAME = os.getenv('MONGO_DATABASE_NAME') FRONTEND_ORIGIN = os.getenv('FRONTEND_ORIGIN')
#!/usr/bin/python # -*- coding: UTF-8 -*- import config import file_reader import logger.logger as logger from model.directory import Directory def get_content(): directory = _get_selected_directory() file_name = _get_selected_file(directory) if (file_name is not None): path = directory.get_path(...
for i in range(5): if(i==3): break #breaks the loop completely print(i) print('\n') #example of continue statement for i in range(5): if(i==3): continue #skips the current iteration and moves to next print(i) print('\n') #example of pass statement for i in range(5): if(i==3): ...
# coding: utf-8 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib import sys import csv import os import datetime import time mailto_list = ["staticor@me.com"] mail_host = "smtp.sina.com" try: mail_user = os.environ.get('MAIL_USERNAME') mail_password = os.environ.g...
import torch import time from datetime import datetime from models import save_model from utils import ProgressMonitor, RunningAverage, check_dims device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") best_loss = float('inf') prev_loss = float('inf') loss_inc_cnt = 0 stp_erly_cnt = 1 stop_earl...
#path = '/media/ostalo/MihaGarafolj/ME_data/CASME2_Color_TIM10/CASME2_Color_TIM10/' #pathtxt = '/media/ostalo/MihaGarafolj/ME_data/CASME2_Color_TIM10/' db_name = 'CASME1_Color_TIM10' path = '/home/mihag/workingDir/flownet2-docker/data/' + db_name + '/' + db_name + '/' pathtxt = '/home/mihag/workingDir/flownet2-doc...
import sys for order in sys.stdin.read().splitlines(): N, K = map(int, order.split()) i = 0 input_list = list(range(1, N + 1)) output_list = [] while input_list: i = (i + K - 1) % len(input_list) output_list.append(input_list.pop(i)) print(f"<{', '.join(map(str, output_list))}...
# coding: utf-8 from __future__ import unicode_literals SLACK_TOKEN = None REDIS_URL = None # gevent pool size POOL_SIZE = 20 # add your app name to this list APPS = ['hello_world', 'helper', 'giphy', 'ghost', 'rainy_day', 'what_temp', 'sleep']
import gtk.gdk import os import datetime w = gtk.gdk.get_default_root_window() sz = w.get_size() print "The size of the window is %d x %d" % sz pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1]) pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1]) if (pb != None): currenttime = datetime...
import logging.config import os import gridfs from flask import (Flask) from flask_themes2 import (Themes) from pymongo import MongoClient from simplekv.fs import FilesystemStore BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) app = Flask(__name__) Themes(app, app_identifier='cert_view...
# Generated by Django 2.2 on 2019-04-24 13:27 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Test', fields=[ ('id', models.AutoField(auto_...
from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from .views import UserViewSet, UserByUid user_list = UserViewSet.as_view({ 'get': 'list', 'post': 'create' }) user_detail = UserViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_up...
import cv2 import matplotlib.pyplot as plt clahe = cv2.createCLAHE(clipLimit=2,tileGridSize=(10,10)) cl1 = clahe.apply(img) plt.subplot(132),plt.imshow(res,'gray') plt.subplot(133),plt.imshow(cl1,'gray') plt.show()
# Generated by Django 3.1.1 on 2020-09-26 08:13 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='COM_CD_M', fields=[ ...
# coding=utf-8 _author_='love_huan' def create(smallest,largest): intSet=[] for i in range(smallest,largest+1): intSet.append(None) return intSet def insert(intSet,e): intSet[e] = 1 def member(intSet,e): return intSet[e]==1
#!/usr/bin/env python import sys arcstats_file = '/proc/spl/kstat/zfs/arcstats' try: with open(arcstats_file, 'r') as f: garbage = f.readline() header = f.readline() stats = f.read() stats_lines = stats.split('\n') except Exception as E: print "CRITICAL - failed to parse arc...
# code by Jonathan from Utils import oauth_post from urllib.parse import quote # building the query string from the post form data def builddeletetweet(formdata): querydata = 'https://api.twitter.com/1.1/statuses/destroy/' if formdata['parameters_id'] != "": querydata = querydata + quote(formdata['p...
# Ronald Yu, :ab 1 # Roger Ding , Lab 1 # We certify that we worked cooperatively on this programming # assignment, according to the rules for pair programming import goody import random def read_corpus(order_stat, infile): corpus=dict() word_list = list(goody.read_file_values(infile)) start = ...
from collections import defaultdict import email_sender from database import db_interface as db from functions.utilities import utils from functions.utilities import variables as vrs def main(specific_day=None): """ Mentors are given personalized schedules as they walk in each day for their meetings. Thi...
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-05 09:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0036_auto_20161002_2055'), ] operations = [ migrations.AddField( ...
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
#1**2 + 2**2 + 3**3 + .. + 1000**1000 = toplamının son 10 basamağını veren algo toplam = 0 for i in range(1,1001): toplam += i**i #print(len(str(toplam))) str ye çevirirsem kaç basamaklı olduğunu bulabilirim print(str(toplam)[-10:]) #sondan 10 basamağını yazdırmamızı söylüyoruz
''' Created on Sep 15, 2015 @author: Jonathan Yu ''' import math import turtle wn = turtle.Screen() def circleLine(turtle, center, heading, length, numCircles, numLines): #draws a set of lines, which are made up of circles, that are rotated around a point turtle.penup() turtle.goto(center) turtle.pen...
import netmiko import os def main(): """ Basic Netmiko script showing how to connect to a device. """ # https://github.com/ktbyers/netmiko/blob/develop/netmiko/ssh_autodetect.py # user = os.environ.get('username') # pwd = os.environ.get('password') # sec = os.environ.get('secret') ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 5 16:35:36 2020 @author: kodiuser """ from flask import Flask, render_template, request, flash import random, requests, html, inflect, numexpr, math from math import factorial app = Flask(__name__) app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @app.rou...
#!/usr/bin/env python3 # Kebechet # Copyright(C) 2018, 2019 Fridolin Pokorny # # 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) any later ...
from onegov.chat import Message from sqlalchemy.orm import object_session from typing import TYPE_CHECKING if TYPE_CHECKING: from onegov.file import File class FileMessage(Message): __mapper_args__ = { 'polymorphic_identity': 'file' } @classmethod def log_signature(cls, file: 'File', si...
#coding=utf-8 from word_oper.extract_words import words_count def task(): words_count() if __name__ == '__main__': task()
''' Name: Elijah Thorpe Course: CSE Assignment: Data Modeling Purpose: This parses all of the data files. parse_data() is what you want to do, returning: ({'Wind':[int(megawatthours of wind in Alaska),etc.],etc.}, [int(average income in Alaska),etc.]) ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed May 16 16:21:27 2018 @author: meicanhua """ # coding: utf-8 from gensim.models import word2vec from gensim.models import Word2Vec import logging import sys logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) if...
#!/opt/anaconda3/bin/python """ Author: Jialun Luo """ import h5py import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.colors import LogNorm import time import subprocess import argparse import glob def PlotTransmission(refTrFile, measu...
n1=int(input("enter 1st number ")) n2=int(input("enter 2nd number :")) if n1>n2: print("big number is :",n1) else: print("big number is :",n2)
# -*- encoding: utf-8 -*- # # OpenERP Correccion Monetaria # Copyright (C) 2011-2013 David Acevedo <dacevedo@stratanet.cl> # # 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 t...
# Class for storing and sharing common data such as # config and settings data from . import logging from .logging import handlers import os class AnkiHabiticaCommon: config = {} # dictionary for configuration user_settings = {} log = logging.Logger class settings: pass # empty class for ho...
"""An implementation of the Minover algorithm.""" import numpy as np from percplotter import plot from percutility import generalization_error, generate_data, generate_teacher def run_minover(P=5, N=2, t_max=100, clamped=False, use_teacher=False): """Minover algorithm. N is the number of dimensions P is...
from aiogram import types from misc import dp, bot from .sqlit import cheak_traf,reg_user,cheak_chat_id reg_user(1,1) list_channel = cheak_traf() name_channel_1 = list_channel[0] name_channel_2 = list_channel[1] name_channel_3 = list_channel[2] name_channel_4 = list_channel[3] def obnovlenie(): glob...
__author__ = 'Alexey' from graph_tools.bipartite_utils import build_maximum_matching log = open("input.txt") left, right = [], [] left += log.readline().strip().split(' ') right += log.readline().strip().split(' ') edges = [] line = log.readline() while len(line) > 0: card, cover = map(int, line.strip().split(' '...
# -*- coding: utf-8 -*- from irc3 import event from irc3 import rfc __doc__ = ''' ============================================== :mod:`irc3.plugins.core` Core plugin ============================================== Core events .. autoclass:: Core :members: .. >>> from irc3.testing import IrcBot Usage:: >>...
# -*- coding: utf-8 -*- import scrapy from myfirstpjt.items import MyfirstpjtItem class WeisuenSpider(scrapy.Spider): name = 'weisuen' allowed_domains = ['sina.com.cn'] start_urls = ( 'http://slide.news.sina.com.cn/s/slide_1_2841_103185.html#p=1', 'http://slide.news.sina.com.cn/k/slide_8_19...
import pandas as pd import os from cycifsuite.plate_based_analysis import per_well_analysis expr_data = pd.read_csv( 'example_input/sample_exprdata.csv', index_col=0) metadata = pd.read_csv( 'example_input/sample_metadata.csv', index_col=0) if not os.path.exists('example_output'): os.makedirs('example_outp...
class Test(): pass print(bool(Test))
# -------------- #Importing header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Path of the file data=pd.read_csv(path) data.rename(columns = {'Total':'Total_Medals'}, inplace = True) data.head(10) #Code starts here # -------------- #Code starts here data['Better_Event']=...
# Generated by Django 2.0.1 on 2018-02-06 20:18 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('PlanningBoard', '0010_planningcreate_created_at'), ] operations = [ migrations.AlterField( model_na...
import datetime from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from tabledef import * engine = create_engine('sqlite:///ap.db', echo=True) # create a Session Session = sessionmaker(bind=engine) session = Session() user = User("admin","admin") session.add(user) user = User("vanhoa",...
"""Script to run the Cognitive Debugging, Automated LFA Framework.""" __author__ = "tyronevb" __date__ = "2021" import argparse import sys sys.path.append("..") from src.lfa_framework import AutomatedLFAFramework # noqa if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run the Automated ...
class PagSeguroPhone: areaCode = None number = None def __init__(self, areaCode = None, number = None): if areaCode: self.areaCode = areaCode if number: self.number = number def getAreaCode(self): return self.areaCode def getNumber(self)...
# 1055. Shortest Way to Form String ''' From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions). Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossib...
import requests import json from data.url_data import URL class Login: def __init__(self, s): self.s = s self.url = URL() def login(self, data=None): """ 登录 """ if data: data = data else: data = {"username": "admin", "password": ...
def distribute_copula_spec(copula_spec, *keys): """This function distributes the copula specification.""" rslt = [] for key_ in keys: rslt += [copula_spec[key_]] return rslt
#!/usr/bin/env python # -*- coding: UTF-8 -*- from sgmllib import SGMLParser class GetBlogListPerPaper(SGMLParser): def reset(self): self.enter_dl = False self.enter_dt = False self.blogfeature = [] self.bloglist = [] SGMLParser.reset(self) def start_dl(self, attrs): for k,v in attrs: ...
from exts import db # class City(db.Document): # meta = {'collection': 'cities'} # key = db.StringField() # cities = db.ListField(db.StringField(),default=list) # class Movie(db.Document): # meta = {'collection': 'douban_movie'} # name = db.StringField() # actors = db.ListField(db.StringField(...
#!/usr/bin/env python #!-*-coding:utf-8 -*- #!@Time :2019/12/9 15:08 #!@File : .py # 将数据预处理并保存文件避免重复生成 from nltk.corpus import stopwords import os data_file = 'dataset.txt' path = "../data/" files = os.listdir(path) lines = [] # 读取数据 for file in files: filename = path + file with open(filename,"r") a...
import pyfirmata2 import sys def get_board(port): try: print("Initializing... ", end='', flush=True) board = pyfirmata2.Arduino(port) print("Arduino ready") return board except Exception as e: print ('{}\nNo Arduino found.'.format(e)) sys.exit() def init_pins_d...
# An if statement that is always false is called a contradiction. # You will rarely want to do this while programming, but it is # important to realize it is possible to do this. def always_false(num): if (num > 0) and (num < 0): return True else: return False print(always_false(0)) # should print False...
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_gradient(x): return sigmoid(x) * (1 - sigmoid(x)) def gradient_cross_entropy(x, t, w): return -x * (t - sigmoid(np.dot(w, x))) def hyberbolic_tangent(x): return np.tanh(x) def gradient_hyperbolic_tangent(x): return ...
import os import tempfile import transaction from onegov.core.utils import safe_move from typing import TYPE_CHECKING if TYPE_CHECKING: # NOTE: Technically this could be overwritten by anything that # satisfies the ITransaction interface, but we are happier # not having to deal with the zope....
import cv2 import numpy as np from PIL import Image class ColorTransfer: # content_img - image containing desired content # color_img - image containing desired color def __init__(self, content_img, color_img): self.content_img = content_img self.color_img = color_img def luminance_transfer(self, conv...
from flask import render_template, session, request, abort, redirect, Blueprint, url_for from werkzeug.security import generate_password_hash, check_password_hash from werkzeug import secure_filename import uuid import os from user.forms import RegisterForm, LoginForm, ForgotForm, EditForm, UsernameForm from stores.mo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thurs Jul 20 15:25:45 2019 @author: Maosong Pei """ import mappy as mp import argparse def parseArgs(): parser = argparse.ArgumentParser( description='compare assemblies with minimap2') parser.add_argument('-r', help='inp...
n1 = int(input('Primeiro valor:')) n2 = int(input('Segundo valor:')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 print('A soma vale {}, \n Multiplicação{} e A divisão {:.3f}'.format(s, m, d), end=' ') print('Divisao inteira {}, Potencia {}'.format(di, e))
from dateutil.parser import parse from onegov.gazette.models import Issue from textwrap import dedent def html_converter(text): return '<br>'.join((line.strip() for line in text.split('\n'))) class SogcConverter: """ The base class for all converters. """ def __init__(self, root): self.root = ...
from abc import abstractmethod class BaseDealWith: @staticmethod @abstractmethod def deal_with(params): pass
# Author: Avrahami (abraham.israeli@post.idc.ac.il), last update: 1.10.2020 #/usr/bin/python from __future__ import print_function import data import torch import numpy as np import os from torch import optim from etm import ETM from utils import prepare_embedding_matrix import commentjson from data_prep.arabic_twitte...
# -*- coding: utf-8 -*- # Module currently not in use. Yet future functionality is not discarded """ Created on Sat Aug 7 02:16:59 2021 @author: Dialvec """ #Specific functions import import utils #Packages importing missing_packages=[] try: import requests except ModuleNotFoundError: missing_packages.appen...
import discord import asyncio import random import openpyxl from discord import Member from discord.ext import commands import youtube_dl from urllib.request import urlopen, Request import urllib import urllib.request import bs4 import os import sys import json from selenium import webdriver import time ...
# General import torch import torch.nn as nn import torch.nn.functional as F # Setup from setups import CategoricalImageFlowSetup from setups.argparse import prep_int, prep_float, prep_str, prep_bool # Data from pixelflow.data import CategoricalImageNet32 # Model from pixelflow.flows import AutoregressiveSubsetFlow2...
from game.items.item import Ore class AdamantiteOre(Ore): type = 'Adamantite' name = 'Adamantite Ore' value = 400 weight = 2.721
import hashlib empty_file_md5_hex_str = 'd41d8cd98f00b204e9800998ecf8427e' def _calc_file_hash(hasher_name, file_path, return_hex): hasher = hashlib.new(hasher_name) with open(file_path, 'rb') as f: while True: bytes = f.read(1024) if len(bytes) > 0: hasher.up...
n = int(input()) mn = 0 for i in range(n, 1, -1): if n % i == 0: mn = i # print(mn) print(mn)
#Cafe Cafe Boxee App Parameters #### Ads Settings #### adSource = "local" #Use "local" or "rss" #If adSource is "local" this defines ads list localAdList = ["banner_dance_phoneYakir.gif", "lexidale.gif", "OurAdvertisment.gif", "sonic.gif", "banner_out_phoneGuy.gif", "TomVedan.gif"] # Durations and Intervals ### #...
# shellcode from pwn import * p=remote('124.126.19.106','49759') context(arch='amd64', os='linux', log_level='debug') p.recvuntil('secret[0] is ') v4_addr = int(p.recvuntil('\n')[:-1], 16) p.sendlineafter("What should your character's name be:", 'cxk') p.sendlineafter("So, where you will go?east or up?:", 'east') p.se...
import logging; _L = logging.getLogger('openaddr.ci.run_ec2_ami') from os import environ from time import time, sleep from argparse import ArgumentParser from .util import request_task_instance from .ci import setup_logger, log_function_errors from . import __version__ from boto import connect_autoscale, connect_ec2...
#!/usr/bin/env python """ A simple script to calculate some basic assembly stats.""" import sys import re if len(sys.argv) != 2: print "Usage: ./assembly.stats.py <assembly (fasta) file>\n" quit() assembly = open(sys.argv[1], "r") assembly_dict = {} scaffolds = 0 # Reads the assembly into a dictionary for ...
import os from wingedsheep.carcassonne.objects.connection import Connection from wingedsheep.carcassonne.objects.farmer_connection import FarmerConnection from wingedsheep.carcassonne.objects.farmer_side import FarmerSide from wingedsheep.carcassonne.objects.side import Side from wingedsheep.carcassonne.objects.tile i...
import numpy as np import matplotlib import matplotlib.pyplot as plt import operator from os import listdir def createDataSet(): group = np.array([[1.0,1.1], [1.0,1.0], [0,0], [0,0.1]]) labels = ['A', 'A', 'B', 'B'] return group, labels def classify0(inX, dataSet, labels, k): dataSetSize = dataSet.sh...
# coding=utf-8 from abit.models import AbitRequest, EducationalForm, Speciality, TestSubject from django.test.client import Client from django.test.testcases import TestCase from django_any import any_model #from functional_tests import FunctionalTest #from selenium.selenium import #from django.utils import unit...
from application.lib.instrum_classes import * class Instr(Instrument): """ Dummy instrument class for debugging purposes """ # creator function def initialize(self, arg1, arg2, kwarg1=100, kwarg2="toto", kwarg3="100", **kwargs): """ Initializes the dummy instrument. """ ...
''' Author: twsec Date: 2021-03-25 13:44:54 LastEditors: twsec LastEditTime: 2021-04-03 17:13:52 Description: 测试代码 ''' import socket import re import subprocess from bs4 import BeautifulSoup import requests import json import urllib.request import urllib.error import time import threading from fake_useragent...
def get_sample(nbits=3,prob=None,n=1): ''' purpose is to do this :param nbits: input, int, only for assert statement :param prob: input, dict, :param n: input, int :return: list ''' import random import math assert isinstance(nbits,int) assert nbits>=1 ass...
#!/usr/bin/env python # # Copyright (c) 2015-2016 IBM Corporation # # 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 appl...
#------------------------------------------------------------------------- # uiucinfometrics.py #------------------------------------------------------------------------- # Provides methods querying data from various UIUC websites. #------------------------------------------------------------------------- from Beautif...
import sqlalchemy import pandas as pd import requests from sqlalchemy import create_engine import multiprocessing import datetime from dbmanager import * from pathlib import Path from tqdm import tqdm DATA_PATH = Path('/mnt/volume_nyc1_02/videos_save') def download(tweet): id = tweet[0] url = tweet[1] t...
import numpy as np listas = [1, 2, 3] for i in listas: print(i) print(listas) print(testes)
import serial # Set the device file ser = serial.Serial('/dev/tty.usbserial') # Timeout is 5 seconds ser.timeout=5 # Yes, we will be using RTS and CTS (ready to send/clear to send) ser.rtscts = True # Give the command to the radio that asks for its ID print "Writing ID command..." ser.write('ID;') # Read the respo...
import time def fac(n): ret = 1 for x in range(2, n+1): ret *= x return ret digitFacs = [fac(n) for n in range(10)] def sumFacDigits(n): ret = 0 while n: ret += digitFacs[n % 10] #ret += fac(n % 10) n //= 10 return ret cache = dict() def chainLen(n): if n in cache...
### Add your imports here from matplotlib.dates import date2num import IncludeFile as IncF import mospat_inc_directories as IncDir import datetime as dt import logging import numpy as np import os from pandas import ExcelFile from INetwork import INetwork from aux_operations import naive_num2date, find from manip.t...
import pygame import random class Food: def __init__(self): self.foodPosition = [] def getFoodPosition(self, gui): self.foodPosition = random.choice(gui.field) def drawFood(self, win): pygame.draw.rect(win, (255, 0, 0), (self.foodPosition[0], self.foodPosition[1], 10, 10))
#! /usr/bin/env python import sys def main(): for line in sys.stdin: data = line.split('\t') key = data[0] value = 1 print >>sys.stdout, "%s\t%s" % (key, value) if __name__ == "__main__": main()
from filters import Filter from glob import glob import cv2 import matplotlib.pyplot as plt import numpy as np def main(): filter = Filter(model_file="model.p",scaler_file="scaler.p") image = cv2.cvtColor(cv2.imread(filter.test_video_images_path[0]), cv2.COLOR_BGR2RGB) filter.draw_one_box(image,120,(500,50...
#CSCI 1133 Homework 1 #Sid Lin #Problem 1C import turtle width = int(input("Enter a width:")) type(width) height = int(input("Enter a height:")) type(height) def drawRectangle(width, height): turtle.forward(width) turtle.left(90) turtle.forward(height) turtle.left(90) turtle.forward(width) turt...
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...