text stringlengths 8 6.05M |
|---|
'''
- list type
1. 순서가 있다
2. 여러 type의 데이터를 저장할 수 있다.
3. 값 변경 가능
'''
a=[1,2,3]
b=[10, True, "문자열"]
c=[10,20,30]
d=a #id값 복사
print("a id:",id(a))
print("b id:",id(b))
print("c id:",id(c))
print("d id:",id(d))
print("a[0]:",a[0]) #a[0] 값 불러오기
a[0] = 999; # a[0] 값 수정하기
print("a : ",a)
... |
import requests
from bs4 import BeautifulSoup
import time
import re
import random
import xlwt
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
class Get_ip(object):
'''
获取ip信息
'''
def __init__(self):
super(Get_ip, self).__init__()
self.url = 'http://www.ku... |
from math import hypot
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
def __str__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
def __pos__(self):
return Vector(self.x, self... |
yas = 35
emeklilikYasi = 65
simdikiYil = 2020
emeklilikYili = simdikiYil + (emeklilikYasi - yas)
print(emeklilikYili)
print("yılında emekli olabilirsiniz")
|
#!/usr/bin/env python
import numpy as np
import numba
from numba import jit
"""
from cffi import FFI
ffi = FFI()
lib = ffi.dlopen('./test.so')
ffi.cdef('void w3j_ms(double, double, double, double);')
_w3j_ms = lib.___pyx_pw_4test_1w3j_ms
drc3jm = lib.drc3jm_
"""
from test import w3j_ms as _w3j_ms
@jit#(nopython=Tru... |
import sys
import copy
import rospy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
from math import pi
from std_msgs.msg import String
from moveit_commander.conversions import pose_to_list
from urdf_parser_py.urdf import URDF
from pykdl_utils.kdl_kinematics import KDLKinematics
import numpy as ... |
from random import randint
def get_number():
"""Get number from user.
Try until user give proper number.
:rtype: int
:return: given number as int
"""
while True:
try:
result = int(input("Guess the number: "))
break
except ValueError:
print("... |
class DataManager:
def __self__(self, list_of_symbols=None, ):
pass |
from collections import defaultdict
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
order = defaultdict(list)
def traverse(root,level,h):
if root:
order[level].append((h,root.val))
traverse(root.left,level-1,h+1)
... |
import neuron as n
import numpy as np
class Network(object):
#constuctor of the class
"""
@args:
featureLength: count of node in input layer
noOfNeuronsL1: count of nodes in hidden layer
noOfNeuronsL2: count of nodes in output layer
eta
"""
def __init__(self, featureLength, noOfNe... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 10:23:54 2020
@author: Alex
"""
import numpy as np
import matplotlib.pyplot as plt
#import the simulated annealing methods and the 3 dimensional NLL function
from Annealing import Main
from Analysis_Methods import NLL_2
#apply the sim annealing method and calcul... |
# Implement Naïve Bayes method using scikit-learn library
# Use train_test_split to create training and testing part
# Evaluate the model on test part
# importing libraries
from sklearn.naive_bayes import GaussianNB
import pandas as pds
from sklearn.metrics import accuracy_score
from sklearn import metrics
from sklear... |
def gcd(a, b):
for d in range(min(a, b), 0, -1):
if a % d == 0 and b % d == 0:
return d
def lcm(a, b):
return a * b / gcd(a, b)
num_tests = int(raw_input())
for test_index in range(num_tests):
num_sensors = int(raw_input())
sensor_intervals = map(int, raw_input().split())
min_l... |
import pydot
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz/bin/'
rootDir = "project/ceo"
a=["skyblue","yellow"]
x=0
G = pydot.Dot(graph_type="digraph")
node = pydot.Node(rootDir.split('/')[-1], style="filled", fillcolor="green")
G.add_node(node)
for root , dirs ,files in... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 24 11:23:03 2018
@author: HP
"""
#"python is good" ">" "good is python"
#def reverse(s):
# return " ".join(reversed(s.split()))
#s = "python is good"
#print(reverse(s))
#def revers(s):
# s = s.split()
# s.reverse()
# return s
#s = "hi hello how are you"
#pr... |
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.conf import settings
from Teste.models import TesteQuestao, Fontes
#-----------------------AJAX-----------------... |
import random
import app
from physics import Component as PhysicsComponent
from animation import Animation, AnimationFactory
from config import Player as config
# Player controls
class Controls:
END = 0
JUMP = 1
LEFT = 2
RIGHT = 3
GROUND = 4
ATTACK = 5
class State(object):
def __init__(sel... |
numeros1=int(input("Digite o primeiro número:"))
numeros2=int(input("Digite o segundo número:"))
numeros3=int(input("Digite o terceiro número:"))
if numeros1 < numeros2 < numeros3:
print("crescente")
else:
print("não está em ordem crescente")
|
#!/usr/bin/env python
import threading
import logging
import sys
from dockercommon import execute, fix_collectd_file, fix_signalfx_collectd_file, repeated_http_get
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger(__name__)
fix_signalfx_collectd_file()
fix_collectd_file()
execute(... |
import torch
import ZZYResNet18
model = ZZYResNet18.ZZYResNet18_indices(n_classes=10)
model.load_state_dict(torch.load("./cifar_net89.pth"))
model.eval()
conv1 = model.conv1
maxpool = model.maxpool
conv2_x = model.conv2_x
conv2_x_bb1_conv1 = conv2_x[0].conv1
conv2_x_bb1_conv2 = conv2_x[0].conv2
conv2_x_bb2_conv1 = con... |
# matrix는 2차원 list
def Largest(matrix):
height = len(matrix)
width = len(matrix[0])
dp = [[0 for _ in range(width)] for _ in range(height)]
for y in range(height):
for x in range(width):
if y <= 0 or x <= 0:
continue
if matrix[y][x]==1 and matrix[y-1][x]==1 and \
matrix[y][x-1]==1 and matrix[y-1][... |
from src.util.Build import NaveBuilder
from src.util.FabricaNaves import FabricaNavePerdida
from src.cgd import Path
class NavePerdidaBuilder(NaveBuilder):
def __init__(self):
super(NavePerdidaBuilder, self).__init__()
self.build_dano()
self.buildimagem_nave()
self.build_imagem_exp... |
# TODO: shits going kind of slow
import socket, re, itertools, ssl
from time import sleep
from os import strerror
from multiprocessing import Pool, Lock, active_children
from urllib import urlencode
global lock
lock = Lock()
class BrutePasswords(object):
def __init__(self,username,password):
self.username = userna... |
import pandas as pd
df = pd.read_excel(r'C:\Users\jberg\OneDrive - A-T Controls, Inc\pythonMTR\mtrinput.xlsx')
size = []
materiallist = []
material = []
partno = []
component = []
endstyle = []
endoptions = ["BW", "DA", "F1", "F3", "F6", "L1", "L3", "LUG", "TH", "SA", "SF", "SO", "SW", "WAFER"]
# adding ... |
#!/usr/bin/env
# encoding: utf-8
"""
A graph whose nodes have all been labeled can be represented by an adjacency list, in which each row of the list contains the two node labels corresponding to a unique edge.
A directed graph (or digraph) is a graph containing directed edges, each of which has an orientation. That i... |
"""Methods to assist making unit_tests"""
import string
import random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return "".join(random.choice(chars) for _ in range(size))
|
from django.conf.urls.defaults import *
urlpatterns = patterns('scaffold.views',
url(r'^(?P<section_path>.+)$', 'section', name="section"),
) |
#!/usr/bin/env python
#-*- codinig: UTF-8 -*-
#from launch_demo import launch_demo
import rospy
import actionlib
from actionlib_msgs.msg import *
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from nav_msgs.msg import Path
from geometry_msgs.msg import PoseWithCovarianceStamped,Twist
from tf_conversions i... |
../gasp/gasp_target_fitsheader_info_exclude_baddata_permonth.py |
#A string is a sequential set of characters.we can access a character by using bracket operator.
sub = "Python"
print sub[0] #This is going to print the first letter "P"
#Remeber we can't give a float values inside the brackets like sub[1.5]. It gives a TypeError.
print '\n'
#Getting the length of the given string.We h... |
import numpy as np
def compute_Z(X=np.array([[-1,-2],[-2,1],[4,-1],[1,1]]), centering=True, scaling=False):
if centering:
mean = np.mean(X, axis=0, keepdims=True)
print(mean)
print(X)
Z = (X - mean)
print(Z)
if scaling:
std = np.std(X, axis=1, keepdims=True)
Z = np.divide(X, std, where=std!=0)
eli... |
#!/usr/bin/env python
def fizzbuzz(x):
if x % 3 == 0 and x % 5 == 0: return "fizzbuzz"
elif x % 3 == 0: return "fizz"
elif x % 5 == 0: return "buzz"
return x
|
import numpy as numpy
import importlib
import random
import PHY_frame
sf1 = 31
sf2 = 64
lf1 = 11
lf2 = 21
sNi = 1024
lNi = 15120
def short_interleaver(index):
s_int = sf1*index + (sf2*index^2 % sNi)
return s_int
def long_interleaver(index):
l_int = lf1*index + (lf2*index ^2 % lNi)
return l_int
def i... |
from mongoengine import *
import numpy as np
import datetime
import pandas
import matplotlib.pyplot as plt
import sklearn
import sklearn.preprocessing
import sklearn.model_selection
import sklearn.linear_model
from sklearn.ensemble import RandomForestRegressor
import tabulate
import requests, json
import time
import pi... |
#!/usr/bin/python3
import sys
import pytz
from cptv import CPTVReader
local_tz = pytz.timezone('Pacific/Auckland')
reader = CPTVReader(open(sys.argv[1], "rb"))
print(reader.timestamp.astimezone(local_tz))
for i, (frame, offset) in enumerate(reader):
print(i, offset, frame.min(), frame.max())
|
# -*- coding: utf-8 -*-
import os
import re
import yaml
import glob
import docutils
from collections import OrderedDict
from docutils import ApplicationError
from docutils.frontend import OptionParser
from docutils.utils import new_document
from docutils.parsers.rst import Parser
from architect import utils
from archi... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
i, j, result = 0, len(grid[0]) - 1, 0
while i < len(grid) and j >= 0:
if grid[i][j] < 0:
j -= 1
result += len(grid) - i
e... |
from flask import Blueprint, render_template, request, flash, jsonify
from flask_login import login_required, current_user
from .models import Bookmark, Note,User,Profiles,Posts ,competitions, internships_job
from . import db
import json
from datetime import datetime, timedelta
import os
views = Blueprint('views', __na... |
import os
from io import open
import torch
from ..data import Dataset, Field, Example, Iterator
class BABI20Field(Field):
def __init__(self, memory_size, **kwargs):
super(BABI20Field, self).__init__(**kwargs)
self.memory_size = memory_size
self.unk_token = None
self.batch_first ... |
def input(val):
val=eval(input("enter the choose value:"))
a=5
def compaire(val,a):
if a>val:
print("enter the number is greater")
elif(a<val):
print("entered number is greater than")
|
# Create your views here.
# directory: workstatus/mail
from string import*
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
import workstatus.mail.models
from django.core.mail import send_mail
from datetime import datetime
import feedparser
from d... |
# Databricks notebook source
# MAGIC %run "Users/mblahay@gmail.com/Demo Credentials"
# COMMAND ----------
#Setting up snowflake authentication
snowflake_options = {
"sfUrl": "https://op82353.east-us-2.azure.snowflakecomputing.com",
"sfUser": sfUser,
"sfPassword": sfPassword,
"sfDatabase": "NORTHWOODS",
"sfS... |
#!/usr/bin/python
from PyQt4.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt4.QtGui import QAction, QFrame, QLabel, QPalette, QStyle
from PyQt4.QtGui import QItemDelegate, QItemSelection, QItemSelectionModel, QSortFilterProxyModel, QTableView
from MeshDevice import MAP_SIZE
FONT_METRICS_CORRECTION = 1.3
MA... |
#!/usr/bin/env python
from FileTransfer import FtpFileTransfer
import os
import subprocess
import prody
class _main_():
def fetchData():
global wd
wd = str(os.getcwd())
print('All Files will go into the celpp folder')
cred = (wd + '/credentials.txt')
try: #attempts to connect to file ... |
from django.urls import path, include
from rest_framework import routers
import shop.views
router = routers.DefaultRouter()
router.register('categories', shop.views.CategoryViewSet)
router.register('items', shop.views.ItemViewSet,basename='Item')
urlpatterns = [
path('', include(router.urls)),
]
|
#!/usr/bin/env python
#-*- coding: UTF-8 -*_
import os
import pandas as pd
import sys
from Bio import SeqIO
from subprocess import Popen, PIPE
def Parser(folder):
""" Funtion to determined if the files have the format genbank
and to rewrite the file in fasta format """
directory = os.getcwd()
tr... |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import text_sensor
from esphome.const import CONF_ID
from . import EmptySensorHub, CONF_HUB_ID
DEPENDENCIES = ['empty_sensor_hub']
text_sensor_ns = cg.esphome_ns.namespace('text_sensor')
TextSensor = text_sensor_ns.class_('Tex... |
def get_sum(a, b):
if a > b:
a, b = b, a
return sum(xrange(a, b + 1))
|
from __future__ import absolute_import, division, unicode_literals
from json import loads, dumps
from twisted.trial.unittest import SynchronousTestCase
from twisted.internet.task import Clock
import treq
from mimic.rest.swift_api import SwiftMock
from mimic.resource import MimicRoot
from mimic.core import MimicCore... |
import tornado.ioloop
import tornado.httpserver
from config import IS_DEVELOPMENT, PORT
from utils.logging_handler import Logger
from routes import make_app
if __name__ == "__main__":
app = make_app()
if IS_DEVELOPMENT:
app.listen(PORT)
Logger.info("Development Server Running on :: http://0.0... |
class BinaryNode(object):
def __init__(self, value):
self.value = value # Store some arbitrary value
self.left = None
self.right = None
def add_child(self, value):
if value < self.value:
if self.left is None:
self.left = BinaryNode(value)
... |
while True:
s = int(input())
print('Acesso Permitido' if s == 2002 else 'Senha Invalida')
if s == 2002:
break |
import requests
import string
url = ""
username = "admin"
password = "^"
possible_chars = ...
def retrievePasswordLength(url, username):
for x in range(1, 25):
payload = {"username[$ne]":username, "password[$regex]":".{"+str(x)+"}", "login":"login"}
r = requests.post(url, data=payload, verify=Fal... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 25 23:46:27 2018
@author: Angela
"""
def operate(a, b, oper):
"""Apply an arithmetic operation to a and b."""
if type(oper) is not str:
raise TypeError("oper must be a string")
elif oper == '+':
return a + b
elif oper == '-':
retur... |
import dump
from itm import UCWrappedFunctionality
from utils import wait_for
import logging
log = logging.getLogger(__name__)
class Async_Channel(UCWrappedFunctionality):
def __init__(self, sid, pid, channels, pump, poly, importargs):
self.ssid = sid[0]
self.sender = sid[1]
self.receiver =... |
"""
FENICS script for solving the Biot system using iterative fixed stress splitting method w
with mixed elements
Author: Mats K. Brun
"""
from fenics import *
from dolfin.cpp.mesh import *
from dolfin.cpp.io import *
#from dolfin.fem.bcs import *
#from dolfin.fem.interpolation import *
#from dolfin.fem.solving impo... |
#Works doesnt check for alt.input no game loop or score
v_i = ['r', 'p', 's']
import random
player_move = "get the move!"
print("RPS!")
def get_input():
global player_move
player_move = input("Throw: \n")
if player_move.lower() in v_i:
judgement()
else:
print("Bad input")
get_input()
def judgement():
gl... |
from datetime import datetime
def solve(n):
(x0, y0, x1, y1) = n
sx = x1 + (x1 - x0)
sy = y1 + (y1 - y0)
return "{0} {1}".format(sx, sy)
if __name__ == '__main__':
'''
T = int(input()) # number of test cases
tests = []
for i in range(T):
N = input() # number of cycles in te... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import json
import os
import zipfile
from textwrap import dedent
from typing import Any, ContextManager
import pytest
from pants.backend.docker.goals ... |
#!/usr/bin/env python3
from pathlib import Path
import sys
import cv2
import depthai as dai
import numpy as np
import time
'''
Yolo-v3 device side decoding demo
YOLO v3 is a real-time object detection model implemented with Keras* from
this repository <https://github.com/david8862/keras-YOLOv3-model-set> and conv... |
import os
import sys
import pygame as pg
from pygame.constants import DOUBLEBUF
from pygame.locals import *
import asset
import events
from config import SCREEN_HEIGHT, SCREEN_WIDTH
from game_screen.game_screen import GameScreen
from victory_screen.end_screen import EndScreen
from screen import Screen
from title_scre... |
# Generated by Django 3.1 on 2020-08-17 16:51
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('polls', '0005_auto_20200817_1327'),
]
operations = [
migrations.AddField(
... |
#!/usr/bin/env python3.6
# NOTE: requires python 3.6, you get a syntax error otherwise
from dataclasses import dataclass
from typing import List, Set
from dataclasses import field
@dataclass
class FluentArg:
name: str = None
type: str = None
@dataclass
class OperatorResource:
name: str
value: int
@d... |
import sys
import sdl2
import sdl2.ext
from traits.api import Enum, HasTraits
from traitsui.api import Item, OKCancelButtons, View
# import other games here
from Games.air_hockey import AirHockeyGame
from Games.pong2 import PongGame
from Games.hello_world import HelloWorldGame
class GameInfo(HasTraits):
game_mo... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from pants.engine.addresses import UnparsedAddressInputs
from pants.option.option_types import TargetListOption
from pants.option.subsystem import Subsys... |
from setuptools import setup,find_packages
#generate install_requires from requirements.txt file
install_requires=open('requirements.txt','r').read().strip().split('\n')
print(f"install_requires:{install_requires}")
config = {
'name': 'chrombpnet',
'author_email': 'anusri @ stanford.edu',
'license': 'MI... |
#!/usr/bin/env python
# encoding: utf-8
"""
oauth2lib.py
Created by yang.zhou on 2012-10-06.
Copyright (c) 2012 zhouyang.me. All rights reserved.
"""
import logging
import requests
import json
from urllib import urlencode
from urlparse import parse_qs
from tornado.auth import OAuth2Mixin
from tornado.web import asynch... |
import numpy as np
from scipy import interpolate
from scipy import fftpack
from scipy import signal
import math
import pdb
import matplotlib.pyplot as plt
class AScan:
def __init__(self,ref_spectrum,resample,imrange):
self.ref_spectrum = ref_spectrum
self.resampling_table = resample
self.range = imrange... |
import os
import json
class Pyson:
'''Allows for easier manipulation of json files.
It will check if a json file already exists with the given file name and open that, otherwise it will create a new one.
Default datatype is a DICT, but you can pass what you want to it. EX: example=Pyson(file_name,[]) wo... |
from micompy.common.tools.bbmap import BBmap
from micompy.common.tools.checkm import CheckM
from micompy.common.tools.mash import MASH
from micompy.common.tools.hmmer import HMMer
from micompy.common.tools.tool import Tool
class WorkBench(object):
def __getitem__(self, key):
return self.tools.get(key)
... |
import requests
from pymongo import MongoClient
from selenium import webdriver
from bs4 import BeautifulSoup
import time
client = MongoClient('localhost', 27017)
db = client.dbsparta
# 내장 라이브러리이므로 설치할 필요가 없습니다.
# 셀레니움을 실행하는데 필요한 크롬드라이버 파일을 가져옵니다.
chrome_path = '/Users/apple/Desktop/sparta/projects/recycling/chromedrive... |
from flask import Blueprint, g
from sqlalchemy import or_
from grant.utils.enums import RFPStatus
from grant.utils.auth import requires_auth
from grant.parser import body
from .models import RFP, rfp_schema, rfps_schema, db
from marshmallow import fields
blueprint = Blueprint("rfp", __name__, url_prefix="/api/v1/rfps... |
# Copyright 2023 Pulser Development Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
import cv2
import numpy as np
import Detect_lines as dec
import Segmentation as s
import os
# ============================================================================
def reduce_colors(img, n):
Z = img.reshape((-1, 3))
# convert to np.float32
Z = np.float32(Z)
# define criteria, nu... |
x = int(input())
y = int(input())
day = 1
while x < y:
x += x * 0.1 # ежедневное увеличение дистанции на 10%
day += 1
print(day)
|
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" File contain all Tonga decorator
"""
from functools import wraps
from typing import Any, Callable
from tonga.stores.manager.errors import UninitializedStore
__all__ = [
'check_initialized'
]
def check_initialized(func: Callable) -> Any:
... |
"""
defaultRig deformation setup
"""
import maya.cmds as mc
import maya.mel as mm
import glob
from rigTools import bSkinSaver
from . import project
from rigLib.utils import name
def build(baseRig, characterName):
#load skin weights
modelGrp = '%s_model_grp'%characterName
geoList = _getModelGeoObject... |
from bbob3 import bbobbenchmarks
import numpy as np
def getbenchmark(fid, dim, instance=None, zerox=False, zerof=True, param=None):
"""Returns an instance of the specified BBOB function
Keyword arguments:
fid -- the funciton ID (1 to 24)
dim -- the number of dimensions (positive)
instance -- ... |
#!/usr/bin/env python
import os
import jinja2
import webapp2
from random import randint
template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)
class BaseHandler(webapp2.RequestHandler):
def write(self, ... |
from enum import Enum
import sys
class Stack:
m_data = None
def __init__(self):
self.m_data = []
def isEmpty(self):
return self.m_data == []
def peak(self):
ch = None
if (len(self.m_data) > 0):
ch = self.m_data[len(self.m_data)-1]
return ch
d... |
''''
批量下载豆瓣首页的图片
采用伪装浏览器的方式爬去豆瓣网站首页的图片,保存到指定路径你文件夹下
'''
import urllib.request
import re
import ssl
import os
# 用if __name__ = '__main__' 来判断是否执行该文件
# 定义保存文件的路径
targetPath = "F:\\Spider\\03\\images"
def save_file(path):
# 检测当前路径的有效性
if not os.path.isdir(targetPath):
os.mkdir(targetPath)
... |
from __future__ import print_function
import sys
sys.path.insert(0, '../cli_')
from click_shell import shell
import click as c
from cli_ import cli_state
from pprint import pprint
r = cli_state.CliState()
@shell(prompt= 'BuildHunter> ', intro='Welcome to BuildHunter!')
def cli():
username = c.prompt('What is yo... |
import dash_bootstrap_components as dbc
from dash import html
inputs = html.Div(
[
dbc.Input(placeholder="Valid input...", valid=True, className="mb-3"),
dbc.Input(placeholder="Invalid input...", invalid=True),
]
)
|
#!/usr/bin/env python3
from ev3dev2.motor import MoveSteering, MoveTank, MediumMotor, LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D
from ev3dev2.sensor.lego import TouchSensor, ColorSensor, GyroSensor
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4
from ev3dev2.button import Button
import xml.etree.E... |
from functools import reduce
import re
from dataclasses import is_dataclass
from enum import Enum, EnumMeta
from json import JSONEncoder, JSONDecoder
import datatypes
import time
import traceback
from functools import wraps
from exceptions import RetryException
def parse_bool(value):
return str(value).upper() in ... |
# Когда Антон прочитал «Войну и мир», ему стало интересно, сколько слов и в каком количестве используется в этой книге.
# Помогите Антону написать упрощённую версию такой программы, которая сможет подсчитать слова, разделённые пробелом и вывести получившуюся статистику.
# Программа должна выводить для каждого уникаль... |
import csv
import sys
from collections import defaultdict
input_file_name = sys.argv[1]
output_file_name = sys.argv[2]
columns = defaultdict(list) # each value in each column is appended to a list
with open(input_file_name) as f:
reader = csv.DictReader(f) # read rows into a dictionary format
ro... |
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
TESTS = 100
GRID_SIZE = 50
def update_bayes(prob_vector, guess, direction):
A_prob = prob_vector[guess] # Prior probability of the ball being at the given x or y coordinate
B_... |
#!/usr/bin/python
#python instance_creation.py "image_id" "key_name" "instance_type" "subnet_id" "service_name"
import boto3
import sys
image_id = sys.argv[1]
name = sys.argv[2]
key_name = sys.argv[3]
instance_type = sys.argv[4]
subnet_id = sys.argv[5]
service_name = sys.argv[6]
#creating ec2 instance and providing the... |
# 导入python内置的SQLite驱动:
import sqlite3
import os.path
import logging
base_dir = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(base_dir, "word.db")
def create_table():
"""创建表"""
# 连接到SQLite数据库
# 数据库文件是word.db
# 如果文件不存在,会自动在当前目录创建:
conn = sqlite3.connect(db_path)
# 创建一个Curso... |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class SearchBar(FlaskForm):
query = StringField('', validators=[DataRequired()])
search_btn = SubmitField('Search')
|
import dash_bootstrap_components as dbc
from dash import html
placeholder = html.Div(
[
dbc.Placeholder(xs=6),
html.Br(),
dbc.Placeholder(xs=4, button=True),
]
)
|
from collections.abc import (
Callable,
Collection,
Hashable,
Iterable,
Iterator,
Mapping,
MutableMapping,
)
from typing import ClassVar, Generic, TypeVar, overload
from _typeshed import Self, Incomplete
from networkx.classes.coreviews import AdjacencyView
from networkx.classes.digraph impo... |
#!/usr/bin/env python
switches = [
(0, (0, 1, 2)),
(1, (0, 2, 14, 15)),
(2, (3, 7, 9, 11)),
(3, (3, 14, 15)),
(4, (4, 10, 14, 15)),
(5, (4, 5, 7, 14, 15)),
(6, (0, 4, 5, 6, 7)),
(7, (1, 2, 3, 4, 5)),
(8, (6, 7, 8, 10, 12)),
(9, (3, 4, 5, 9, 13))
]
""" sort switch by maxClock "... |
name ="zhang"
password ="123456"
username = input("your name:")
pw = input("your password:")
if name == username and password == pw:
print("welcom login")
else:
print("username or password is wrong") |
import unittest
import sys
import os
try:
from flounder.flounder import Flounder
except ImportError:
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
from flounder.flounder import Flounder
DEVELOPER_ACCESS_TOKEN = 'YOUR_DEVELOPER_ACCESS_TOKEN'
class TestFlo... |
def find_character(li,l):
result=[]
for i in li:
if i.find(l)!=-1:
result+=[i]
return result
print find_character(['hello','world','my','name','is','Anna'],"o")==["hello","world"]
|
import numpy as np
import pandas as pd
class KNN:
def __init__(self, k=7):
self.k = k
def fit(self, X_train, Y_train):
self.X_train = X_train
self.Y_train = Y_train
def predict(self, X_test):
self.y_pred = np.array([])
for x in X_test:
dist = np.sum((x-self.X_train)**2, axis=1)
dist = dist.... |
from matplotlib import pyplot as plt
import numpy as np
#Here is our original data. The format is: [bitcoin price, video games sales, wafer shippments]
#Dollars is the unit for bitcoin price
#Millions of Dollars is the unit for video game sales
#Million of Square Inches (MSI) is the unit for wafer shippments
'''
data ... |
def closest_mod_5(x):
while True:
if x % 5 == 0:
return x
else:
x += 1
x = 31
a = closest_mod_5(x)
print(a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.