text stringlengths 8 6.05M |
|---|
import serial
import sqlite3
import psutil as ps
import time
try:
dbConn = sqlite3.connect('datalogger.db')
except:
print("could not connect to database")
#open a cursor to the database
cursor = dbConn.cursor()
device = 'COM18' #this will have to be changed to the serial port you are using
try:
print("Trying... |
# -*- coding: utf-8 -*-
import urllib, hashlib
from flask import Blueprint, render_template, request, redirect, url_for
from pygit2 import Repository
from pygit2 import init_repository
repo = Blueprint('repo', __name__)
@repo.route('/repositories/new', methods = ['GET'])
def new():
email = "jian.baij@gmail.com"
... |
dias = int(input('Quantos dias alugados? '))
km = int(input('Quantos Km rodados? '))
print('-'*25)
Pdias = (dias * 60)
PKm = (km * 0.15)
print("""Preço por dias: R${:.2f}
Preço por Km: R${:.2f}
Total: R${:.2f}""".format(Pdias, PKm, Pdias+PKm))
print('-'*25)
|
from flask import Flask, render_template, request, flash, redirect, url_for,send_file, make_response
import os
from canvasapi import Canvas
from werkzeug.utils import secure_filename
import requests
from water import water
import asyncio
API_URL = "https://canvas.oregonstate.edu/"
# Canvas API key
API_KEY = "1002~m1Sh... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" Link Management Packet (LMP) -related gateware. """
from amaranth import *
from usb_protocol.types.superspeed import HeaderPacketType, LinkManagementPacketSubtype
from ..l... |
import requests
r = requests.get("http://mobilelistings.tvguide.com/Listingsweb/ws/rest/schedules/80004.null/start/1517214600/duration/1440?ChannelFields=Name&ScheduleFields=ProgramId%2CEndTime%2CStartTime%2CTitle%2C&formattype=json")
data = r.json()
print(data)
channel = data[0]['Channel']
# program = [i[1]['ProgramS... |
class Serializer():
# ----------------------- SERIALIZATION ----------------------
def serialize(self, obj, filename="default"):
if filename != "default":
return self.dump(obj, filename)
else:
return self.dumps(obj)
# serializing python object to string
@classmet... |
import os
from urllib import request, parse
import time
from cluster import knn_detect,get_file_name
import copy
import shutil
# client_id 为官网获取的AK, client_secret 为官网获取的SK
# 获取token
def get_token():
client_id = 'j6qXAsKVzYtqoGGvX6tLoI15'
client_secret ='IpyFTwYKgsc5j9SkqmDXRnnsCiVV9IfQ'
host = 'h... |
from carbon_black.endpoints.base_endpoint import Endpoint
class Stats(Endpoint):
def __init__(self) -> None:
super().__init__()
return
def get(self) -> dict:
all_results = []
for data_item in self.config['nostradamus']:
db_result = self.query(
dat... |
# General Imports
import logging
import os
import database
import time
import threading
import sys
import ssl
from struct import unpack
# Socket Imports
import socket
import tqdm
import pickle
import csv
from config import SOCK
# MQTT Imports
import signal
import json
from time import sleep
import subprocess
import p... |
class Account(object):
def __init__(self,init_value):
self.init_value = init_value
self.value = self.init_value
self.credit_list = [self.value]
self.debit_list = [self.value]
self.last_credit = self.value
self.last_debit = self.value
def bind_stock(s... |
'''
imputationflask.model
-------------------
Database model
'''
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
HASH_STRING_SIZE = 128
COMMENT_STRING_SIZE = 1000
EMAIL_STRING_SIZE = 254
db = SQLAlchemy()
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=... |
import time
from tempmail import TempMail
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def __init__(self):
super().__init__()
self.result = []
def handle_starttag(self, tag, attrs):
# Only parse the 'anchor' tag.
if tag == "a":
# Check the li... |
from rest_framework import generics, status
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.authentication import (JSONWebTokenAuthentication,
get... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
last mod 7/17/19
Determines the 3m x 3m tiles that are most important to apply object detection on.
This can be used to speed up an object detector, at the cost of lowered accuracy
because of missed detections (but that's the reason to carefully choose tiles to miss).... |
class Solution(object):
def minimumTotal(self, triangle):
if triangle == None:
return 0
if len(triangle) == 1:
return triangle[0][0]
for i in range(1, len(triangle)):
k = len(triangle) - i - 1
for j in range(0, len(triangle[k])):
if triangle[k][j] + triangle[k+1][j] > triangle[k][j] + triangl... |
import sys
import time
import Queue as q
from core import DefaultProcess
class Discoverer(DefaultProcess):
def __init__(self,
name='Discoverer',
queue=None,
shutdown=None,
config=None,
collectors=None):
DefaultProcess.__i... |
from tkinter import *
from PIL import Image, ImageTk
import numpy as np
import cv2
import os
import shutil
from run_all_models import run_all
from test import ESR_gan
import os.path as osp
import glob
import cv2
import numpy as np
import torch
import RRDBNet_arch as arch
#orig1.jpeg lady with hat
#orig2.jpeg scenery
#... |
from openpyxl import Workbook
from openpyxl import load_workbook
from zlib import crc32
import sys
import glob
import logging
import xml.etree.ElementTree as ET
def GetCrc32(filename): # calculate crc32
with open(filename, 'rb') as f:
return crc32(f.read())
def strnset(str,ch,n): # string change
str = ... |
import smbus
# Power management registers
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
def read_byte(adr):
return bus.read_byte_data(address, adr)
def read_word(adr):
high = bus.read_byte_data(address, adr)
low = bus.read_byte_data(address, adr+1)
val = (high << 8) + low
return val
d... |
#!/usr/bin/env python
from main.page.desktop_v3.purchase.pe_tx_payment_base import *
from selenium.webdriver.common.by import By
class TransactionListPage(TxPaymentBasePage):
_page = "tx_order_list.pl"
#LOCATORS
#Search Invoice
_search_invoice_bar_loc = (By.CSS_SELECTOR, 'div.row-fluid form#form-filt... |
"""
=================
Typenames
=================
[User]
* GraphUser
[Hashtag]
* GraphHashtag
[Post]
* GraphSidecar -> combination of videos or/and images
- GraphImage
- GraphVideo
[Story]
* GraphReel -> user story
* GraphHighlightReel -> user's story highlights
* GraphMASReel -> hashtag story
- GraphStoryIma... |
#!/usr/bin/env python
# encoding: utf-8
# @author: Zhipeng Ye
# @contact: Zhipeng.ye19@xjtlu.edu.cn
# @file: filter_gram2.py
# @time: 2020-01-16 18:43
# @desc:
import os
import codecs
import sys
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
def verifyContent(words, word_set):
for word in words:
... |
import random
from tkinter import Tk, Canvas
def create_board(width, height):
columns = []
for i in range(height):
row = []
columns.append(row)
for i in columns:
for n in range(width):
i.append(None)
gameboard = columns
return gameboard
def bury_mines(gameboard, n):
mine_counter = 0... |
X, Y = input().split()
X = int(X)
Y = int(Y)
V = [4.00, 4.50, 5.00, 2.00, 1.50]
print('Total: R$ {:.2f}'.format(V[X-1]*Y)) |
#
# Copyright 2008-2009, Blue Dynamics Alliance, Austria - http://bluedynamics.com
#
# GNU General Public Licence Version 2 or later
__author__ = """Robert Niederreiter <rnix@squarewave.at>"""
__docformat__ = 'plaintext'
import logging
logger = logging.getLogger('IntelliDateTime')
logger.info('Installing Product')
f... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" Endpoint interfaces for working with streams.
The endpoint interfaces in this module provide endpoint interfaces suitable for
connecting streams to USB endpoints.
"""
fro... |
import admincommands, usercommands, supercommands, re, actions, spelling
# DEVELOPER: https://github.com/undefinedvalue0103/nullcore-1.0/
vk = None
config = None
logging = None
utils = None
def init():
usercommands.vk = vk
admincommands.vk = vk
supercommands.vk = vk
actions.vk = vk
... |
# Arrays: Left Rotation
# Cracking the Coding Interview Challenge
# https://www.hackerrank.com/challenges/ctci-array-left-rotation
def array_left_rotation(a, n, k):
# Initialize
answer, rotations, count = [], k, 0
# Begin new array from point in old array
while rotations < len(a):
answer.a... |
def SumSquares(lst):
""" sum_squares == PEP8 (forced PascalCase by Codewars) """
try:
return sum(SumSquares(a) for a in lst)
except TypeError:
return lst ** 2
|
# coding our association rules algorithm into python notes
'''
our algorithm essentially manipulates our tables T and C with counts
how do we store these tables?
we do not want to store all of the pairs if we don't have to (keeps Table T lean)
we want our table to be sparse (many entries will be 0 and not need to be s... |
import math
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.optimizer import Optimizer
class CyclicLR(_LRScheduler):
"""Sets the learning rate of each parameter group according to
cyclical learning rate policy (CLR). The policy cycles the learning
rate between two boundaries with a con... |
from utils.function.setup import *
from utils.lib.user_data import *
from main.activity.desktop_v3.activity_login import *
from main.activity.desktop_v3.activity_logout import *
from main.activity.desktop_v3.activity_user_settings import *
import unittest
class TestBank(unittest.TestCase):
# Instance
_site = ... |
#-*-coding=utf-8-*-
"""FirstDjango URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.hom... |
from enum import Enum
from typing import Optional
import numpy as np
from pydantic import PrivateAttr, validator
from napari.utils.color import ColorArray
from napari.utils.colormaps.colorbars import make_colorbar
from napari.utils.events import EventedModel
from napari.utils.events.custom_types import Array
from nap... |
from django.conf.urls import url
from django.contrib import admin
from blog import views
admin.autodiscover()
urlpatterns = [
url(r'^$', views.writing, name='writing'),
url(r'^tags/(?P<tags>.+)/$', views.tags, name='tags'),
url(r'^search/$', views.search, name='search'),
url(r'^(?P<category>\w+)/$', ... |
import unittest
from idstools import maps
class SignatureMapTestCase(unittest.TestCase):
def test_load_generator_map(self):
sigmap = maps.SignatureMap()
sigmap.load_generator_map(open("tests/gen-msg.map"))
sig = sigmap.get(1, 1)
self.assertTrue(sig is not None)
self.asse... |
def get_sign(x):
if x[0] in '+-':
return x[0]
arr = ['в', '5', 'часов', '17', 'минут', 'температура', 'воздуха', 'была', '+5', 'градусов']
i = 0
while i < len(arr):
sign = get_sign(arr[i])
if arr[i].isdigit() or (sign and arr[i][1:].isdigit()):
if sign:
arr[i] = sign + arr[i][1:]... |
from django.contrib import admin
from .models import Game, Score, RoundScore, Player
admin.site.register(Player)
admin.site.register(Game)
admin.site.register(Score)
admin.site.register(RoundScore)
|
# __all__ = [
# 'main',
# 'processPrefixes',
# 'processProperties',
# 'processInfosheet',
# 'processDictionaryMapping',
# 'processCodebook',
# 'processTimeline',
# 'processData',
# 'sdd2setl'
# ]
#from .sdd2rdf import *
from .sdd2setl import sdd2setl, sdd2setl_main
from .sddmarkup i... |
""" script to check, if there can be a delayed signal without a neutron in the events of user_atmoNC_.root:
To get a delayed signal, there should be at least one neutron in the event. But to check this, around 1000 events
with no neutron from user_atmoNC_.root must be analyzed and checked for a delayed signal.... |
from data_load import data_list
query=input("query: ")
query = query.strip(" ").split()
query = list(set(query))
if ("or" in query) and ("and" not in query):
query.remove("or")
print("Performing OR search for: ", query)
for i, quote in enumerate(data_list):
... |
from torch import einsum
from backpack.extensions.firstorder.base import FirstOrderModuleExtension
class BatchL2Linear(FirstOrderModuleExtension):
def __init__(self):
super().__init__(params=["bias", "weight"])
def bias(self, ext, module, g_inp, g_out, backproped):
C_axis = 1
return ... |
import os
import sys
import glob
import numpy as np
def extract_likelihoods(results_dir, verbose = True):
ll1 = 0
ll2 = 0
improve = 0
treated = 0
diffs = []
maxdiff = 0.0
maxfam = ""
for stats in glob.glob(os.path.join(results_dir, "*.stats")):
#if ("14014_" in stats):
# continue
lin... |
from flask import Blueprint, flash, request, redirect, url_for, render_template
from flask import json
from labcheckin.models import Seat, Student, Transaction
from labcheckin import db
from labcheckin.utilities import parse_card, utc2local
from datetime import datetime
from labcheckin.models import Seat
main = Bluep... |
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.home, name='home'),
path('products/<pk>/', views.ProductDetailView.as_view(), name='product-detail'),
path('products/categories/<pk>/', views.Category... |
#
# @lc app=leetcode.cn id=116 lang=python3
#
# [116] 填充每个节点的下一个右侧节点指针
#
# @lc code=start
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = righ... |
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QWidget, QMainWindow, QTableWidgetItem, QAbstractItemView, QDesktopWidget
from PyQt5.QtGui import QColor
from template import Ui_main_window
import get_data
from subprocess import call
class game_viewer(QMainWindow):
def __init__(self, parent=None):
... |
import os
import sys
import re
class Shift:
def __init__(self, day, guard):
self.day = day
self.guard = guard
#self.onDuty = ['.'] * 60 # minutes
self.onDuty = [0] * 60 # minutes
def setup():
global fileHandle, fileData
filename = input("Enter an input file name: ")
ex... |
import numpy as np
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input
from keras.models import Model
from PIL import Image as PIL_Image
from pelops.features.feature_producer import FeatureProducer
# Use global so we only load... |
#!usr/bin/env python
# -*- coding: utf-8 -*-
"""
Entries as classes
"""
from src.DB.Model import Model
class Page(Model):
table = 'page_content' # table name is page_content
fields = ['id', 'url', 'content']
class Url(Model):
table = 'cached_url' # table name is page_content
fields = ['url']
|
"""
Faça um Programa que leia três números e mostre-os em ordem decrescente.
"""
def obter_numero_inteiro(msg):
return int(input(msg))
def obter_numero_maior(numero_1, numero_2, numero_3):
if numero_1 >= numero_2 and numero_1 >= numero_3:
return numero_1
elif numero_2 >= numero_1 and numero_2 >=... |
#!/usr/bin/env python
# coding: utf-8
import requests
import json
import argparse
# 获取access_token用于鉴权
def get_access_token(client_secret, client_id):
grant_type = "client_credentials"
url = "https://openapi.data-baker.com/oauth/2.0/token?grant_type={}&client_secret={}&client_id={}"\
.format(grant_ty... |
import sys
if len(sys.argv) == 1:
print('Input filename:')
f=str(sys.stdin.readline()).strip()
else: f = sys.argv[1]
data = []
for l in open(f):
data.append(l.strip())
def step(d, mx, my, xl, yl, x=0, y=0, c=0):
x = (x + mx) % xl
y = y + my
if '#' == d[y][x]: c += 1
return c if y == yl-1 else step(d... |
resources = {}
while True:
item = input().lower().split()
if item[0] == 'total':
break
key = item[0]
value = item[1]
if key in resources:
resources[key] += int(value)
else:
resources[key] = int(value)
for element in sorted(resources):... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 17 19:33:38 2017
Contains the Agent class and functions of it
@author: paula
"""
import random
class Agent():
#x = random.randint()
#y = random.randint()
agents = []
environment = []
def __init__(self, environment, agents):
self.x = ran... |
def gameStart() :
loop = False
while (loop == False) :
print ('What do you want to play?')
print ('1.) Single player')
print ('2.) 2 Player')
print ('3.) How to play')
print ('Please choose number do you want')
number = input()
if nu... |
import numpy as np
np.random.seed(1234)
#Original class given by the paper
class Driving(object):
def __init__(self, num_lanes=5, p_car=0.16, p_cat=0.09, sim_len=300, ishuman_n=False, ishuman_p=False):
self.num_lanes = num_lanes
self.road_length = 8
self.car_speed = 1
self.cat_spe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
""" Error classes used for database models"""
class UserEmailError(AttributeError):
def __init__(self, email, *args, **kwargs):
self.message = "E-mail: {} is already taken!".format(email)
super().__init__(args, kwargs)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 16-12-4 下午8:52
# @Author : sadscv
# @File : chunkFreatures.py
import nltk
from chunkFreatures import npchunk_features_ultimate as \
npchunk_features
class ConsecutiveNPChunkTagger(nltk.TaggerI):
def __init__(self, train_sents):
"""
... |
from django.db import models
import datetime
class Region(models.Model):
nombre = models.CharField(max_length=100)
def __str__(self):
return self.nombre
#asdasd
class Ciudad(models.Model):
nombre = models.CharField(max_length=100)
region = models.ForeignKey(Region, on_delete=models.CASCADE, b... |
from Character import Character
from data import features
class FighterClass(Character):
def __init__(self, params):
super().__init__(params)
# self.stamina = params['stamina']
# self.combat_skill = params['combat_skill']
def fight_auto_attack(self, enemy):
damage = 0
... |
#!/usr/bin/python3
import os
import sys
if len(sys.argv) == 1:
print('错误!请传入 xml 文件')
elif len(sys.argv) > 2:
print('错误!传入参数太多')
else:
print('传入的文件是 %s' % sys.argv[1])
with open(sys.argv[1], 'r') as fin:
while True:
linestr = fin.readline()
if linestr == '': #表示文件结束
... |
import os
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
from db.sqlite3_connect import select_data, insert_data
from custom_gestures import gesture_nd as gesture
from utils.common import num_of_word_to_study
class ImageButton... |
import os
import threading
import socket
import sys
import struct
import time
lock = threading.Lock()
class clientreceiver(threading.Thread):
def __init__(self, hostname, port, clientsocket, packet, seqnum):
threading.Thread.__init__(self)
self.port = port
self.hostname = hostname
s... |
from django.conf.urls import url
from ad_hoc_scripts.ad_hoc_scripts import *
from api_views import *
urlpatterns = [
url(r'^getnews', GetNewsRecordView.as_view(),name="get_news_results"),
url(r'^updatenewstactical', UpdateNewsView.as_view(),name="update_news_view"),
url(r'^scorecalcultaions', ScoreCalculat... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\FindIDWindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCor... |
from tkinter import *
# Initializing root
root = Tk()
myLabel1 = Label(root, text='Write some text here!')
myLabel2 = Label(root, text='Something more...')
myLabel1.pack() # Can use grid(row=0, column=0) instead aswell.
myLabel2.pack()
root.mainloop() |
import configparser
import io
import json
import os
import re
import threading
import zipfile
from pathlib import Path
from wsgiref.util import FileWrapper
import pymysql
from datetime import datetime
from django.core import serializers
from django.core.paginator import Paginator, PageNotAnInteger, EmptyP... |
from django.shortcuts import render, reverse, HttpResponseRedirect
from .forms import CustomUserCreationForm
from django.contrib.auth import authenticate, login, logout
def sign_up(request):
"""
Task:
- if this is a POST request we need to process the form data
- create a form instance and populate it... |
from odoo import models, fields
class SaleReport(models.Model):
_inherit = 'sale.report'
contract_id = fields.Many2one('sale.contract', 'Contract', readonly=True)
def _query(self, with_clause='', fields={}, groupby='', from_clause=''):
fields['contract_id'] = ", s.contract_id AS contract_id"
... |
""" Harry Potter Sorting Hat Quiz by Ryan Smith.
This project is for my class COP 1500 Intro to Computer Science.
The purpose of this project is to have a demonstration of the knowledge
I accumulated during this semester.
Sources: Descriptions of each House Source:
https://harrypott... |
class Solution:
def maximumSafenessFactor(self, grid: List[List[int]]) -> int:
dist = [[float('inf')]*len(grid[0]) for _ in range(len(grid))]
q = collections.deque()
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
... |
import json
import sys
from devtools import debug
def handle(event, context) -> dict:
"""
Escalates or de-escalates depending on the incoming event type.
For more details on the event object format, refer to our reporting docs:
https://docs.symops.com/docs/reporting
"""
print("Got event:")
... |
from django.shortcuts import render, redirect
from django.contrib import messages
from django.core.urlresolvers import reverse
from .forms import RegisterForm, LoginForm
from .models import *
from ..home.models import *
import stripe, datetime
# Create your views here.
def index(request):
if 'user' in request.ses... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s, n):
qntd = int(n/len(s)) * s.count("a")
resto = n % len(s)
qntd += s[0:resto].count("a")
return qntd
if __name__ == '__main__':
s = "aba"
n = 10
result... |
value = raw_input()
print any([c.isalnum() for c in value])
print any([c.isalpha() for c in value])
print any([c.isdigit() for c in value])
print any([c.islower() for c in value])
print any([c.isupper() for c in value]) |
"""
注释:
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-10, 11, 1)
plt.plot(x, x**2, 'r--')
# 方法:plt.annotate()
plt.annotate('this is bottom', xy=(0, 1), xytext=(0, 20),
arrowprops=dict(facecolor='r', headlength=5, headwidth=10, width=5))
# xy用于指定箭头的位置,xytest用于指定注释的位置,arrowprops用于配置箭... |
"""
Given a directed graph, design an algorithm to find out whether there is a route between two nodes
"""
def route_between_nodes_using_dfs(graph, start, end):
visited = set()
import pdb; pdb.set_trace()
def dfs(node):
if node == end:
return True
visited.add(node)
for neigh in graph.get(node, []):
... |
# see http://effbot.org/zone/simple-top-down-parsing.htm
import sys
import re
if 1:
class literal_token:
def __init__(self, value):
self.value = value
def nud(self):
return self
def __repr__(self):
return "(literal %s)" % self.value
class operator_... |
# Generated by Django 2.2.6 on 2020-01-31 03:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('consumers', '0011_consumer_consumer_id'),
]
operations = [
migrations.AlterUniqueTogether(
name='consumer',
unique_together=... |
import os
class SoundPlayer:
def __init__(self):
self.pause_file = "/home/pi/spotify_dj/Assets/brute-force.mp3"
self.skip_file = "/home/pi/spotify_dj/Assets/SkipTone.mp3"
self.boot_file = "/home/pi/spotify_dj/Assets/bootup.mp3"
def play_pause_tone(self):
os.system("mpg32... |
import time
import numpy as np
from State import State
from constants import move_action_to_deviation, Action
import random
class Oracle:
def __init__(self, window_width, window_height, step_size, goal_config, init_state):
self.window_width = window_width
self.window_height = window_height
... |
from fid import fid
from kid import kid_kid, kid_is
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-m", "--metric", dest="metric", default="all",
help="Set batch size to use for InceptionV3 network",
type=s... |
x=float(input("x= "))
y=4*(pow((x-3),6))-7*(pow((x-3),3))+2
print(y) |
#!/usr/bin/env python3
import dadi
import dadi.NLopt_mod
import nlopt
def three_epoch_noF(params, ns, pts):
"""
params = (nuB,nuF,TB,TF)
ns = (n1,)
nuB: Ratio of bottleneck population size to ancient pop size
nuF: Ratio of contemporary to ancient pop size
TB: Length of bottleneck (in units of... |
"""Partial derivatives for the SELU activation function."""
from torch import exp, le, ones_like, zeros_like
from backpack.core.derivatives.elementwise import ElementwiseDerivatives
class SELUDerivatives(ElementwiseDerivatives):
"""Implement first- and second-order partial derivatives of SELU."""
alpha = 1.... |
#-*-coding:utf-8-*-
"""
"创建者:Li Zhen
"创建时间:2019/4/1 8:48
"描述:TODO
"""
import torch
from torch.nn import Linear, Module, MSELoss
from torch.optim import SGD
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
print(torch.__version__)
#%%
x = np.linspace(0,... |
"""
Support for broadlink remote control of a media device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.broadlink/
"""
import asyncio
from base64 import b64decode
import binascii
import logging
import socket
from math import copysign
fr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-14 14:42
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('teams'... |
# Use the QuickSelect Algorithm to find the k-th largest element of an array
import random
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def kthlargest(arr, k):
n = len(arr)
def partition(start, end, ind):
""" Rearranges arr[start:end] so that everything to
the left of arr[pivot] is... |
#import time
class Fremoga:
def __init__ (self, name):
#adding characteristics
self.name = name
self.age = 13
self.connect = []
def born (self, age):
if age < 13:
print ("This is a big kid website. Go play outside.")
else:
print ... |
# -*- coding: utf-8 -*-
from project_name import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'filters': {
# 'require_debug_false': {
# '()': 'django.utils.log.RequireDebugFalse'
# }
# },
# 'handle... |
import Image
class Resize:
def __init__(self, max_scale, height):
self.max_scale_ = max_scale
self.height_ = height
def image(self, name, width_resize):
image_file = Image.open("fon.jpg")
image_file.thumbnail((width_resize, width_resize))
image_file.save(name)
def... |
'''
get specific number(--num) images from a folder(--input_dir), rename these images(--prefix), turn them to destination folder(save_dir)
'''
import sys
from glob import glob
import os
import argparse
import scipy.misc
parser = argparse.ArgumentParser()
parser.add_argument('--input_dir', type=str, default='', help=''... |
import time
class Solution:
def countPrimes(self, n):
if n<2:
return 0
#生成长度为n的list
isPrime=[1]*n
isPrime[0],isPrime[1]=0,0
for i in range(2,int(n**0.5)+1): #遍历2-根号n
#如果i为质数,所有i的倍数为0
if isPrime[i]:
isPrime[i**2:n:i]=[0]*((n... |
from django.db import models
class Vmhost(models.Model):
name=models.CharField(max_length=200)
virtType=models.CharField(max_length=200)
class Guest(models.Model):
vmhost= models.ForeignKey(Vmhost)
name=models.CharField(max_length=200)
currCpu=models.CharField(max_length=200)
currMemory=models.CharField(max_l... |
# -*- coding: utf-8 -*-
""" Classe definissant une delivery (mission) caracterisee par :"""
#- son nom
#- la position de destination
#- l'id du drone auquel est affecte la mission courante
#- l'id du stock d'ou vient le colis
#- l'id du colis
#- le statut de la mission
# Etat de la livraison
import time
class Deliver... |
from django.db import models
from djutil.models import TimeStampedModel
from edtech.models.mixins import DefaultPermissions
from edtech.models.test_series import TestSeries
from edtech.models.topic import Topic
class Question(TimeStampedModel, DefaultPermissions):
description = models.TextField()
diagram = m... |
"""
红黑树查询,红黑树真的不好理解啊
"""
"""
红黑树的五条性质:
1)任何一个节点非红即黑;
2)树的根为黑色;
3)叶子节点为黑色(注意:红黑树的所有叶子节点都指的是Nil节点);
4)任何两个父子节点不可能同时为红色;
5)任何节点到其所有分枝叶子的简单路径上的黑节点个数相同;
红黑树通过上述五条性质,保证整棵树的黑色节点数量平衡,使得红黑树是一个红黑平衡树,尽可能平衡的二叉树的搜索速度是非常快的。
上亿条数据,通过简单的几十次对比就能找到需要的数据,确实非常厉害了。
"""
class Entity(object):
'''数据实体,假设这是一种数据存储的结构'''
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.