text stringlengths 8 6.05M |
|---|
# This file is part of beets.
# Copyright 2019, Jack Wilsdon <jack.wilsdon@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the... |
import os
import sys
import subprocess
import shutil
import time
import fam
sys.path.insert(0, 'scripts')
sys.path.insert(0, os.path.join("tools", "families"))
sys.path.insert(0, os.path.join("tools", "trees"))
sys.path.insert(0, os.path.join("tools", "msa_edition"))
import saved_metrics
import experiments as exp
impor... |
from app import db, login
from flask_login import UserMixin
from flask import url_for, current_app
import base64
from datetime import datetime, timedelta
import os
import json
class PaginatedAPIMixin(object):
@staticmethod
def to_collection_dict(query, page, per_page, endpoint, **kwargs):
re... |
import pandas as pd
import numpy as np
def get_labels():
dir = 'training2017/'
label = pd.read_csv(dir + 'REFERENCE.csv')
label = label.values.tolist() # --> convert test dataframe to list
# print(label)
classes = ['A','N','O','~']
y = np.array([])
file = []
for t in label:
... |
def simple_Bayes(A, B_given_A, B):
"""
A straightforward implementation Bayes formula
Parameters
A_given_B: posterior
A: Prior
B_given_A: likelihood
B: marginal likelihood
"""
A_given_B = (A * B_given_A) / B
return A_given_B
"""
Example 2: easy -- all of the terms are spell... |
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
# Input list for Convolutional code
K = 4 # constraint length
r = 2 # number of output bits per input bit
m = K-1 # memory size
# g = np.array([[1, 1, 1], [1, 1, 0]])
g = np.array([[1, 1, 0, 1], [1, 1, 1, 1]])
matlab_inde... |
a=mymodulept2.employee["salary"]
print(a) |
from django import forms
from django.core.validators import validate_image_file_extension
class ImageUploadForm(forms.Form):
image = forms.ImageField(validators=[validate_image_file_extension]) |
n1 = int(input('Digite um número:'))
n2 = int(input('Digite outro número:'))
r = 0
while r != 5:
print('Escolha uma das opções abaixo')
r = int(input('[1] - Somar\n'
'[2] - Multiplicar\n'
'[3] - Maior\n'
'[4] - Novos números\n'
'[5... |
""" Objects module to hold all the objects for the game
"""
import random
import pygame
from pygame.locals import *
import utils
import numpy as np
class Fish(object):
""" A fish
"""
TURN_SPEED = 0.2
ACCELERATION_AMOUNT = 1
MAX_SPEED = 10
MIN_SPEED = 0
SIGHT_ANGLE = 3.14159/2.0
def ... |
"""Supervision scan directory management.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import abc
import errno
import logging
import os
import sys
import six
from treadmill import fs
from . import _service_b... |
from django.conf.urls import url
from . import views
app_name = 'market'
urlpatterns = [
# /classes/
url(r'^$', views.index, name='index'),
url(r'^makeoffer/$', views.makeoffer, name='makeoffer',),
#url(r'^offers/$', views.offer, name='offer'),
url(r'^makeoffer/(?P<subjectId>[0-9a-zA-Z]+... |
from bottle import route, run, static_file, error, request, get
import os
import paste
# My current working directory
my_dir = os.getcwd()
# Route this API GET request to return invitation templates and query of the language.
# NOTE: Change the route in parenthesis to match your GET requests.
@route('/Brand/invitat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from add_pinyin_key import add_pinyin_key_to_bib_file
def main():
parser = argparse.ArgumentParser(description='Add pinyin keys to chinese bib entries.')
parser.add_argument('input_bib')
parser.add_argument('output_bib')
parser.add_argume... |
# В какой-то момент вам надоело использовать имена файлов с пробелами и вы решили написать программу, которая переименовывает все файлы, содержащие пробелы в имени, заменив группы пробелов на символ подчёркивания "_".
# Для начала нужно написать программу, которая считывает строку и заменяет в ней группы пробельных си... |
import os
import re
import sys
from pathlib import Path
from subprocess import run
from lib.grade import grade
from lib.runner import set_home_path, set_assignment_name
from lib.print import (is_in_quiet_mode, enter_quiet_mode, leave_quiet_mode, print_error,
print_message, print_usage)
DEFAULT_... |
# This is a .py file |
# 学生选课系统
import pickle
import os
import hashlib
import time
import sys
class Admin(object):
"""docstring for Admin"""
def __init__(self, name):
super(Admin, self).__init__()
self.name = name
self.auth = 'admin'
def 创建课程(self):
with open('courses','ab') as f:
new_course = input('请输入新课程信息(课程名称,价格,周期,老师)。... |
#!/usr/bin/python
import math
n = 1000000
arr = [True] * (n + 1)
count = 0
for i in range(2, int(math.sqrt(n)) + 1):
if arr[i]:
j = i * i
while j <= n:
arr[j] = False
j += i
for i in range(2, n + 1):
if arr[i]:
count += 1
if count == 10001:
... |
import random
import torch
import numpy as np
import yaml
import os
import requests
import secrets
from typing import Any, Generator, Iterable, List, Mapping, Optional, Sequence, Sized, Union, Collection
from pathlib import Path
from urllib.parse import urlencode, parse_qs, urlsplit, urlunsplit, urlparse
from logging i... |
"""
Week 3, Day 6: Kth Smallest Element in a BST
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
H i n t s
(1) Try to utilize the property of a BST.
(2) Try in-order traversal.
(3) What if you coul... |
import numpy as np
import pandas as pd
import MARS # MARS (Multivariate Adaptive Regression Splines) regression class
import WindFarmGeneticToolbox # wind farm layout optimization using genetic algorithms classes
from datetime import datetime
import os
import pickle
# parameters for the genetic algorithm
el... |
from django.conf.urls import url
from diary import views
urlpatterns = [
url(r'^add/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.diary_add, name='diary_add'),
url(r'^calendar/month/$', views.month_calendar, name='month_calendar'),
url(r'^(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day... |
## ermittle Farbwerte eines Tennisballs
import cv2
# initialisiere Webcam
cam = cv2.VideoCapture(0)
# definiere Region of Interest
x, y, w, h = 400, 400, 100, 100
# zeige Stream von WebCam an
while cam.isOpened():
# lese frame von WebCam
ret, frame = cam.read()
#frame = cv2.cvtColor(frame, cv2.COL... |
import pytest
from rest_framework.exceptions import ValidationError
from api.users.v1.serializers import UserSignUpSerializer
from api.users.models import User
user_mock = {
'email': 'test@test.gmail.com',
'first_name': 'test',
'last_name': 'test',
'password': '12345678'
}
@pytest.... |
import time
import os
disk = 'C:\\'
path = 'Users\\Виктория\\Desktop\\Для Универа\\Второй курс\\Четвертый семестр\\Прога\\course_python\\'
file_name = str("the time is %s.txt" % (format(time.strftime("%Y_%m_%d-%H_%M_%S"))))
whole_path = os.path.join(disk, path, file_name)
start_time = time.time()
def setup():
w... |
"""
A single layer model, essentially a regression model, to predict the steering images.
Set the variable 'AUGMENT' to determine if you want to run image augmentation.
If AUGMENT is set to be True, the script will flip the images horizontally in each batch and add it to the training data.
"""
import os
import cv2
fro... |
import maya.cmds as cmds
def rotateImage(objName, deg):
for x in range(0, 360/deg):
l = 'x'+str(x) + 'yna' + 'zna'
cmds.xform(objName, relative=True, rotation=(deg, 0, 0) )
screenShot(objName, l)
for y in range(0, 360/deg):
l = 'x'+str(x) + 'y'+str(y) + 'zna... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:hua
from flask import Blueprint
# 1. 创建蓝图对象
users_blue = Blueprint('users', __name__)
from . import views |
# Cole Calhoun
# CSCI 164 Homework
# Feb 2, 2016
from __future__ import division
from math import exp, pi
import random
# Chapter 3
# 3)
def chapter3Problem3(n):
estimation = 0
for each in range(n):
randomInt = random.random()
estimation += exp(exp(randomInt))
print "Chapter 3, Proble... |
#!/usr/bin/python3
from sys import argv
arg_len = len(argv)
if __name__ == "__main__":
if arg_len == 1:
print('0 arguments.')
else:
if arg_len == 2:
print('1 argument:')
else:
print('{:d} arguments:'.format(arg_len - 1))
for i in range(1, arg_len):
... |
from .custom_driver import client, use_browser
import time
import json
from .utils import log
from .util_game import close_modal, check_resources, old_shortcut
from .village import open_village, open_city
from .settings import settings
def train_troops_thread(
browser: client, village: int, units: list, interval:... |
from sympy import *
from sympy.stats import Normal, density, E, variance
var("tau nact pact dt std damping scale tau_threshold act_threshold", real=True)
var("dt std alpha scale time_constant", real=True, positive=True)
noise = Normal("noise", 0, std)
alpha = 1 - exp(-dt/time_constant)
#nact = alpha*pact + (1 - alpha... |
import torch
import torch.nn as nn
from deep_depth_transfer.utils.math import generate_relative_transformation
import kornia
class GeometricRegistrationLoss(torch.nn.Module):
def __init__(self, registration_lambda, camera_matrix):
super().__init__()
self._loss = nn.L1Loss()
self._registra... |
print("this is good") |
# Create a short text adventure that will call the user by their name.
# The text adventure should use standard text adventure commands ("l, n, s, e, i, etc.").
import string
import sys
class TextAdventure:
COMMANDS = ['go', 'take', 'drop', 'use', 'inspect', 'inventory', 'help']
INVENTORY_SIZE = 3
EXIT_CHECKPO... |
#!python
import sys
import yaml
import dpath
id_num = sys.argv[1]
namespace = 'test-010-%s' % id_num
manifest = list(yaml.safe_load_all(open(sys.argv[2], 'r')))
kinds_to_delete = {
"ClusterRole": True,
"ServiceAccount": True,
"ServiceAccount": True,
"ClusterRoleBinding": True,
}
keep = []
for x ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from cuisine import package_ensure as ensure
from cuisine import package_install as install
from cuisine import package_update as update
from cuisine import package_upgrade as upgrade
from revolver import contextmanager as ctx
f... |
from django.conf.urls import patterns, include, url
from extra.views import Update
urlpatterns = patterns('',
url(r'^(?P<pk>.+)/update/$', Update.as_view(), name='update'),
)
|
from .diary_add import *
from .diary_detail import *
from .month_calendar import *
|
#_*_coding:utf-8_*_
__author__ = 'Jorden Hai'
from sqlalchemy import create_engine,Table
from sqlalchemy.orm import sessionmaker
from conf import settings
# engine = create_engine(settings.DB_CONN)
# engine = create_engine(settings.DB_CONN,echo=True)
#创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
SessionCls... |
# -*- coding: utf-8 -*-
"""Tests for v1 API viewsets."""
from __future__ import unicode_literals
from datetime import datetime
from json import dumps, loads
from pytz import UTC
import mock
from webplatformcompat.history import Changeset
from webplatformcompat.models import Browser, Feature
from webplatformcompat.v1.... |
#!/usr/bin/env python
#!coding:utf-8
import struct
files = "/home/quan/桌面/ts/live-2019-05-24_21-48-03.ts"
def Do(files,ff):
f = open(files,"r")
n = 0
while True:
_buf =f.read(188)
if not _buf:
print "已经读取完毕!!"
print "pcr时间为:%d" %pcr_time
return
b... |
import unittest
import vertica_python
from config.db import db_vertica
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.engine.url import URL
def db_connect():
engine = create_engine(URL(**db_vertica), pool_recycle=900)
engine.dialect.supports_sane_rowcount = Fals... |
from datetime import datetime, timedelta
import pymongo
from Utils import Utils
from dbmongo import Database
from geopy.distance import great_circle
class Map_Data:
def __init__(self, type=0, lat=0, lng=0, text=""):
self.type = type
self.lat = lat
self.lng = lng
self.text = text
class n1_MapaclassMaxPB:
... |
import matplotlib.pyplot as plt
from pyrsa.vis import rdm_plot
from pyrsa.vis.colors import rdm_colormap
import pickle
import numpy as np
import scipy
import scipy.cluster.hierarchy as sch
def cluster_corr(corr_array, inplace=False):
"""
Rearranges the correlation matrix, corr_array, so that groups of highly
... |
from datetime import datetime
# dc = {'11.12.12': 1, '10.12.12': 2}
# #
# dc = dict(dc)
#
# a = max(dc.keys())
# #
# # print({k: v for k, v in dc.keys() if k == a})
# # print([k for k, v in dc.keys() if k == a])
#
# for k, i in dc.items():
# print(k, i)
#
# d = '2020-08-20'
# datetime_object = datetime.strptime(d... |
# -*- coding: utf-8 -*-
import urllib2
import time
import urlparse
def download(url,retry=2):
# print "downloading %s" % url
header = {
'User-Agent':'Mozilla/5.0'
}
try:
req = urllib2.Request(url,headers=header)
html = urllib2.urlopen(req).read()
except urllib2.HT... |
import sys
import getopt
import errno
import os
from pathlib import Path
# Total number of files in chosen datasets
total_files = 0
# Default score of all prediction
score = {}
# All prediction outputs by your algorithm
all_predictions = {}
# When predicting files outside of chosen datasets
class DatasetsNotChosenExc... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
def factorial(n):
if n == 1:
return n
return n * factorial(n - 1)
assert factorial(3) == 6
assert factorial(5) == 120
explain = 5 * (5-1) * (4-1) * (3-1) * (2-1)
assert explain == factorial(5)
|
from datetime import datetime, timedelta
import pendulum
from airflow import DAG
from airflow.contrib.operators.spark_submit_operator import SparkSubmitOperator
from airflow.models import Variable
local_tz = pendulum.timezone("Asia/Tehran")
default_args = {
'owner': 'mahdyne',
'depends_on_past': False,
's... |
# -*- coding: utf-8 -*-
# @Author: Maximus
# @Date: 2018-03-19 19:08:39
# @Last Modified by: mom1
# @Last Modified time: 2018-04-27 11:19:28
import sublime
import sublime_plugin
import os
import time
import re
import json
import hashlib
import imp
import Default.history_list as History
import RSBIDE.external.symdb ... |
from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QFrame, QDesktopWidget
from PyQt5.QtGui import QPainter, QColor, QPen, QBrush
from PyQt5.QtCore import Qt, QTimer, QTime
def drawLines(qp):
# print(self.t.elapsed())
pen = QPen(Qt.black, 2, Qt.SolidLine)
pen_dash = QPen(Qt.black, 2, Qt.DotLi... |
import matplotlib
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, \
precision_recall_fscore_support
def beautify_treatment(treatment, treatment_dict):
return t... |
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
def main():
"""
Dealing with errors and exceptions such as HTTP and URL errors
:return:
"""
try:
html = urlopen("http://pythonscraping.com/pages/page1.html"... |
import math
while(True):
IN = input().split(' ')
w = int(IN[0])
h = int(IN[1])
if w == 0 and h == 0:
break
if (2*math.pi*h/3) <= w:
v1 = (math.pi*(h**3))/27
else:
r = w/(2*math.pi)
v1 = math.pi*(r**2)*(h-(2*r))
r = h/(2*(math.pi+1))
if 2*r > w:
r... |
""" Script to check neutrons simulated with JUNO detsim (neutron initial momentum uniformly distributed from 0.001 MeV
to 30 MeV within radius of R<16m)
To check the delayed cut (delayed energy cut, neutron multiplicity cut, time cut and distance cut):
Four important things can be checked with this script... |
#!/usr/bin/python3
# Filename : feibonashulie.py
# Author by : Lily
def recurfibo(n):
# 递归函数 输出斐波那契数列
if n <= 1:
return n
else:
return (recurfibo(n-1)) + recurfibo(n-2)
# 获取用户输入
nterms = int(input("您要输出几项?"))
if nterms <= 0:
print("请输入正数")
else:
print("斐波那契数列:")
for i in ... |
#!/usr/bin/env python
import random
import rospy
from turtlesim.srv import Spawn
def spawn_init_hunter():
rospy.init_node('spawn_init_hunter', anonymous=False)
rospy.wait_for_service('spawn')
try:
serv_func = rospy.ServiceProxy('spawn', Spawn)
response = serv_func(x=random.uniform(0, 10... |
def gcd(x,y):
if(x<y):
temp=x
x=y
y=temp
for i in range (0,y):
if y!=0:
r=x%y
x=y
y=r
else:
break
r=x
return r
gcd1=gcd(12,30)
print(gcd1)
|
from common.run_method import RunMethod
import allure
@allure.step("通用/资源/更新资源信息")
def src_updateSrcInfo_post(params=None, body=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return: 默认jso... |
from urllib import request
from bs4 import BeautifulSoup
url = "http://www.baidu.com"
rsp = request.urlopen(url)
content = rsp.read()
soup = BeautifulSoup(content,'lxml')
#bs自动转码
content = soup.prettify()
print("==" * 12)
print(soup.head)
print("==" * 12)
print(soup.meta)
print("==" * 12)
print(soup.link)
print(s... |
import math
from typing import Optional, Tuple
import torch
from torch import nn, Tensor
from torch.nn import init
from torch.nn.modules.utils import _pair
from torch.nn.parameter import Parameter
from torchvision.extension import _assert_has_ops
from ..utils import _log_api_usage_once
def deform_conv2d(
input:... |
#!/usr/bin/python
from PyQt4.QtCore import * # Qt core
from PyQt4.QtGui import * # Qt GUI interface
from PyQt4.uic import * # ui files realizer
from PyQt4 import QtGui, uic
from brewtroller import *
from mash import *
from functools import *
from matplotlib.backends import qt_compat
use_pyside = qt_compat.QT_API ... |
import torch.nn as nn
from model import CRNN, ConvNet, LSTM_FIRST, LSTM_FULL, LSTM_LAST
from dataset import generate_loaders
class Config():
def __init__(self, **kwargs):
self.data_folder = None
self.num_threads = None
self.learning_rate = None
self.batch_size = None
self.num_epochs = None
se... |
class Person: # Person 클래스 정의
def __init __(self, first_name="", last_name=""):
self.first_name = first_name
self.last_name = last_name
person1 = Person("John", "Smith") # ❶
print(person1.first_name, person1.last_name)
person2 = Person() # ❷
person2.first_name = "Robert" # ❸
person2.last_name ... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os
import urllib.request
import json
def download_imgs(urls, folder... |
#!/usr/bin/env python3
import asyncio
import logging
import argparse
from os import linesep
from functools import reduce
from typing import Union
import config
import sync
from filestructs import FileStat
def get_args():
"""Get arguments from command line"""
parser = argparse.ArgumentParser(description='Rsy... |
class TwoSum:
"""
@param: number: An integer
@return: nothing
"""
def add(self, number):
# write your code here
"""
@param: value: An integer
@return: Find if there exists any pair of numbers which sum is equal to the value.
"""
def find(self, value):
# write you... |
# -*- coding: utf-8 -*-
import json
import yaml
my_list = []
my_list.append("YAML")
my_list.append("JSON")
my_list.append({})
my_list[-1]["Cisco"] = True
my_list[-1]["Platform"] = "C819HWD-E-K9"
with open("list_file.yml", "w") as f:
f.write(yaml.dump(my_list, default_flow_style=False))
with open("list_file.json"... |
"""
Definition of TreeNode:
"""
class TreeNode:
def __init__(self, val= None):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param: root: A Tree
@return: Preorder in ArrayList which contains node values.
"""
def createTree(self):
root = TreeNo... |
#!/usr/bin/env python3
#
# Adapted from litex/litex/litex/tools/litex_sim.py
#
# Copyright (c) 2015-2020 Florent Kermarrec <florent@enjoy-digital.fr>
# Copyright (c) 2020 Antmicro <www.antmicro.com>
# Copyright (c) 2017 Pierre-Olivier Vauboin <po@lambdaconcept>
# SPDX-License-Identifier: BSD-2-Clause
import sys
impor... |
print (2<<input())-2
|
# -*- coding: utf-8 -*-
import pylast
import keys as keys
API_KEY = keys.API_KEY
API_SECRET = keys.API_SECRET
username = keys.username
password_hash = pylast.md5(keys.password_hash)
network = pylast.LastFMNetwork(api_key = API_KEY)
per = pylast.PERIOD_OVERALL
class CustomUser(pylast.User):
def __init__(self,... |
import logging
import uuid
from abc import abstractmethod
from typing import Callable, List, Set
import sbol3
import labop
import uml
from labop.execution_engine import ExecutionEngine
l = logging.getLogger(__file__)
l.setLevel(logging.ERROR)
class ExecutionIssue(object):
pass
class ExecutionWarning(Executio... |
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'test_midl_include_dirs',
'type': 'executable',
'sources': [
'hello.cc',
'subdir/... |
import os
# os.environ['PYSPARK_SUBMIT_ARGS'] = '\
# --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.2.0,com.datastax.spark:spark-cassandra-connector_2.11:2.0.1 \
# pyspark-shell'
#
# from pyspark import SparkConf, SparkContext
# from pyspark.streaming import StreamingContext
# from pyspark.streaming.kafk... |
# Written by: Michael Imhof
# Date: 01/31/2020
# Part of Udacity Self-Driving Car Nanodegree
# Advanced Lane Finding Project
# Imports
import numpy as np
import cv2
import pickle
class CameraCalibration(object):
"""Class to calibrate the camera and warp perspective."""
def __init__(self):
# Initiali... |
from scrapy.spiders import Spider
from scrapy.selector import Selector
from dirbot.items import Website
class DmozSpider(Spider):
name = "dmoz"
allowed_domains = ["https://www.pinterest.com/"]
start_urls = ["https://www.pinterest.com/Girl_in_Dublin/followers/"]
def __init__(self,*args,**kwargs):
... |
# -*- coding: utf-8 -*-
"""
目标:提供一个函数能够从网上下载资源
输入:
url列表
保存路径
输出:
保存到指定路径中的文件
要求:
能够实现下载过程,即从0%到100%可视化
"""
# =====================================================
from six.moves import urllib
import os
from urllib.parse import quote
import string
import sys
import json
def download_and_extract(File... |
#!/usr/bin/env python
import sys
sys.dont_write_bytecode = True
import litefs
litefs.test_server() |
from csv import DictReader as dr
from django.core.management import BaseCommand
from ticketingsystem.models import Device, Customer
loaded_error_message = """
If you need to reload the device data from the CSV file,
delete the db.sqlite3 file to destroy the database.
Then do a new migration"""
class Command(BaseCom... |
print("Hello Folks - This is Number guessing game:")
print("_________________")
import random
print("easy is between 1 and 25")
print("medium is between 1 and 100")
print("hard is between 1 and 200")
dif=input("Choose your difficulty by typing 'e' for easy 'm' for medium and 'h' for hard:-")
while True:
if dif !="... |
import requests
import lxml.etree
url = 'https://th.wikipedia.org/wiki/รายชื่อเทศบาลตำบลในประเทศไทย'
resp = requests.get(url)
content = resp.content
tree = lxml.etree.fromstring(content, parser=lxml.etree.HTMLParser())
xpath = '//*[@id="mw-content-text"]/div/table[2 <= position]/tbody/tr/td[2 <= position() and posit... |
import abc
import numpy
import os
from smqtk.representation import SmqtkRepresentation
from smqtk.utils import plugin
from smqtk.utils import merge_dict
__author__ = "paul.tunison@kitware.com"
class DescriptorElement (SmqtkRepresentation, plugin.Pluggable):
"""
Abstract descriptor vector container.
Th... |
from .. import Verb
from ..interface import Adapter
class FunctionAdapter(Adapter):
def __init__(self, function_pointer):
self.fn = function_pointer
def get_value(self, ctx : Verb) -> str:
return str(self.fn()) |
"""
rabbitpy Specific Exceptions
"""
from pamqp import specification
class ActionException(Exception):
def __repr__(self):
return self.args[0]
class ChannelClosedException(Exception):
def __repr__(self):
return 'Can not perform RPC requests on a closed channel, you must ' \
'... |
from flaskr import jwt
from functools import wraps
from flask_jwt_extended import (
verify_jwt_in_request,
get_jwt_claims
)
from utils.errors import NotAuthorizedError
from utils.blacklist_helpers import is_token_revoked
# ROLES VALIDATIONS
# Define our callback function to check if a token has been revoked ... |
import math
class Solution:
def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:
n = len(patience)
def dijkstra(g:List[List[tuple]], src:int) -> List[int]:
dis = [inf] * n
dis[src] = 0
# 堆优化
q = [(0, src)]
whi... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import nntools as nt
# In[2]:
from models.architectures import *
import torch
import torch.nn as nn
from config import args
import os
from data_loader import get_loader
from torch.nn.utils.rnn import pack_padded_sequence
# In[3]:
device = torch.device('cuda' if ... |
# test 1
cars = ["bwm","loslias","toyota","Audi"]
for car in cars:
if car.lower() == "audi":
print(car.upper())
else:
print(car.title())
'''
python中大小写不同,比较得到的结论为不等
如果想忽略大小写进行比较,可以用lower()函数将两者均变为小写(临时)再进行比较
'''
# test 2
if car[2] != "2333":
print("yep")
else:
print("osh")
'''
数值检测等或不等... |
from common.run_method import RunMethod
import allure
@allure.step("小程序/订单/根据订单状态查询订单数量")
def order_api_inner_order_order_countByStatuses_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的... |
import sys
class MyQueue:
#initialize the main, buffer queues
def __init__(self, input=[]):
self.main_stack = [];
self.buffer_stack = [];
self.enqueue(input);
#enqueue-ing a list of input data
def enqueue(self, input_list):
#very basic error checking
... |
print('X si 0 -> 2 jucatori reali')
print('')
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
def tabla():
#print(' %c | %c | %c ' % (board[1], board[2], board[3]))
print(board[0], ' |', board[1], '|', board[2])
print('___|___|___')
print(board[3], ' |', board[4], '|', board[5])
print('___|_... |
lavaRoof = "lava2,{0},0,150,100,lava2.png\n"
lavaFloor = "lava,{0},600,150,100,lava.png\n"
ground = "layer2,{0},600,150,100,layer2.png\n"
roof = "layer3,{0},0,150,100,layer3.png\n"
blueCoin = "blueCoin,{0},{1},57,65,6,3,blueCoin.png\n"
blueDimond = "blueDimond,{0},{1},56,60,6,7,blueDimond.png\n"
redCoin ="redCoin... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013-2015 Marcos Organizador de Negocios SRL http://marcos.do
# Write by Eneldo Serrata (eneldo@marcos.do)
#
# This program is free software: you can redistribute it and/or modify
# it un... |
# author zyyFTD
# Github: https://github.com/YuyangZhangFTD/zyy_ML-DL
"""
this code is for python3
"""
import tensorflow as tf # import tensorflow
c = tf.constant(1.5) # creat a constant
x = tf.Variable(1.0, name="x") # creat a variable
add_op = tf.add(x, c) # creat a... |
import matplotlib.pyplot as plt
import numpy as np
SIZE = 5
plt.rcParams["figure.figsize"] = (SIZE,SIZE)
# Gravity
g = 9.8 # [m/s^2]
class Pendulum():
def __init__(self):
# Base Dimensions
self.base_width = 1 # [m]
self.base_height = 0.5 # [m]
# Wheel Radi... |
from django.shortcuts import render, redirect
from .forms.pizza_app.user import UserForm, UserLoginForm
from .forms.pizza_app.pizza import PizzaForm
from .forms.pizza_app.address import AddressForm
from collections import namedtuple
from typing import ContextManager
from django.contrib import messages
from pizza_app.mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.