text stringlengths 38 1.54M |
|---|
from __future__ import print_function
import time
from upm import pyupm_light as lightObj
def main():
# Create the light sensor object using AIO pin 0
sensor = lightObj.Light(0)
# Read the input and print both the normalized ADC value and a
# rough lux value, waiting one second between readin... |
# 预处理
import re
# 处理多余的换行
class Pre_convert:
_path = ''
def __init__(self, path):
self._path = path
def content_convert(self):
file_data = ""
with open(self._path, "r", encoding="utf-8") as f:
for line in f:
if '*' in line:
line ... |
'''
https://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
Ask the user for a number and determine whether the number is
prime or not. (For those who have forgotten, a prime number is
a number that has no divisors.). You can (and should!) use your
answer to Exercise 4 to help y... |
from combine import closest_pixel
def test_closest_pixel_1():
pixel1 = [255,155, 9]
pixel2 = [155, 255, 10]
pixel3 = [0,155, 8]
pixel4 = [89, 208, 190]
window = [[pixel1, pixel2], [pixel3, pixel4]]
pixel = [255, 150, 8]
return closest_pixel(window, pixel) == (0,0)
def test_closest_pixel_... |
import random
rand_num = random.randint(1, 100)
print('Добро пожаловать в числовую угадайку')
def is_valid(num):
flag = False
if num.isdigit() and int(num) in range(1, 101):
flag = True
return flag
while True:
num_inp = input('Введите число от 1 до 100: ')
if is_valid(num_inp):
n... |
from django import forms
from .models import *
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['user','title','text','image']
class LoginForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(max_length=30,widget=forms.PasswordInput)
|
from random import sample
from itertools import product
from mesa.space import MultiGrid
from mesa import Model
from mesa.time import SimultaneousActivation
from TestProjects.TriageMoraal.agents import *
class Triage(Model):
"""
Simulation of Triage
"""
# todo: hier worden alle agents aangemaakt
d... |
from PySide2.QtWidgets import *
from UI.UserTaskManager.utils import rvPlayerUtils
class rvButtonsTM():
def __init__(self, taskManager, treeWidget):
self.taskManager = taskManager
self.treeWidget = treeWidget
self.project = self.taskManager.currentProject
self.itemUtils = self.tre... |
"""This file is for defining messages which we show to
users to inform them or to ask for something in case of minor failure"""
YOUR_PO_TYPE_IS = "Alright! making P.O. of type "
SAVING_PO = "Alright! saving PO..."
PO_PROCESS_ENDED = "The PO making process was ended. "
ASK_PO_DETAIL_TYPE_NUMBER_AGAIN = "I couldn't fin... |
#Problema: Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer
# como parâmetro e mostre uma mensagem com o tamanho adaptável.
# Função para imprimir mensagens dentro de cabeçalho com bordas
def escreva(mensagem):
print('-' * (len(mensagem) + 4))
print(f' {mensag... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_basic_solver"]
import numpy as np
from .. import kernels
from ..basic import BasicSolver
from ..hodlr import HODLRSolver
from ..latenthodlr import LatentHODLRSolver
def _test_solver(Solver, N=100, seed=1234):
# Set up the... |
import numpy as np
import time
from gym.spaces import Box, Discrete
# Custom utils
def printISO8601():
'''
Prints date and time in ISO8601 format
e.g. 6th June 2018, 11:15 pm, at UTC:
2018-06-06T23:15:00Z
The same moment with Central European Timezone offset:
2018-06-07T0... |
import Tkinter as tk
import ttk
import json
class LoginWindow:
def __init__(self):
self.root = tk.Tk()
self.account_logged_in = dict(id=None, password=None, name=None, type=None)
frame = ttk.Frame(self.root)
style = ttk.Style()
style.theme_use('clam')
frame.pack()
... |
import sqlite3
import itertools
from uuid import uuid4
from contextlib import closing
dbname = "other-1.db"
with closing(sqlite3.connect(dbname)) as conn:
c = conn.cursor()
c.execute("create table list(id text, a1 int, a2 int)")
sql = "insert into list(id, a1, a2) values (?, ?, ?)"
for one, two in iterto... |
#
# Copyright (C) 2017-2020 Dimitar Toshkov Zhekov <dimitar.zhekov@gmail.com>
#
# 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 2 of the License, or (at your option)
# any later v... |
c = {'a':10 , 'b':1 , 'c':22}
tmp = list()
for k,v in c.items() :
tmp append((v,k))
print_tmp
tmp.sort(reverse = True)
print tmp |
# customer = {
# "1": "one",
# "2": "two",
# "3": "three",
# "4": "four",
# "5": "five",
# "6": "six",
# "7": "seven",
# "8": "eight",
# "9": "nice",
# "0": "zero"
# }
# result = ""
# numbers = input("what is number.....")
# print(numbers)
# for number in numbers:
# a = type(... |
import os
def iter_files_with_ext(root_dir, ext):
"""
Iterate recursively on all files in root dir, ending with <ext>.
:param root_dir: Directory to list.
:param ext: Extension of the files.
:return: absolute path of all files.
"""
for path, sub_dirs, files in os.walk(root_dir):
fo... |
#!/usr/bin/env python3
"""
MLARCS
Mailing List ARChive Search
Download a mailing lists archives and have them available to search.
"""
import os
import subprocess
import bs4
import requests
def get_index_page(index_url):
r = requests.get(index_url)
soup = bs4.BeautifulSoup(r.content, "html.parser")
as_... |
"""
rpc.main
Allows invocation as
$ python -m rpc
"""
from rpc.cmdline import main
if __name__ == '__main__':
main()
|
import random
wins = 0
draws = 0
choices = ["rock", "Paper", "Siscors"]
for i in range(5):
player_choice = input("r/p/s")
if player_choice == "r":
player = 1
elif player_choice == "p":
player = 2
elif player_choice == "s":
player = 3
computer = random.randint(1, 3)
if pla... |
# !/usr/bin/python
# Filename: base64_converter
# Auteur: Chao
import base64
print "base64: this is a script to"
print "produce the url by using base64"
print
print "please input the name of Editor:"
Editor = str(raw_input("name of Editor:"))
print
print
print
print "************************************"
print "pl... |
def solve(arr):
suma = 0
sumb = 0
arra = []
arrb = []
n = len(arr)
for i in arr:
if i%2:
sumb+= i
arrb.append(i)
else:
suma += i
arra.append(i)
arra.sort()
arrb.sort()
# print(suma,sumb,arra,arrb)
for j in range(len(... |
# Generated by Django 3.1.3 on 2020-12-05 14:12
import cloudinary.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hood', '0002_remove_neighbourhood_photo'),
]
operations = [
migrations.AddField(
model_name='neighbourhood',
... |
from django import forms
from .models import Review
from django.forms import ModelForm
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ('job_status', 'reply', 'replies_from_employer', 'test_tasks', 'offers', 'comment')
widgets = {
'text': forms.Textarea,
... |
# https://codeforces.com/problemset/problem/1417/A
for _ in range(int(input())):
n, k = map(int, input().split())
piles = tuple(map(int, input().split()))
min_pile = piles[0]
min_index = 0
for i in range(1, n):
if piles[i] < min_pile:
min_index, min_pile = i, piles[i]
ans ... |
from sqlite3 import connect
from datetime import datetime
class SQLiteConnector:
def __init__(self):
self._connection = connect('tracks.db')
self._connection.execute(
'''CREATE TABLE IF NOT EXISTS unique_tracks (
performance_id text
, track_id text
... |
from django.urls import path
from .views import contactanos
urlpatterns=[
path('',contactanos,name="contactanos"),
] |
import os
with open('GMS_CPLEX_Results_RefCluster1hour.txt') as fp:
lines = fp.readlines()
for line in lines:
instname = line.split(';')[0]
os.system(
'gams modelcli.gms --instname=j30gdx/' + instname + '.sm --iterlim=99999 --timelimit=99999 --solver=CPLEX --trace=0 --nthreads=0')
|
class Animal:
species = None
hunger = 50
def __init__(self, name, species):
self.name = name
self.species = species
def speak(self, greet = 'Hey'):
print(f"{greet}, I am {self.name} the {self.species}.")
class Cat(Animal):
# You could declare all the attributes o... |
import numpy as np
from scipy.special import logsumexp
from viterbi import viterbii
# forward algorithm
def forward(obs, pi, t, e, m, l):
alpha = np.zeros((l, m))
for k in range(m): # задаем начальные параметры для дальнейшего их улучшения
alpha[0, k] = pi[k] * e[k, obs[0][1]]
# рекурсивно получ... |
import json
from datetime import datetime as builtindatetime
import mock
import pendulum
import pytest
from nose.tools import assert_equal, assert_raises
from pytest import raises
from sqlalchemy.exc import DataError, IntegrityError
from app import create_app, db
from app.datetime_utils import naive, utcnow
from app.... |
import matplotlib.pyplot as plt
x_values = list(range(1,1001))
y_values = [x**2 for x in x_values]
# s 为点的大小
#plt.scatter(x_values,y_values,c='red',s=10)
# plt.cm 决定使用哪个颜色映射
plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,edgecolor='none',
s=40)
plt.scatter(500,240000,edgecolor='none',s=40)
plt.title(... |
import pytest
pytest.importorskip("pandas") # noqa
from skbio.tree import MissingNodeError
def test_tree_generation(ocx, api_data):
samples = ocx.Samples.where(project="4b53797444f846c4")
tree = samples.tree_build()
assert tree.has_children()
assert tree.is_root()
staph = tree.find("1279")
a... |
#!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
tuple_acpy = ()
tuple_bcpy = ()
if len(tuple_a) == 0:
tuple_acpy = (0, 0)
elif len(tuple_a) == 1:
tuple_acpy = (tuple_a[0], 0)
else:
tuple_acpy = tuple_a
if len(tuple_b) == 0:
tuple_bcpy = (0, 0)
elif l... |
# Generated by Django 3.1.1 on 2020-10-18 21:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('usuario', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='usuario',
old_name='usuario_aadministrador',... |
#file: widget.py
#Copyright (C) 2008 FunnyMan3595
#This file is part of Endgame: Singularity.
#Endgame: Singularity 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 2 of the License, or
#(at your ... |
import requests
import os
from bs4 import BeautifulSoup
import defines
from deurl import url_to_code
from show_post import get_list
def refresh_boards():
request = requests.get('https://www.ptt.cc/bbs/hotboards.html')
soup = BeautifulSoup(request.content, 'lxml')
# f = open('boards.txt', 'w', encoding='u... |
import requests
import json
'''
局部刷新 AJAX
NETWORK XHR
'''
if __name__ == '__main__':
# UA 伪装
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
}
url = 'https://fanyi.baidu.com/sug'
data = {
... |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Hou-Ning Hu
import numpy as np
class MeanVelocityDiff(object):
""" Class for Mean Overlap metric via a simplified IoU (Only for relative comparison)
Init:
W - Panoramic image width, int, float, in pixel format
... |
from graphics import *;
window = GraphWin("Window", 500,700);
window.setBackground("white")
right = 130
righto = 131
for x in range(0,100):
hair = Rectangle(Point(right,15),Point(righto,70))
hair.draw(window)
right = right+1
righto = righto+1
shirts = Rectangle(Point(100,180),Point(270,160))
s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import glob
class SearchAndChange:
def __init__(self):
if len(sys.argv) != 3:
print ("Musíte zadat argumenty: searchandchange [co] [čím]")
sys.exit(1)
co = sys.argv[1]
cim = sys.argv[2]
seznam = glob.glob("*")
seznam = self.filt... |
# coding=UTF-8
#from youtrack.connection import Connection, httplib2
from youtrack.connection import Connection, httplib2
#from connection import Connection, httplib2
from xml.etree.ElementTree import fromstring
import random
import urllib
#import httplib
#import urllib2
#import socks
import csv
import re
import time... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import xarray as xr
grib_data = 'z500.grib'
dsgrib = xr.open_dataset(grib_data, engine='cfgrib')
# print(dsgrib.variables)
dsarray = dsgrib.to_array()
fig = plt.figure(figsize=(8, 6), edgecolor='b')
# m = Basemap(projection... |
# -*- coding: utf-8 -*-
BOT_NAME = ['tweetsSpider', 'informationSpider']
SPIDER_MODULES = ['Sina_spider2.spiders']
NEWSPIDER_MODULE = 'Sina_spider2.spiders'
DOWNLOADER_MIDDLEWARES = {
"Sina_spider2.middleware.UserAgentMiddleware": 401,
"Sina_spider2.middleware.CookiesMiddleware": 402,
}
ITEM_PIPELINES = ["Sin... |
# -*- coding: utf-8 -*-
"""Chiou and Youngs (2014, :cite:`chiou14`) model."""
import logging
from typing import Optional
import numpy as np
from . import model
from .types import ArrayLike
__author__ = "Albert Kottke"
class ChiouYoungs2014(model.GroundMotionModel):
"""Chiou and Youngs (2014, :cite:`chiou14`) m... |
# -*- coding: utf-8 -*-
# Code from https://sakshambhatla.wordpress.com/2014/08/11/simple-mqtt-broker-and-client-in-python/
from DataManager import DataManager
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
# Subscribing in on_connect() means that if we... |
# This classification changed up a little from predicting quality of wine in a number, instead predicts
# whether the wine is "good quality" or "bad quality" as good quality wine being any wine that was given a
# quality score of 6 or better (out of 10)
import pandas as pd
import numpy as np
import matplotlib.pyplot a... |
#
# Delivery API Address Model & Validators
#
# Tue 1 Mar 21:10:18 2016
#
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import User
from .delivery import SERVICES, STATUSES, get_prices, OFFICE
from .signals import order_purchased
fro... |
import threading
import time, random
import os
def thrd_handler(name):
print ('thread (%s) starts in process(%s)' % (name, os.getpid()))
time.sleep(random.random())
print ('thread (%s) finished in process(%s)' % (name, os.getpid()))
t = threading.Thread (target = thrd_handler, name = 'thread in ex21', args = ('t... |
import pandas as pd
import format as fw
import globals as glob
def rank_relevant_group(group, score, step_size, amount_candidates, amount_candidates_max):
for index, row in group.iterrows():
if amount_candidates <= amount_candidates_max:
group.loc[index, glob.judgement] = score
gro... |
'''EM algorithm for multinomial mixture model'''
import numpy as np
from scipy.misc import logsumexp
def mmm_em_fit(X, T, pz=None, eps=0.00001, maxiter=1000):
'''Fit a multinomial mixture model using EM.
Parameters
----------
X : 2D array of float
Training data, an instance on eac... |
import pytest
from indoor_position.api import api
from indoor_position.models.map import create_map
from indoor_position.api.maps import MapAPI, MapListAPI
from indoor_position.models.user import User
from indoor_position.api.users import UserAPI, UserListAPI
from indoor_position.common.error_handler import *
@pytes... |
"""Motor module."""
from enum import IntEnum
from typing import Tuple
from modi.module.output_module.output_module import OutputModule
class Motor(OutputModule):
class PropertyType(IntEnum):
FIRST_TORQUE = 2
SECOND_TORQUE = 10
FIRST_SPEED = 3
SECOND_SPEED = 11
FIRST_DEGRE... |
import FWCore.ParameterSet.Config as cms
ecalPreshowerDataCertificationTask = cms.EDAnalyzer("ESDataCertificationTask",
prefixME = cms.untracked.string('EcalPreshower'),
mergeRuns = cms.untracked.bool(False)
)
|
'''
Generate test case for the 1593 problem
'''
import random
import time
def gen():
random.seed(time.time()) ;
numLine = 1000 ;
for i in range(0, numLine) :
lineLength = random.randint(50, 180) ;
curlen = 0 ;
result = "" ;
genSp = True ;
while curlen < lineLength:
if genSp == True:
# genera... |
from django import http
from django.http.response import Http404
from django.shortcuts import redirect, render , HttpResponse
from post import urls
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import login as login_new
from django.contrib.auth import... |
"""Koninklijke Philips N.V., 2019 - 2020. All rights reserved."""
import sys
from eaglevision.eaglevision import EagleVision
from eaglevision.eaglevision import create_parser
if __name__ == '__main__':
# Execute the parse_args() method
ARGS = create_parser(sys.argv[1:])
EAGLEVISIONOBJ = EagleVision(ARGS.... |
import numpy as np
K = []
Sgm = []
F = []
Z = []
K_num = {}
def data_input():
global K,Sgm,F,S,Z
with open('nfa.txt', 'r') as f:
lines = f.readlines()
Sgm = lines[0].split()
F = np.zeros((len(lines)-1)*len(Sgm), dtype=np.int32).reshape((len(lines)-1),len(Sgm))
K_num['#'] = -1
... |
import numpy as np
import gym
import math
from matplotlib import pyplot as plt
def eval(env):
average_tot_score = []
for j in range(900):
state = env.reset()
total_reward = 0
for t in range(200):
angle = math.degrees(math.acos(state[0]))
velocity = state[2]
... |
from os import path, makedirs
import yaml
from opennmt.models import SequenceToSequence
from opennmt.config import load_model
def load_config(config_path: str):
"""
Loads an OpenNMT config file
Arguments:
config_path: The path to the config file
Returns:
A dict containing the config... |
'''
Created on 2018-3-30
@author: Dezhi Wang
'''
import numpy as np
import random
from sklearn.utils.metaestimators import if_delegate_has_method
class BalanceDataGenerator(object):
def __init__(self, batch_size, type, te_max_iter=100):
assert type in ['train', 'test']
self._batch_size_ = batch_si... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtWidgets
from program.gui import main as base
def main():
app = QtWidgets.QApplication(sys.argv)
app.setStyleSheet(open('./css/base.css').read())
main = base.Main()
main.dia_widget.ceate_gtrid(3, 4)
main.dia_widget.next_pa... |
import pandas as pd
import logging
import time
#from IPython.display import display, HTML
import base
import fund_scanner.common_tools.logger as logger
import fund_scanner.common_tools.database as db
import fund_scanner.business.grab_data as grab_data
engine = db.get_sqlalchemy_engine()
log = logging.get... |
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
setup(
name='automatic_diff',
version='0.1.0',
description='naive automatic differentiation via dual numbers',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=... |
import sys
sys.stdin = open("slalom.in")
sys.stdout = open("slalom.out", "w")
n = int(input())
s = []
for i in range(n):
s.append([])
for j in range(i + 1):
s[i].append(1)
a = []
for i in range(n):
a.append(list(map(int, input().split())))
for j in range(i):
s[i][j] = a[i][j] + max(s[i... |
import pytest
from code_challenges.multiBracketValidation.multi_bracket_validation import multi_bracket_validation
def test_import():
assert multi_bracket_validation()
|
#!/usr/bin/python
import sys
# Test of Margulis' construction of an expander graph
def usage(name):
print("Usage: %s M" % name)
print("M = Defining paramter. Generates graph with 2 * M*M nodes")
sys.exit(0)
# Map from M X M --> M*M
def mmap(x, y, m):
return m*x+y
# Family of functions defining ... |
class Musician(object):
def __init__(self, sounds):
self.sounds = sounds
def solo(self, length):
for i in range(length):
print self.sounds[i % len(self.sounds)],
print ""
class Bassist(Musician): # The Musician class is the parent of the Bassist class
def __... |
__author__ = 'MaxZhuang'
from collections import deque
queue = deque()
def breadth_first_search(start, goal):
queue.append(start)
back_dict = {}
path = []
back_pointer = goal
back_dict[start] = None
while len(queue) > 0:
location = queue.popleft()
for adjacent in range(len(location.ad... |
import matplotlib.pyplot as plt
import random
import time
import numpy as np
from sklearn import metrics
from math import sqrt
from sklearn.model_selection import train_test_split
def diffa(y, ypred,x):
return (y-ypred)*(-x)
def diffb(y, ypred):
return (y-ypred)*(-1)
def shuffle_data(x,y):
# shuffle x,y,... |
"""
used to run the program via command line arguments
"""
from stega import Stega
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--address','-a', help = "Path to the image you want to encode/decode")
parser.add_argument('--text', '-t',help = "The text you want to embed into the qr code")
par... |
# -*- coding: utf-8 -*-
import os
import random
import time
print()
print("***** Tervetuloa pelaamaan Miinaharavaa! *****")
print()
def alkuvalikko():
"""
Aloittaa ohjelman ja toimii pelin alkupisteenä. Tulostuu aina pelin päättyessä. Ohjelma päättyy vasta kun pelaaja valitsee "4. Poistu pelistä".
"""
... |
import sys
sys.path.append("../..")
import game
def saisieCoup(jeu):
Liste=game.getCoupsValides(jeu)
coup = Liste[0]
return coup
|
#coding:utf-8
'''
代付绑卡
https://payment.test.bkjk.com
URL:/dfapi/querybankcnaps
'''
#coding:utf-8
import requests
import json
import random
import time
url = 'https://payment.test.bkjk.com/dfapi/querybankcnaps'
headers ={"Content-Type":"application/json"}
data = {
"bankNameKeyWord":"工商银行",
"appId":"10007"
}
s... |
from markdown2 import Markdown
class CustomMarkdown(Markdown):
def preprocess(self, text):
return text
markdown = CustomMarkdown(extras=["fenced-code-blocks"])
|
from RecoEcal.EgammaClusterProducers.hybridSuperClusters_cfi import cleanedHybridSuperClusters
from RecoEcal.EgammaClusterProducers.multi5x5BasicClusters_cfi import multi5x5BasicClustersCleaned
from RecoEgamma.EgammaIsolationAlgos.electronTrackIsolations_cfi import trkIsol03CfgV1,trkIsol04CfgV1,trkIsol03CfgV2,trkIsol0... |
# ----------------------------------------------
# | Build in 2020.03.09 22:00 - 2020.03.10 2:00 |
# | Tester:KaryoYou |
# ----------------------------------------------
#
# 创建列表,包含3个元素,并使用这个列表打印消息.
Guests = ['aa', 'bb', 'cc']
# 定义消息内容;由于消息内容过长,使用 \ 符号进行换行编辑; 建议代码行长度为 80 以内.
message = "H... |
#! /usr/bin/env python3
# Image_Site_Downloader.pyw
'''
Write a program that goes to a photo-sharing site like Flickr or Imgur,
searches for a category of photos, and then downloads all the resulting
images.
'''
import requests, sys, bs4, os, pprint
from selenium import webdriver #need selenium b/c html containing i... |
'''
N을 입력받고
별개수cnt 1, idx=0
1. '*'*cnt출력
2. 공백+1 cnt+2 idx+1
3. idx == n//2가 되면 별-2,공백-1
'''
n = int(input())
if not n%2 or n < 0 or n > 100:
print('INPUT ERROR!')
else:
cnt = 1
idx = 0
blank = 0
while idx < n:
print(' '*blank+'*'*cnt)
idx+=1
if idx <=n//2:
cnt +=... |
# -*- coding: utf-8 -*-
#模拟移动端,测试Web程序
import unittest
import json
from flask import url_for
from app.models import Role, Product, Category, User, Order
from app import db, create_app
from base64 import b64encode
class APITestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
... |
"""
Mongoengine Database class to handle access to mongoDB through ODM.
"""
try:
import pymongo
except ImportError:
raise ImportError(
"Mongostorage_socket requires pymongo, please install this python module or try a different db_socket.")
try:
import mongoengine
except ImportError:
raise Impo... |
import unittest as ut
from calc import calculator as calc
class test_calc(ut.TestCase):
def test_addition(self):
#OK tests
self.assertEqual(calc.addition(10,5), 15 )
self.assertEqual(calc.addition("st", 10), "Not a number, please try again!")
#Not Equal Tests
self.assertNotEqual(calc.addition(1,1), 3 )
... |
# https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/674/
#SOLUTION FOR ARRAYS THAT ARE SORTED
from typing import List
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
intersection_array = list()
i = 0
j = 0
while i... |
import cv2
import numpy as np
import torch
import pyzed.sl as sl
from models.with_mobilenet import PoseEstimationWithMobileNet
from modules.keypoints import extract_keypoints, group_keypoints
from modules.load_state import load_state
from modules.pose import Pose, track_poses
from val import normalize, pad_width
def... |
import numpy as np
import sys
import matplotlib
from matplotlib import pyplot as plt
from matplotlib import gridspec as gs
from multiprocessing import Pool
import matplotlib as mpl
from matplotlib.patches import Rectangle
from operator import itemgetter
sys.path.append("/Users/theo/Desktop/ALP_Simulation/New_code/Modu... |
for t in range(int(input())):
l, d, s, c = map(int, input().split())
flag = 0
if s >= l:
print("ALIVE AND KICKING")
flag = 1
continue
for i in range(d-1):
s *= c+1
if s >= l:
flag = 1
break
if flag == 1:
print("ALIVE AND KICKING... |
# #삼각 함수 그리기
# import matplotlib.pyplot as plt
# import numpy as np
#
# x = np.linspace(0, 4 * np.pi, 2000)
# y = np.sin(x)
# y2 = np.cos(x)
# y3 = np.tan(x)
#
# plt.plot(x, y, color='red', label='sine')
# plt.plot(x, y2, color='blue', label='cosine')
# plt.plot(x, y3, label='tangent')
# plt.ylim(-2, 2)
# plt.xlabel('x... |
from typing import List
import os
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from sql_app import crud, models, schemas
from sql_app.database import SessionLocal, engine
load_dotenv()
m... |
import re
from telegram import Bot
from utils import load
from utils.load import _lang, _text
from telegram.utils.request import Request as TGRequest
from threading import Thread
import subprocess
_cfg = load.cfg
size_object = ""
size_size = ""
size_info = ""
def simple_size(update, context, item, size_chat_id, size_... |
"""
Given a string s, find the longest palindromic substring in s. You may assume that
the maximum length of s is 1000.
"""
def longestPalindrome(s):
if not s:
return s
res = ""
for i in range(len(s)):
j = i + 1
while j <= len(s) and len(res) <= len(s[i:]):
if s[i:j] =... |
x=float(input("Digite um numero: "))
j=0
d=1
g=1
s=0
b=1
c=0
while(x>j):
g=1/(b*(3**c))
s=s+(g*d)
c=c+1
b=b+2
j=j+1
d=-d
m=(12**0.5)*s
m=round(m,8)
print(m) |
from googleapiclient.discovery import build
API_KEY = 'AIzaSyAnVlazTy4mQv18h9KJBPemnqpKFlEb7Nk'
youtube = build('youtube','v3',developerKey = API_KEY)
request = youtube.search().list(
part='snippet', #required parameter
safeSearch="none",
type='video',
q = 'What is love haddway'
)
response = request.... |
#coding=utf-8
from send_mail import *
import os,sys
#os.system('raspistill -v -o test.jpg -w 640 -h 480 -t 30000 -tl 2000 -o image%04d.jpg')
sendMultipartMail('test image', sys.argv[1:], subject=u'testimage')
|
def skew(Seq):
sk = 0
location = []
sk_list = []
for i in range(len(Seq)):
location = []
if Seq[i] == "C":
sk = sk -1
if Seq[i] == "G":
sk = sk +1
# (i,sk)
location.append(i)
location.append(sk)
sk_list.append(location)... |
# -*- coding: UTF-8 -*-
import os
import sys
os.chdir(sys.path[0])
c1="sh & "
#查看当前 ls,相对于windows的dir命令
c2='ls'
#查看当前绝对路径
#c2='pwd'
#查看隐藏文件
#c2='ls -a'
#查看sample_data文件夹的内容
#c2="ls -l ./sample_data"
#查看树形目录结构,需要先安装模块,apt-get install tree -y
#c2="tree"
#生成隐藏文件夹,文件夹前面加个“.”,表示隐藏文件
#c2='mkdir .hide'
#下载文件,用-P指定保存目录... |
# Functions
from rz_import_statements import *
##################################################
# Function dependent on standard libraries only, #
# e.g. pandas, numpy, scanpy #
##################################################
def oset(a_list):
"""given a list/1d-array, returns an ordered set (list)"""... |
from merge_account import *
from Account import *
#0 = ID, 1 = Account_number, 2 = card_number, 3 = account balance
def check_balance(account_number):
acc_data = getData(account_number)
bal = acc_data[3]
return bal
|
from django.db.models import Manager, Q
from django.utils.timezone import now
__author__ = 'zz'
class PublishManager(Manager):
def publish(self, for_user=None):
if for_user is not None and for_user.is_staff:
return self.all()
return self.filter(
Q(publish_date__lte=now())... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.