text
stringlengths
8
6.05M
#!/bin/env python3 # Search algorithms #from . import map_utils as utils import heapq def backtracking(parents, agent_cord, goal_cord): path = [goal_cord] while path[-1] != agent_cord: path.append(parents[path[-1]]) path.reverse() return path def manhattan_heuristic_function(agent_cord, goal_...
''' FileServer is a library with a file-like interface for reading and writing, most of which is exposed by the BundleRPCServer for calling remotely. The core method that opens files handles, open_file, is NOT exposed as an RPC method for security reasons. Instead, alternate methods for opening files (such as open_tem...
#!/usr/bin/python import numpy as np import pylab as py from COMMON import grav, light, hub0, yr, mpc, msun, week, h0, omm, omv import COMMON as CM from Formulas_AjithEtAl2008 import apar, bpar, cpar, xpar, ypar, zpar, kpar import Formulas_AjithEtAl2008 as A8 from scipy import interpolate factor=1. detector='ALIGO' to...
#build watershed image set #last update 4/23/2014 import urllib widList = [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, ...
from flask import Flask, g, render_template, request, send_from_directory from sounds import controller as c_sounds from sounds.model import sounds_dir from helpers import languages import sqlite3 import os app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return render_template('index.html', la...
#!/usr/bin/env python3 import sys import math try: fp= open("input.txt","r") fuel= 0 part1_fuel=0 lines= fp.readlines() for l in lines: try: i= int(l.strip()) new_fuel= math.floor(i/3)-2 fuel+= new_fuel part1_fuel+= new_fuel while new_fuel >= 9: new_fuel= math.floor(new_fuel/3)-2 fuel+= ne...
from PIL import Image from scipy import misc from keras.constraints import maxnorm from keras.models import Sequential from keras.layers import Dense, Flatten, Conv2D, Dropout, MaxPooling2D import matplotlib.image as mpimg import numpy as np import tensorflow as tf import cv2 import os """ Data collection and preproc...
from flask import Blueprint, redirect, render_template, url_for, flash, session, request from .__init__ import db roles = Blueprint('roles', __name__, template_folder='templates', static_folder='static') @roles.route('/roles/edit') def editRoles(): if not session: return redirect(url_for('auth.login')) ...
from bitstring import ConstBitStream, ReadError from .reporter import Reporter # How many updates we want, 100 would be every percentage. 4 would be every 25%. UPDATES = 100 def read(config, file_name): """ Read binary file into an array of unsigned integers. :param config: dict - Config values from the...
# coding=utf-8 from django.core.management.base import BaseCommand, CommandError from mulan.models import Order, OrderHistory class Command(BaseCommand): def handle(self, *args, **options): if OrderHistory.objects.count() == 0: for order in Order.objects.all(): order_history = O...
# -*- coding: utf-8 -*- """ Define image properties @author: peter """ import cv2 import numpy as np class png_gray(object): def __init__(self, image_path, isPositive ): self.image = cv2.imread( image_path )[:,:,0] self.integral = self.integral_image(self.image) self.isPosit...
import sys import string import logging from util import mapper_logfile logging.basicConfig(filename=mapper_logfile, format='%(message)s', level=logging.INFO, filemode='w') def mapper(): ''' For this exercise, compute the average value of the ENTRIESn_hourly column for different weath...
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. ############################PARA LA TABLA USUARIO EN LA BASE DE DATOS############################### class User(AbstractUser): #A partir de ahora la tabla de usuarios para la autenticacion es esta (User) y el d...
# encoding=utf8 """ Author: 'jdwang' Date: 'create date: 2017-01-13'; 'last updated date: 2017-01-13' Email: '383287471@qq.com' Describe: """ from __future__ import print_function from regex_extracting.extracting.common.regex_base import RegexBase __version__ = '1.3' class Brand(RegexBase): ...
import os import sys from src.tcp import read_request, handle_request, write_response from src.tcp.tcp_server import create_server_socket, accept_connection def serve_client(client_socket, cid): child_pid = os.fork() if child_pid: client_socket.close() return child_pid request = read_req...
#!/usr/bin/python import fractions den = 1 nom = 1 for i in range(1, 10): for j in range(1, i): for k in range(1, j): if (k * 10 + i) * j == k * (i * 10 + j): den *= j nom *= k print(den / fractions.gcd(nom, den))
from MSLLib.MSL import run run(""" COM This is a simple calculator COM Take user input for the math GET math Type the math equasion you want to solve: COM Calculate the equasion and store it in the "$&maths" variable CAL outmath $&math COM Print the equasion and the answer PRL $&math = $&outmath! """)
../../Integrate-Exp-Data.py
from room import Room from secrets import Secrets from decision import Decision from challenge import Challenge from randomiser import Random import yaml, os class Scenario(object): def __init__(self, name, image=None, text = None): self.rooms = {} self.name = name self.image = image self.text = text sel...
from string import join from datetime import datetime def get_between(string, sep1, sep2): tmp = string.split(sep1)[1] return tmp.split(sep2)[0] ids = file('ids.txt', 'r') names = file('titles.txt', 'r') times = file('times.txt', 'r') outf = file('edges.csv', 'w') for iline in ids: nameline = names.readl...
from folium import Marker from sunnyday import Weather from geopy.distance import geodesic from geopy.geocoders import Nominatim class Address: def __init__(self, area, zone, city, country='India'): self.area = area self.zone = zone self.city = city self.country = coun...
# coding=utf-8 import os import sys import unittest from time import sleep from selenium import webdriver from selenium.common.exceptions import NoAlertPresentException, NoSuchElementException sys.path.append(os.environ.get('PY_DEV_HOME')) from webTest_pro.common.initData import init from webTest_pro.common.model.ba...
# coding: utf-8 # # Tools for visualizing data # # This notebook is a "tour" of just a few of the data visualization capabilities available to you in Python. It focuses on two packages: [Bokeh](https://blog.modeanalytics.com/python-data-visualization-libraries/) for creating _interactive_ plots and _[Seaborn]_ for c...
import loader import pyautogui import time import json import os import distutils.dir_util pyautogui.FAILSAFE = True def main(): generateFiles() generateFileProperties() createSave() def generateFiles(): try: distutils.dir_util.mkpath(pathing('SaveGames')) return False except FileExistsError: pass de...
#!/usr/bin/python3 ''' DBStorage schema using SQLAlchemy and MySQL ''' import pymongo from pymongo import MongoClient from models.base_model import BaseModel import models import os class DBStorage: ''' Main database storage class ''' __collection = None __client = None def __init__(self): ...
import flask from flask import render_template from helpers import json_method from standalone import get_queue_and_start app = flask.Flask(__name__) logger = app.logger queue = None @app.route('/') def index(): global queue if queue is None: queue = get_queue_and_start() return ...
n=int(input()) f=1 for x in range (n,1,-1): f*=x print(f)
from time import sleep from enum import Enum import napari import numpy as np import psygnal from napari.qt.threading import thread_worker BOARD_SIZE = 14 INITIAL_SNAKE_LENGTH = 4 class Direction(Enum): UP = (-1, 0) DOWN = (1, 0) LEFT = (0, -1) RIGHT = (0, 1) class Snake: board_update = psygna...
import os from PIL import Image def argumanetation(path, name): label = name[-7:] id = str(int(name[:-7])+300) newName = id + label img = Image.open(path+name) img = img.transpose(Image.ROTATE_90) # rotation 90 #img = img.transpose(Image.ROTATE_180) # rotation 180 #img = img.transpose(Im...
from django.core.cache.backends import memcached class MemcachedCache(memcached.MemcachedCache): def _get_memcache_timeout(self, timeout): """Override _get_memcache_timeout so that it accepts 0.""" if timeout == 0: return 0 else: return super(MemcachedCache, self)._get_memcache_timeout(time...
import socket def create_command_socket(host, port): sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(1) return sock def create_data_socket(client): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Connec...
import os import smtplib, ssl def send_confirmation_email(receiver_email, alumni_uuid): port = 465 # For SSL smtp_server = "smtp.gmail.com" sender_email = os.getenv('SENDER_EMAIL') password = os.getenv('EMAIL_ACCOUNT_PASSWORD') confirmation_link = f"https://alumni-frontend.herokuapp.com/confirm/...
"""Define the command-line interface for the iterator program.""" import typer from factorialmaker import display from factorialmaker import factorial def main( # TODO: Add a typer option parameter for the --iterative command-line argument # TODO: Set the default value of this argument to be False # TOD...
# Generated by Django 2.2.4 on 2019-08-24 10:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('residents', '0001_initial'), ] operations = [ migrations.CreateModel( name=...
def solution(N, stages): answer = [] player = len(stages) for i in range(1, N + 1): if player == 0: answer.append([i, 0.0]) else: answer.append([i, stages.count(i) / player]) player -= stages.count(i) answer.sort(key=lambda x: -x[1]) return [answ...
# Copyright (C) 2012-2013 Claudio Guarnieri. # Copyright (C) 2014-2018 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. def has_com_exports(exports): com_exports = [ "DllInstall", "DllCanUnloadNow", ...
import numpy as np import pandas as pd import re import tkinter as tk df = pd.read_html('data.html', header=0, encoding='utf-8')[0] gk = {} dl = {} dc = {} dr = {} dm = {} mc = {} ml = {} mr = {} aml = {} amr = {} amc = {} fs = {} ts = {} for i in range(len(df)): player = df.iloc[i] pos = player['Position'] ...
from django.dispatch import Signal badge_awarded = Signal(providing_args=["badge"])
# shell utilities import shutil shutil.copyfile('old', 'new') shutil.move('old', 'new')
from __future__ import unicode_literals __version__ = '2019.03.01'
import unittest from katas.kyu_7.two_to_one import longest class LongestTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(longest('aretheyhere', 'yestheyarehere'), 'aehrsty') def test_equals_2(self): self.assertEqual(longest( 'loopingisfunbutdangerous', 'lessda...
"""Utilities available to other modules.""" import typing as t import pandas as pd def get_metadata( num_train_episodes: int, artificial: bool, num_base_models: int = 4 ) -> t.Tuple[pd.DataFrame, pd.DataFrame]: metadata_path = ( f"metadata/metafeatures_{num_train_episodes}" f"{'_artificial' ...
from django.conf.urls import url from . import views urlpatterns = [ url(r'dashboard/$', views.dashboard, name="user_dash"), url(r'dashboard/admin/$', views.dashboard_admin, name="user_dash_admin"), url(r'user/new/$', views.user_new, name="user_user_new"), url(r'user/create/$', views.create_new, ...
from ipwhois import IPWhois obj = IPWhois('16.58.214.142') res1 = obj.lookup_whois() print(res1) res2 = obj.lookup_rdap() print(res2)
from .common import assert_dataservice_processor_data def test_bills(): assert_dataservice_processor_data("bills", "bills", [{'id': 5, 'kns_num': 1, 'name': 'חוק שכר חברי הכנסת, התש"ט-1949'}, {'id': 20, 'kns_num': 7, 'name': 'חוק מקצועות...
# -*- coding:utf-8 -*- import sqlite3 import re import requests # 去重列表 medicine_name_list = [] # 药物ID medicine_id = [0] # 获取疾病大类例如:肝炎的子链接 def get_sub_url(): html = requests.get('http://www.a-hospital.com/w/%E8%A1%A5%E9%93%81%E5%92%8C%E8%A1%A5%E7%A1%92%E7%9A%84%E8%8D%AF%E5%93%81%E5%88%97%E8%A1%A8') li = re.fi...
vocales = "aeiou" for vocal in vocales: print(vocal.upper())
DAEMON_VERSION='2.0' SOCKET_PATH='/tmp/pywalfox_socket' PYWAL_COLORS_PATH='~/.cache/wal/colors' LOG_FILE='daemon.log' LOG_FILE_COUNT=1 LOG_FILE_MAX_SIZE=1000*200 # 0.2 mb BG_LIGHT_MODIFIER=35 ACTIONS = { 'VERSION': 'debug:version', 'OUTPUT': 'debug:output', 'COLORS': 'action:colors', 'INVALID_ACTION...
# -*- coding: utf-8 -*- """ Created on Thu Jun 7 20:13:26 2018 @author: user 倍數總和計算 """ a=int(input()) b=int(input()) c=[] j=0 sum=0 while a <= b: if (a % 4 == 0) or (a % 9 == 0): c.append(a) sum=sum+a a=a+1 for i in c: j=j+1 print("{:<4}".format(i),end="") if j % 10 == 0: ...
import numpy as np import pandas as pd class Analyze(): def __init__(self,Draft): self.draft = Draft self.teams = Draft.teams self.roster_spots = {'RB':2.5,'WR':2.5,'TE':1,'QB':1,'DEF':0,'K':0} #Used by the draft analysis tool. Doesn't deal with flex players yet, so I'm sticking in 2.5s for RB and WR. Not goi...
import os from .common import * DEBUG = True INTERNAL_IPS = ['127.0.0.1'] INSTALLED_APPS += ( 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.environ...
from contextlib import nullcontext class Node: def __init__(self,value=None): self.value=value self.next=None class SlinkedList: def __init__(self): self.head=None self.tail=None def __iter__(self): node=self.head while node: yield node...
from flask import Flask, request, render_template from wordcloud import WordCloud import tempfile app = Flask(__name__) def display_cloud(raw_text): # do some escaping or something, right? print(raw_text) wc = WordCloud().generate(raw_text) fname = tempfile.NamedTemporaryFile(suffix=".png", delete=Fa...
from examples.instrument import generate_experiment_kwargs from examples.development.variants import TOTAL_STEPS_PER_UNIVERSE_DOMAIN_TASK from morphing_agents.mujoco.ant.elements import LEG from ray import tune import argparse import importlib import ray import multiprocessing import tensorflow as tf BAD_DESIGN = [ ...
from enums import Direction, State, Symbol def encode_number(s): inputs = [] for c in s: for rep in c: inputs.append(Symbol.by_rep(rep)) return inputs def encode(s): inputs = [] for c in s: for rep in str(ord(c)): inputs.append(Symbol.by_rep(rep)) i...
# 卡最后一个样例的时间md N = int(input()) W = list(map(int, input().split())) s = set() for i in range(N): for item in s.copy(): if abs(W[i] - item): s.add(abs(W[i] - item)) if abs(W[i] + item): s.add(abs(W[i] + item)) s.add(W[i]) print(len(s))
from weather_ui import WeatherUi from weather_api import WeatherApi from datetime import datetime as dt from config import data import logging class Comparator: def __init__(self, logger): self.logger = logger self.weather_ui = WeatherUi(logger) self.weather_api = WeatherApi(log...
# import dependancies import scrape_mars.py, pymongo from flask import ( Flask, render_template, jsonify, request, redirect) # constants WIP = "wip<br/>rip" APP = Flask(__name__) CONN = 'mongodb://localhost:27017' CLIENT = pymongo.MongoClient(CONN) DB = CLIENT.marsdb # define functions ...
def get_characters_between(start, end): string = "" start = ord(start) end = ord(end) for character in range(start + 1, end): string += (chr(character) + " ") return string chr_1 = input() chr_2 = input() print(get_characters_between(chr_1, chr_2))
# Generated by Django 3.0.3 on 2021-05-03 19:39 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ticketingsystem', '0004_auto_20210420_2004'), ] operations = [ migrations.CreateModel( name='inven...
#!/usr/bin/env python """ prep-cub.py Process the CUB metadata into something saner """ import pandas as pd import numpy as np train_sel = pd.read_csv('./data/cub/train_test_split.txt', sep=' ', header=None) train_sel = np.array(train_sel[1].astype('bool')) meta = pd.read_csv('./data/cub/images.txt', s...
#!/usr/bin/env python3 from gender_bias import Document import argparse parser = argparse.ArgumentParser() parser.add_argument('document', help="document to analyze") parser.add_argument('-s', help="list sentences", action='store_true') parser.add_argument('-w', help="list words", action='store_true') parser.add_argu...
# environment def setup(): size(800, 500) background(255) stroke(0) strokeWeight(1) noFill() # general axis references (not used for curve control points) alist = [0, 100, 200, 300, 400, 500, 600, 700, 800] # right eyebrow strokeWeight(2) curve(0, 400, alist[4], alist[2...
import random print("안녕하세요. 시간표마법사입니다") print("먼저 자신의 정보를 작성해주세요") print("="*40) name=str(input("이름을 입력하세요:")) student_number=str(input("학번을 입력하세요:")) print("="*40) while True: print("메뉴를 선택해주세요.\n1. 개설 강좌 목록 \n2. 시간표 생성\n3. 수강신청 예상인원\n4. 시스템종료") choice_one=int(input('선택:')) print('='*40) if choic...
# -*- coding: utf-8 -*- # # Copyright 2016 Ramil Nugmanov <stsouko@live.ru> # This file is part of MODtools. # # MODtools is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation; either version 3 of the License,...
class Mensaje: def __init__(self, id_vecino, mensaje): self.id_vecino = id_vecino self.mensaje = mensaje def getId(self): return self.id_vecino def getMensaje(self): return self.mensaje
import numpy as np from control.matlab import * import matplotlib.pyplot as plt from control_self import * ## Inputs for the simulation and unit conversion: m = 1600 ## mass of the vehicle, in kgs kdash = 0.072 ##k' = k/(a*b) - 1 wb = 2.747 ##wheelbase in metres a = wb * 600 / m ##distance from CG to front axle in m b...
import argparse import datetime as dt import json import logging import os import sys import traceback import numpy as np import pandas as pd import requests import calculateCalibrationConstant import Configurator import Scripts.plotFitResults as plotFitResults import vdmDriverII from postvdm import PostOutput def ...
class Solution: def uncommonFromSentences(self, s1: str, s2: str) -> List[str]: dic = {} l1, l2 = s1.split(' '), s2.split(' ') for item in l1: if item not in dic: dic[item] = 1 else: dic[item] += 1 for item in l2: i...
space=" " firstName=input("What is your first name? ") lastName=input("What is your last name? ") location=input("What is your current location? ") age=input("What is your age? ") print("Hi"+space+firstName+space+lastName+"."+space+"You are in"+space+location+space+"and you are"+space+age+space+"years old")
#2048.py #write a program that will open the game at https://play2048.co/ and keep sending up right down left keystrokes to autoamtically play the game from selenium import webdriver from selenium.webdriver.common.keys import Keys import time browser = webdriver.Firefox() browser.get('https://play2048.co/') keySend ...
class student: def __init__(a,name,age): a.name=name a.age=age def say_age(self): print(self.age) s1=student('sdfg',18) #s1.say_age() #student.say_age(s1) class math: pass #print(dir(math)) #print(dir(student)) #print(dir(s1)) #print(s1.__dir__()) print(isinstance(s1,math))
# Write a Python file that uploads an image to your # Twitter account. Make sure to use the # hashtags #UMSI-206 #Proj3 in the tweet. # You will demo this live for grading. print("""No output necessary although you can print out a success/failure message if you want to.""") import tweepy import nltk import requ...
from flask import g import sqlite3 import os import errno import time insert_query = 'INSERT INTO sounds (lang, text, path, created, accessed) values (?, ?, ?, ?, ?)' select_path_query = 'SELECT * FROM sounds WHERE path = ?' select_idd_query = 'SELECT * FROM sounds WHERE id = ?' update_idd_query = 'UPDATE sounds SE...
import pandas as pd import numpy as np # in-memory modelling from sklearn.metrics import mean_squared_error import lightgbm as lgb if __name__ == '__main__': X_train = pd.read_csv('X_train.csv') X_val = pd.read_csv('X_val.csv') X_test = pd.read_csv('X_test.csv') y_train = pd.read_csv('y_train.cs...
# Python Substrate Interface Library # # Copyright 2018-2021 Stichting Polkascan (Polkascan Foundation). # # 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/LIC...
from flask import request, jsonify from werkzeug.security import generate_password_hash import re import json from ..models.models import Users, get_all_users def register_user(): """This method handles the registration of a new user""" data = request.json given_data = { "username": data.get("use...
import cv2 import time import numpy as np #计算程序执行时间的装饰器 def time_test(fn): def _wrapper(*args, **kwargs): start = time.clock() location = fn(*args, **kwargs) print ("%s() cost %s second" % (fn.__name__, time.clock() - start)) return location return _wrapper @time...
a=int(input("ENTER 1 : ")) b=int(input("ENTER 2 : ")) degit=0 while a>0 and b>0: if a%10==b%10: degit+=1 a//=10 b//=10 print(degit)
# Ryan Spies # 3/28/13 # Python 2.6.5 # This script converts .MAP and .MAT files into simple tab delimited text # files for use in matlab #!!!!!!!!!!! Units left in inches and degrees F !!!!!!!!!!!!!!!!!!!!!!! #!!!!!!!!!!! Data must be 6 hour time steps !!!!!!!!!!!!!!!!!!!!!! import os import datetime os.c...
import PyPDF2 pdf_file = PyPDF2.PdfFileReader('super.pdf', 'rb') watermark = PyPDF2.PdfFileReader('wtr.pdf', 'rb') output = PyPDF2.PdfFileWriter() for i in range(pdf_file.getNumPages()): page = pdf_file.getPage(i) page.mergePage(watermark.getPage(0)) output.addPage(page) with open('edited....
# -*- coding: utf-8 -*- from datetime import datetime import pytz from django.contrib.auth import get_user_model from django.core.mail import EmailMessage from progress_analyzer.helpers.helper_classes import ProgressReport def str_to_dt(dt_str): if dt_str: return datetime.strptime(dt_str,"%Y-%m-%d") else: retu...
def main(): print("Syötä kilpailijan nimi ja pistemäärä. Lopeta syöttämällä tyhjä rivi.") rivi = "a" dict = {} summadict = {} nimilista = [] while rivi != "": rivi = input("") if rivi == "": break nimi, numero = rivi.split(" ") numero = str(...
import functools print("We have three helpful functions; filter(), map() y reduce()") print("All of them receive a function and one or more secuences (depending of the number of paramaters that the function receive)") def return_some_prime_numbers(x): return x%2!=0 and x%3!=0 print("For a function like this 'def retur...
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 21:34:02 2019 @author: My """ # Import libraries # math library import numpy as np # visualization library %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('png2x','pdf') import matplotlib.pyplot as plt ...
# -*- coding: utf-8 -*- class BinNode(object): def __init__(self, value, left_child=None, right_child=None): self.lChild = left_child self.rChild = right_child self.value = value def addLeft(self, lChild): self.lChild = lChild def addRight(self, rChild): se...
"""Given a array of numbers, output the array like this: a1 <= a2 >= a3 <= a4 >= a5... """ import unittest def print_list(alist): out = '' for i in range(len(alist)): if i > 0: out += (' <' if i % 2 else ' >') + '= ' out += str(alist[i]) return out class OutputTest(unittest.TestCase): de...
# function 定义 # 无参定义 def say_hello(): """函数定义""" print("hello dear.") say_hello() # 函数调用 # 带有参数的定义 def get_max(a, b): # 形参(形式参数) if a > b: print(a) else: print(b) get_max(3, 5) # 传递实参,与形参位置对应,个数也与形参相对应,会按顺序传参(位置参数) get_max(b=5, a=12) # 关键字参数调用,这里就可以与参数顺序无关了 # ...
# CD to DAPPER folder from IPython import get_ipython IP = get_ipython() if IP.magic("pwd").endswith('tutorials'): IP.magic("cd ..") elif IP.magic("pwd").endswith('DA and the Dynamics of Ensemble Based Forecasting'): IP.magic("cd ../..") else: assert IP.magic("pwd").endswith("DAPPER") # Load DAPPER from co...
# SPDX-License-Identifier: BSD-2-Clause import time import sys import traceback import socket import struct import threading import curses import atexit try: import RPi.GPIO as gpio except: pierr = "Rpi.GPIO not loaded" try: import audiodev import audiospeex except: print('cannot load audiodev.s...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # removeAcentos.py # # Copyright 2015 Cristian <cristian@cristian> import sys import libplnbsi """ Remover acentos de um texto Exemplo: python3 removeAcentos.py <arquivo original> <arquivo sem acentos> """ def main(): PARAMETROS = 3 copiaArquivo = "" if len...
from django.contrib import admin from media.models import * admin.site.register(MediaType) #class TagInline(admin.TabularInline): # model = Tag #admin.site.register(Tag, TagInline) class MediaAdmin(admin.ModelAdmin): model = Media fields = ('is_featured', 'name', 'short_description', 'description', 'views...
from . import temp_views as views from rest_framework.routers import DefaultRouter from django.urls import path, include from . import api_view router = DefaultRouter() router.register(r"", api_view.StakeViewSet, basename="Stake") app_name = "daru_wheel" urlpatterns = [ path("stake", include(router.urls)), ...
''' enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。 enumerate(sequence, [start=0]) sequence – 一个序列、迭代器或其他支持迭代对象。 ''' ''' 常规方法很容易想到,用内外两层循环即可 更加有效的方法是利用 HashMap存储 nums数组的值-索引 ''' class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dict = {} ...
''' @Description: In User Settings Edit @Author: your name @Date: 2019-08-19 20:11:09 @LastEditTime: 2019-09-06 15:27:05 @LastEditors: Please set LastEditors ''' import torch import torch.nn as nn import torch.nn.functional as F from layers import GraphConvolution,GConv class GCNencoder(nn.Module): def __init__(s...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import pytest from pants_release.changelog import Category, Entry, format_notes @pytest.mark.parametrize("category", [*(c for c in Category if c is no...
""" BFS Algorithm - Iterative """ #graph to be explored, implemented using dictionary g = {'A':['B','C','E'], 'B':['D','E'], 'E':['A','B','D'], 'D':['B','E'], 'C':['A','F','G'], 'F':['C'], 'G':['C']} #function that visits all nodes of a graph using BFS (Iterative) approach def BFS(graph,start): queue =...
for number in range(10): print("send email", number+1, (number+1)*".")
import re # Download the Data ! wget -O gdp_data.txt 'https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2001.txt'
"""Sengled Bulb Integration.""" import asyncio import logging _LOGGER = logging.getLogger(__name__) class Switch: def __init__( self, api, device_mac, friendly_name, state, device_model, accesstoken, country, ): _LOGGER.debug("SengledAp...