text stringlengths 8 6.05M |
|---|
# OpenCV bindings
import cv2
# To performing path manipulations
import os
# Local Binary Pattern function
from skimage.feature import local_binary_pattern
# To calculate a normalized histogram
from scipy.stats import itemfreq
from sklearn.preprocessing import normalize
# Utility package -- use pip install cvutils to i... |
'''
Koko 每小时最多吃一堆香蕉,如果吃不下的话留到下一小时再吃;
如果吃完了这一堆还有胃口,也只会等到下一小时才会吃下一堆。
在这个条件下,让我们确定 Koko 吃香蕉的最小速度(根/小时)
'''
# 第一版解法
def min_eating_speed_1(piles, hour):
max_num = max(piles)
speed = 1
while speed <= max_num:
if can_finish(piles, speed, hour):
return speed
speed += 1
return max_num
# 第二版解法
def min_eating_... |
import pytest
import sort
def test_my_bs():
res = [2,1,2,8,5,0,6]
assert my_sort.bubble_sort(res) == sorted(res)
def test_my_qs():
res = [2,1,2,8,5,0,6]
assert my_sort.quick_sort(res) == sorted(res)
|
from enum import IntEnum
COMMAND_HEAD = b"\x6a\xa6"
COMMAND_TYPE_OUTPUT_CTR = 0x01
COMMAND_TYPE_READ = 0xFE
class Command(IntEnum):
OUTPUT_CTR = 0x01
DEVICE_TIME = 0x02
TAP_TIME = 0x03
DELAY_TIME = 0x04
MODBUS_ADDRESS = 0x05
OUTPUT_STATE = 0x06
INPUT_STATE = 0x07
CYCLE_TIME = 0x08
... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import hashlib
import json
from collections import OrderedDict
from enum import Enum
import pytest
from pants.base.hash_utils import CoercingEncoder, hash_all, json_hash
from pants.util.... |
from tkinter import *
from tkinter import messagebox
import sqlite3
from sqlite3 import Error
from tkinter import ttk
import pandas as pd
import random
import os
from PIL import ImageTk,Image
pd.set_option('display.max_columns', None)
pd.set_option('expand_frame_repr', False)
conn = sqlite3.connect('B:\StudyMaterials... |
import sys
import json
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import jsonlines
import math
import numpy as np
costhetas = []
for i,e in enumerate(jsonlines.Reader(open(sys.argv[1]))):
els = [p for p in e['particles'] if p['id'] == 11]
mus = [p for p in e['particles'] if p['id'] == ... |
def a(n):
if n==1:
return 1
return n*a(n-1)
def b(n):
s=1
for i in range(1,n+1):
s=s*i
return s
if __name__=='__main__':
print b(4)
print a(5) |
media = mediaF= maior = cont = 0
menor = 99999999
ans = 's'
listN = []
while ans == 's':#ou while ans in 'Ss'
cont += 1
n = int(input('Digite um valor: '))
listN.append(n)
ans = str(input('Deseja continuar? [S/N]: ')).lower()
media += n
if n > maior:
maior = n
if n < menor:
m... |
from rest_framework import generics
from rest_framework.generics import get_object_or_404
from .models import Livro
from .serializers import LivroSerializer
class LivrosAPIView(generics.ListCreateAPIView):
queryset = Livro.objects.all()
serializer_class = LivroSerializer
class LivroAPIView(generics.Retrieve... |
import VdManalyze as v
detectors = ['PLT','HFET', 'HFOC']
detector = 'PLT'
folder = '/brildata/vdmoutput/Automation/Analysed_Data/'
bcmfolder = '/brildata/vdmoutput/Automation/Analysed_Data/'
print detector, 'all'
df = v.load_all([detector], main_folder=bcmfolder, forcemodel=True)
df.to_csv(detector + '_const_2017.cs... |
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D, Input, AveragePooling2D, GlobalAveragePooling2D, Concatenate
from keras.regularizers import l2
from keras.layers.normalization import BatchNormalization
import k... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-03-15 09:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quicklook', '0007_exerciseandreporting_did_workout'),
]
operations = [
migr... |
# Generated by Django 3.0.5 on 2020-08-03 22:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mobileapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Document',
fields=[
('id... |
def esaustivo(n):
'''Stampa tutte le permutazioni dei numeri da 0 a n - 1 con numeri pari
nelle posizioni pari.'''
def check(cifre):
for i in range(len(cifre)):
if not i % 2 and cifre[i] % 2:
return False
return True
def genera(cifre, utilizzate):
if... |
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'client address:', addr
c.send('welcome to cainiao jiaocheng')
c.close()
|
import json
import re
import sys
import traceback
import typing
from datetime import datetime
import yaml
from flask import Flask, request, abort
from matrix_client.client import MatrixClient
from matrix_client.errors import MatrixRequestError
application = Flask(__name__)
# Not going to care for specifics like the ... |
from django.shortcuts import render
from rest_framework import viewsets, views, mixins, status, permissions, generics
from rest_framework.response import Response
from .models import LinkShop
from .serializers import LinkShopSerializer
from tracking.settings import DEFAULT_IDENTIFIER_SHOP
# Create your views here.
cl... |
from ckeditor.fields import RichTextField
from django.contrib.auth import get_user_model
from django.db import models
# Create your models here.
class Term(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='terms')
school = models.CharField(max_length=20, blank=F... |
# Python program to print all prime numbers
start = input("Enter the start number: ")
end = input("Enter the end number: ")
for i in range(start,end):
if i>1:
for j in range(2,i):
if(i % j==0):
break
else:
print(i) |
from . import nx_agraph as nx_agraph, nx_pydot as nx_pydot
from .layout import *
from .nx_latex import *
from .nx_pylab import *
|
# -*- coding: cp936 -*-
# import pygame
import wx
import os
import win32com.client
# import keyevent
import server
import threading
import httpserver
window_size = (420,350)
button_size = (80,80)
filelist_size = (350,200)
frame_colour = wx.Colour(255,255,255)
text_colour = wx.Colour(40,139,213)
... |
from collections import OrderedDict
from treadmill.infra.setup import base_provision
from treadmill.infra import configuration, constants, exceptions, connection
from treadmill.api import ipa
class Zookeeper(base_provision.BaseProvision):
def setup(self, image, key, cidr_block, instance_type,
ipa_a... |
import cross_deletions_with_dgv_results_Vfor_new
from collections import OrderedDict
from openpyxl import Workbook
from openpyxl.comments import Comment
from openpyxl.styles import Font, Fill, PatternFill, Alignment
from openpyxl.styles.borders import Border, Side
def make_reg_to_test(params, chrr, start,end):
dic={... |
#!/usr/bin/env python3
import subprocess
# import optparse
#
# parser = optparse.OptionParser()
# parser.add_option("-i", "--interface", dest="interface", help="Interfae to change it's Mac_Address.")
# parser.add_option("-m", "--mac", dest="mac_address", help="New Mac_Address.")
# (options, arguments) = parser.parse_ar... |
"""
Created on Fri Sep 6 09:24:55 2019
@author: Fenrir
function
math function明示的な注記のない限り、戻り値は全て浮動小数点数になります。
https://docs.python.org/ja/3/library/math.html#module-math
"""
import math
'''
int(x)
文字列を数値に変換するにはint()を使います。
'''
x = "7"
print(10 + int(x))
'''
float(x)
文字列を浮動小数点数に変換するにはfloat()を使います。
'''
x = "1.25"
print... |
#!/usr/bin/python
import sys
# Represents how we define a question.
class Question:
# Question identifier
id = None
# Related users
users = []
def __init__(self, id, author):
self.id = id
self.users = [int(author)]
# Add an user.
def addUser(self, user):
self.users.append(int(user))
# P... |
# -*- coding: utf-8 -*-
a=int(input())
if a % 2 == 0:
print(a,"is an even number.")
else:
print(a,"is not an even number.")
|
from Player import Player
class SmartPlayer(Player):
"""
Player that makes decisions based on logic written down
The main goal is to create an artificial intelligence that can
play Hearts, but for now, we need a basis on how to play
in order to create a ranking system with ELO
"""
def take_turn(self, initi... |
class Drone(object):
"""docstring for Drone"""
def __init__(self, x,y,storageCapacity,ID,weightList):
super(Drone, self).__init__()
self.x = x
self.y=y
self.storageCapacity=storageCapacity
self.ID=ID
self.items={}
self.currentWeight=0
self.weightList=weightList
def addItem(self,nbItem,itemID):
if ... |
# -*- coding:utf-8 -*-
#FND.py
import smbus
import time
import threading
bus = smbus.SMBus(1)
#FND configuration
addr_fnd = 0x20
config_port = 0x06
out_port = 0x02
data_fnd = (0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0x3E, 0xE0, 0xFE, 0xF6, 0x01,0x02,0x1A)
digit = (0x7F, 0xBF, 0xDF, 0xEF, 0xF7, 0xFB)
out_disp = 0
... |
"""
Split a compressed text file into multiple smaller (compressed) text files.
"""
import gzip
import bz2
import lzma
from itertools import islice
import click
from . import cli
COMP_OPEN = {"gzip": gzip.open, "bz2": bz2.open, "xz": lzma.open, "text": open}
COMP_OPTIONS = list(COMP_OPEN.keys()) + ["infer"]
def ... |
# with open(r"C:\Users\admin\OneDrive\デスクトップ\python1\07\example.txt", encoding="sjis") as file:
# print(file.readline().rstrip("\n"))
# print(file.readline().rstrip("\n"))
# print(file.readline().rstrip("\n"))
with open(r"C:\Users\admin\OneDrive\デスクトップ\python1\07\numbers.txt", encoding="sjis") as file:
a ... |
# Generated by Django 2.1.1 on 2018-09-08 05:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
... |
from braindecode.datasets.filterbank import generate_filterbank
import numpy as np
import pytest
def test_generate_filterbank():
filterbands = generate_filterbank(min_freq=2, max_freq=16,
last_low_freq=8, low_width=6, low_overlap=4,
high_width=10, high_overlap=6, low_bound=0.2)
assert np.array_... |
# _*_ coding: utf-8 _*_
import ta
import os
import sys
import warnings
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
warnings.filterwarnings("ignore")
import pandas as pd
class TechnicalAnalysis(object):
def __init__(self, data, window_size):
self.data = data
... |
from . import fleet
def connect() -> None:
"""
Connect to fleet signals to make tracking react to it
"""
fleet.connect()
|
from math import sqrt
def problem32():
nums = set()
for i in range(1, 10000):
for k in range(2, int(sqrt(i)) + 1):
if i % k == 0:
pandi = str(i) + str(k) + str(i//k)
if ordstr(pandi) == "123456789":
nums.add(i)
return sum(nums)
def or... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('news.views',
url(r'^$', 'news', name='news'),
url(r'^(?P<post_id>\d+)/$', 'one_new', name='one_new'),
) |
# Generated by Django 2.2.1 on 2019-06-21 16:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('questi', '0018_prof_class'),
]
operations = [
migrations.AlterField(
model_name='questions',
name='quest',
... |
print ('menentukan bilangan terbesar')
print ('menentukan 3 bilangan yang diinginkan')
a = int (input ('bilangan pertama ='))
b = int (input ('bilangan kedua ='))
c = int (input ('bilangan ketiga ='))
if a>b and a>c :
print ('bilangan terbesar =',a)
elif b>a and b>c :
print ('bilangan terbesar =',b)
else :
... |
from data_structures import Shot
import numpy as np
from scipy.io import wavfile
import re
from sys import argv
import os, sys
import glob
import evaluate_method
import multiprocessing
import time
import random
import json
sys.path.insert(0, 'document_similarity/')
from document_similarity import DocSim
from gensim.mod... |
import math
b = float(input("Entre com o 1o. cateto: "))
c = float(input("Entre com o 2o. cateto: "))
a = math.sqrt(b**2 + c**2)
print ("A hipotenusa é: ",a)
|
import pandas as pd
url = "data_v3.csv"
insider = pd.read_csv(url, header=0)
print insider.shape
row_num = insider['side'].count()+1
train_num = int(row_num /3*2)
test_num = -1*int(row_num /3)
col_list = ['side', 'return_t5', "return_t30", "vol_sh_out_pct","stake_pct_chg", "tran_value","mkt_cap", "prev_tran_... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.base.build_root import BuildRoot
from pants.bsp.spec.base import BuildTargetIdentifier
from pants.bsp.util_rules.targets import BSPResourcesRequest, BSPResourcesResult
from pant... |
#!/usr/bin/python3
"""
Rectangle module
"""
class Rectangle():
"""
Recatangle class
"""
pass
|
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
import mpl_toolkits.mplot3d.axes3d as p3
from scipy import integrate
G=6.67408e-11 #m^3Kg^-1s^-1 #Big G
"""
Below are the default values for scales of mass, distance, velocity, as w... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#####################################################################################
# #
# author: t. isobe (tisobe@cfa.harvard.edu) ... |
l=[1,2,3,4,5,6,7,8,9,10]
for i in l:
print (i)
print (i)
|
#-*-coding:utf-8-*-
#__author__='maxiaohui'
#当前只能自动抓取log,自动分析结果
#下一步:Smoke基本功能实现自动化之后,可以全面实现自动化
from adb import loggerHandler,deviceLogger
from config import config
import time
def runFr1N():
print("请测试:在**模式下,连续刷脸")
pro=deviceLogger.getLogcat(config.deviceId,"desktop29",config.faceRecognizationKey)
time... |
import pymongo
from collections import Counter
DB = 'controversy'
mongo_col = 'test'
col = pymongo.MongoClient()[DB][mongo_col]
print('#retweets {}'.format(col.find().count()))
hashtag_freq = Counter([h for r in col.find() for h in r['hashtags']])
print(hashtag_freq.most_common(10))
|
"""
import math
x = float(input("Enter x: "))
y = math.sqrt(x)
print("The square root of",x,"equals to",y)
"""
"""
#ZeroDivisonError
try:
print("1")
x = 1/0
print("2")
except:
print("Oh dear, something went wrong...")
print("3")
"""
"""
try:
x = int(input("Enter a number: "))
... |
import numpy as np
def read_ucr(filename):
data = np.loadtxt(filename, delimiter="\t")
y = data[:, 0]
x = data[:, 1:]
return x, y.astype(int)
x_train, y_train = read_ucr("FordA_TRAIN.txt")
x_test, y_test = read_ucr("FordA_TEST.txt")
np.save("FordA", (x_train, y_train, x_test, y_test), allow_pickle=T... |
from django.shortcuts import render,redirect
from . models import *
from django.contrib import messages
def index(request):
if 'id' in request.session:
return redirect('/dashboard')
else:
return render(request, 'black_app/index.html')
def register(request):
if request.method == 'POST':
... |
import unittest
from katas.kyu_6.regexp_basics_parsing_time import to_seconds
class ToSecondsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(to_seconds('00:00:00'), 0)
def test_equals_2(self):
self.assertEqual(to_seconds('01:02:03'), 3723)
def test_equals_3(self):
... |
import os
import sys
sys.path.append(os.getcwd())
from base.get_driver import GetDriver
from page.page_biannianaolai import PageBaiNianAoLai
class TestLogin():
def setup(self):
self.driver = GetDriver()
self.login = PageBaiNianAoLai(self.driver)
def teardown(self):
self.driver.quit()
... |
# coding=utf-8
"""
题目:用两个栈实现一个队列
"""
class Queue(object):
def __init__(self):
self.push_stack = list()
self.pop_stack = list()
def push(self, value):
self.push_stack.append(value)
def pop(self):
if self.pop_stack:
return self.pop_stack.pop()
else:
... |
#!/usr/bin/env
# -*- coding: utf-8 -*-
__author__ = 'vmture'
import csv
import wx
from new_script import qihu_new, apple_new, baidu_new, tengxun_new, xiaomi_new
from com.common import CommonFunction
class ButtonFrame(wx.Frame):
def __init__(self):
self.update = '渠道已更新\n\n'
self.un_update = '渠道未... |
import string, sys, math
def getStart(m):
#return math.floor(len(m) / 2), math.floor(len(m) / 2)
return 7000, 2000 # y, x --> optimized for puzzle input to fit in 32bit memory :| TODO: need better solution ;)
def initField(width, height):
m = []
for y in range(0, height):
m.append([])
... |
"""marquee logging formatter."""
import json
from logging import Formatter
class MarqueeFormatter(Formatter):
def __init__(self, source=None, *args, **kwargs):
"""marquee logging formatter.
Args:
source (str): application from which your are logging
"""
self.source = s... |
# -*- coding: utf-8 -*-
# @Time : 2020/5/26
# @Author : J
# @File : 图像的几何变换.py
# @Software: PyCharm
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
#缩放
# img = cv.imread("../image2.jpg")
# res = cv.resize(img,None,fx=2,fy=2,interpolation = cv.INTER_CUBIC)#缩放
# # height,width ... |
from indicator import Indicator
import states
class Ichimoku(Indicator):
def __init__(self, utils, config, logger, timeframe):
Indicator.__init__(self, utils, config, logger, timeframe)
self.senkou_span_b_period = self.cfg.SENKOU_SPAN_B_PERIOD
self.displacement_period = self.cfg.DISPLACEMENT_PERIOD
self.t... |
"""Manage core level cgroups.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
import click
from treadmill import cgroups
from treadmill import cgutils
from treadmill import utils
_LOGGE... |
# flake8: noqa
from .bresenham import bresenham, bresenham_multiply
from .douglas_peucker import douglas_peucker
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 21:40:08 2020
@author: user
"""
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import matplotlib.pyplot as plt
x = torch.linspace(-5, 5, 100) #creat array from -5 to 5
print(x)
x = Variable(x) #charnge to variable
#-----... |
import torch
import torch.nn as nn
import numpy as np
from test01 import get_data
from test02 import Net
path = r"./data1.xls"
net = Net()
# net.load_state_dict(torch.load("./params"))
loss_fn = nn.BCELoss()
optimizer = torch.optim.Adam(net.parameters())
datas = get_data.red_excel(path)
max_data = np.max(... |
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
lhs, rhs = [1], [1]
res = []
for n in nums[:-1]:
lhs.append(n*lhs[-1])
for n in reversed(nums[1:]):
rhs.append(n*rhs[-1])
rhs.reverse()
for i in range(len(nums)):
... |
import os, sys, time, re
class g:
auto_set = True
start_byte = ""
second_byte = ""
third_byte = ""
start = ""
end = ""
arg_list = ""
logfile = os.path.splitext(os.path.basename(__file__))[0] + "-Log.txt"
def set_dns(dns_primary, dns_secondary=""):
if (dns_primary=="auto"):
os.system... |
import torch
import math
import random
import os
import subprocess
import numpy
import gym
import matplotlib.pyplot as plt
import time
from heapq import *
from drivingenvs.vehicles.ackermann import AckermannSteeredVehicle
from drivingenvs.envs.base_driving_env import BaseDrivingEnv
from drivingenvs.envs.driving_env_wi... |
# Changed all TimeField() with CharField() to resolve
# timezone issue in Postgres on server (have to resolve this)
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator ,MaxValueValidator
class UserQuickLook(models.Model):
user = models.Foreign... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Juaumpc
"""
from Token import Token
from SymbolTable import SymbolTable
from TableEntry import TableEntry
from SymbolTableTree import SymbolTableTree
from ASA import *
class Syntactic():
token = ''
arrayToken = []
indexToken ... |
"""
This is a spider; it is a seperate class from the crawler because here
we can cleanly encapsulate all the real scrapign logic.
Nov, 28, 2016 - Pablo Caruana pablo dot caruana at gmail dot com
"""
import re
import logging
from bs4 import BeautifulSoup
from requests import exceptions
class Spider:
... |
from .core import spell, no_spells
from .spells import unpack_keys, unpack_attrs, args_with_source, dict_of, print_args, call_with_name, delegate_to_attr, \
maybe, select_from, magic_kwargs, assigned_names, switch, timeit
try:
from .version import __version__
except ImportError: # pragma: no cover
# vers... |
"""
Start the socker websocket server
Usage:
socker [options]
socker -? | --help
socker --version
Options:
-i INTERFACE Listening interface [default: localhost]
-p PORT Listening port [default: 8765]
-v Enable verbose output
--auth-backend=PATH Auth backend path
... |
# -*- coding: utf-8 -*-
# Вам дано описание пирамиды из кубиков в формате XML.
# Кубики могут быть трех цветов: красный (red), зеленый (green) и синий (blue).
# Для каждого кубика известны его цвет, и известны кубики, расположенные прямо под ним.
# Пример:
# <cube color="blue">
# <cube color="red">
# <cube col... |
#!/usr/bin/env python
"""
https://stackoverflow.com/questions/22959698/distance-from-given-point-to-given-ellipse
"""
import os, sys, argparse, logging, textwrap
import numpy as np, math
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
specs_ = lambda s:filter(lambda s:s[0] != "#", filter(None,map... |
# 20/20
# SECTION 2 - FUNCTIONS (20PTS TOTAL)
from math import *
# PROBLEM 1 (Length of String - 3pts)
# Make a function which asks the user to enter a string, then prints the length of that string.
# You will need to use the input() function.
# Make a call to that function
string = input("Give me some string: ")
prin... |
import redis
import tushare as ts
r = redis.StrictRedis('127.0.0.1',decode_responses=False)
df = ts.get_stock_basics()
print(df.head())
code_list = list(df.index.values)
r.lpush('code',code_list) |
##############################################################################
#
# Copyright (C) 2020-2030 Thorium Corp FP <help@thoriumcorp.website>
#
##############################################################################
from odoo import api, fields, models, _
from odoo.exceptions import MissingError
impo... |
#!/usr/bin/env python
import pysam
import sys
from copy import copy
from vcftagprimersites import read_bed_file
def trim(s, start_pos, end):
if not end:
pos = s.pos
else:
pos = s.reference_end
eaten = 0
while 1:
## chomp stuff off until we reach pos
if end:
flag, length = cigar.pop()
else:
flag, ... |
import random
class Quick_sort:
def sort(self, nums):
'''
快速排序
:type nums: List[int] 要排序的数组
'''
self.quick_sort(nums, 0, len(nums)-1)
# print(sorted(nums))
def quick_sort(self, nums, left, right):
'''
:type nums: List[int] 要排序的数组
'''
... |
#!/usr/bin/env python3
# Test Client application.
#
# This program attempts to connect to all previously verified Flic buttons by this server.
# Once connected, it prints Down and Up when a button is pressed or released.
# It also monitors when new buttons are verified and connects to them as well. For example, run th... |
from django.db import models
class Post(models.Model):
author = models.CharField(max_length=40)
password = models.CharField(max_length=200)
title = models.CharField(max_length=100)
content = models.TextField(max_length=300)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = mod... |
#!/usr/bin/python3
"""Module Matrix-Mul"""
def matrix_mul(m_a, m_b):
"""function that multiplies 2 matrices"""
if type(m_a) != list:
raise TypeError("m_a must be a list")
if type(m_b) != list:
raise TypeError("m_b must be a list")
if len(m_a) and not all(type(i) == list for i in m_a):
... |
"""Utilities specific to Go language ecosystem."""
|
import train
import args
import numpy as np
import os
def get_split_index(y, split_values):
for i, thres in enumerate(split_values):
if y < thres:
return i - 1
return len(split_values) - 1
def split_data(data, split_values, splitted_data):
for one_data in data:
one_index = get_... |
if __name__ == "__main__":
# For direct call only
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import pytest
import pylo
class TestEvent:
def setup_method(self):
self.event = pylo.Event()
self.reset_triggered_handler()
def reset_trigg... |
# coding: utf-8
"""
Copyright 2015 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... |
import unittest
from katas.kyu_7.unflatten_a_list import unflatten
class UnflattenTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(unflatten([3, 5, 2, 1]), [[3, 5, 2], 1])
def test_equal_2(self):
self.assertEqual(unflatten([1, 4, 5, 2, 1, 2, 4, 5, 2, 6, 2, 3, 3]),
... |
# This is a simple Hello World Code
print("My First Hello World!", "Using Python")
palabra="Una Palabra"
print("For a variable 'palabra': "+palabra)
print("palabra[0]="+palabra[0])
print("palabra[1:]="+palabra[1:])
print("palabra[:1]="+palabra[:1])
print("palabra[-1:]="+palabra[-1:])
print("palabra[:-1]="+palabra[:-1]... |
# Python Program to find factorial of a given number
def fac(x):
if x==0:
return 1
elif x>0:
return x*fac(x-1)
|
"""
Tools to import subcatchment paramaters saved as a csv
"""
class Subcatchment(object):
def __init__(self, fields):
"""
load paramaters from fields
:param fields: list of subcatch parameters in typical CUHP order
"""
self.name = fields[0]
self.area = ... |
fruit = {"one": "apple",
"two": "pear",
"three": "grape",
"four": "watermelon",
"five": "banana"
}
print(fruit)
print(fruit["two"]) # find a value by key ,key as the index
# and key-value
fruit["six"] = "peach"
print(fruit)
del fruit["six"]
print(fruit)
fruit.clear()
print(fruit)
d... |
from storm.monitoring.sensor.api import units
class Measure(object):
def __init__(self, value, unit_type, description = ''):
self.value = value
if unit_type not in units.Units().get_units():
msg = 'The specified unit type %s is not supported' % str(unit_type)
raise units.Un... |
from ryu.base import app_manager
from ryu.controller.handler import set_ev_cls
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER
from ryu.controller import ofp_event
from ryu.lib.packet import packet, ether_types, ethernet, dhcp, ipv4, udp
# DHCP
# ofproto 在这个目录下,基本分为两类文件,一类是协议的数据结构定义,另一类是协议解析,也即数据... |
from __future__ import annotations
import typing as T
import re
import os
import logging
import math
from pathlib import Path
from datetime import datetime, timedelta
from . import find
from . import namelist
NaN = math.nan
def datetime_range(start: datetime, stop: datetime, step: timedelta) -> list[datetime]:
... |
"""
Experiments for studying the learned mean embedding.
Two experiments:
* PCA with several different dynamics.
* Interpolating the latent space between two dynamics.
"""
import os
from datetime import datetime
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns... |
import os
from click.testing import CliRunner
import pytest
import signal
import app.configfile as configfile
from app.commands import ls, add, move
def test_add(tmp_path):
runner = CliRunner()
configfile.CONFIG_FILE_PATH = './conf.yml'
with runner.isolated_filesystem():
result = runner.invoke(
... |
#!/usr/bin/env python
fst = lambda ab: ab[0]
snd = lambda ab: ab[1]
head = lambda xs: xs[0]
tail = lambda xs: xs[1:]
def is_inter(a, b):
""" Integer -> Integer -> Bool"""
return a == b - 1 or a == b
def list_sort(data):
""" :: set -> [Integer],
where the result is sorted
"""
return sorted(li... |
import os
import io
import boto3
import mimetypes
s3_client = boto3.client(
"s3",
endpoint_url="https://ams3.digitaloceanspace.com",
aws_access_key_id=os.getenv("DO_SPACE_ACCESS"),
aws_secret_access_key=os.environ("DO_SPACE_SECRET"),
region_name="ams3",
)
def upload_video(local_path, path, bucket... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.