text stringlengths 38 1.54M |
|---|
import os
import selenium
from selenium import webdriver
import time
from PIL import Image
import io
import requests
from webdriver_manager.chrome import ChromeDriverManager
os.chdir('D:/Workspace/Projects/test2py')
#Install driver
opts=webdriver.ChromeOptions()
opts.headless=True
driver = webdriver.Chrome(ChromeDri... |
import random
import re
import time
from enum import Enum
from typing import Optional, Union
import discord
from discord.ext.commands import CheckFailure
from redbot.core.commands import Cog, Context, check
from redbot.core.i18n import Translator
from redbot.core.utils.chat_formatting import escape as _escape
from red... |
#!/usr/bin/env python
import rospy, Map, Astar, Robot, time
from geometry_msgs.msg import Twist, PoseStamped, PointStamped
rospy.init_node('rwiesenberg_lab3')
robot = Robot.Robot()
goal_sub = rospy.Subscriber('/clicked_point', PointStamped, robot.doWavefront, queue_size=1)
time.sleep(2)
rospy.spin() |
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
class CodePanel:
def __init__(self, master):
self.master = master
self.codePanel = ttk.Frame(master)
master.add(self.codePanel, text="G-Code 编辑器")
self.codeEntry = scrolledtext.ScrolledText(self.codePa... |
import importlib
import inspect
from collections import defaultdict
from functools import partial
from typing import Any, Type, TypeVar
from seedwork.application.command_handlers import CommandResult
from seedwork.application.commands import Command
from seedwork.application.events import EventResult, EventResultSet, ... |
from flask import *
import os, sys, json
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs
path = os.path.dirname(__file__)
app = Flask(__name__)
def getVal(querydata, name):
return querydata[name][0] if name in querydata else ''
# extract tradenark Ids from html content... |
# Copyright 2019 Mycroft AI Inc.
#
# 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 in writin... |
#!/usr/bin/python
import os
import argparse
import sys
import subprocess
GTERM = "/usr/bin/gterm"
MINISH = "/usr/bin/minish"
if __name__ == '__main__':
if not os.path.exists(GTERM):
os.system('sudo ln -s /usr/bin/xfce4-terminal %s' % GTERM)
if not os.path.exists(MINISH):
os.system('minish ... |
#!/usr/bin/python
# Statistics for PO files
import sys, os, re, subprocess, os.path, babel, codecs, time
filelist=['yajhfc/src/yajhfc/i18n/messages',
'yajhfc/src/yajhfc/i18n/CommandLineOpts',
'yajhfc-console/i18n/Messages',
'yajhfc-pdf-plugin/i18n/Messages',
'FOPPlugin/i18n/FO... |
from pypy.interpreter.error import OperationError
from pypy.interpreter import typedef, gateway, baseobjspace
from pypy.interpreter.gateway import interp2app
from pypy.objspace.std.listobject import W_ListObject, W_TupleObject
from pypy.objspace.std.intobject import W_IntObject
from pypy.rlib.cslib import rdomain as... |
#CH03-05 연산자의 우선순위
##################################################################
#사용자로부터 3개의 수를 입력받아서 평균을 출력
x = int(input("첫 번째 수: "))
y = int(input("두 번째 수: "))
z = int(input("세 번째 수: "))
avg = (x + y + z) / 3
print("평균 =", avg)
|
from django.db import models
class MenuEntry(models.Model):
parent = models.ForeignKey('self', blank=True, null=True)
caption = models.CharField(max_length=200)
link = models.CharField(max_length=200)
position = models.FloatField()
def __unicode__(self):
return (unicode(self.parent) + ' /... |
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'brochure.views.home'),
... |
from anvil import RegionReader
from png import output_png
DIRECTORY = "/Users/jtauber/Library/Application Support/minecraft/saves/Jamax (World 2)-2/region"
reader = RegionReader(DIRECTORY)
def get_biomes(cx, cz):
return reader.get_chunk(cx, cz).get("Level", {}).get("Biomes")
def make_colour(features):
r,... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 26 12:46:34 2015
@author: as3g15
"""
import math
def degree(x):
"""Returns x radians converted into degrees"""
return x*(180.0/math.pi)
def min_max(xs):
"""Returns a tuple consisiting of xmin and xmax
in the list xs"""
return min(xs), max(xs)
de... |
# Generated by Django 3.0.6 on 2020-11-09 08:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('materials', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='incomingstockent... |
#!/usr/bin/env python
'''Script to determine guide star options in a
given 2dF field of view.
17 December 2018 - Matt Taylor - alpha development
16 January 2019 - Matt Taylor - added UCAC for guide star catalogue
'''
#-----------------------------------------------------------------------
import numpy as np
from ast... |
from pathlib import Path
from os.path import splitext
from detectron2.structures import BoxMode
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.utils.visualizer import Visualizer
import os
import cv2
import pandas as pd
import random
box20List = ["IMG_170406_035932_0022_RGB4.JPG... |
class Node:
def __init__(self, e: object):
self.element = e
self.parent = None
self.child = []
def insert_child(self, n): # 해당 node에 자식을 삽입할 때 사용하는 함수
self.child.append(n)
def del_child(self, n): # 현재 node의 자식 node 중 특정 node를 제거
for i in self.child:
... |
import unittest
from bst import BST
class BSTTests(unittest.TestCase):
def setUp(self):
self.bst = BST()
self.bst.insert(10)
self.bst.insert(6)
self.bst.insert(15)
self.bst.insert(1)
self.bst.insert(20)
def test_inorder_walk(self):
self.bst.inorder_walk(... |
# https://leetcode.com/problems/find-original-array-from-doubled-array/
"""
An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.
Given an array changed, return original if changed is a doubled a... |
"""User Manager used by Improved User; may be extended"""
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
"""Manager for Users; overrides create commands for new fields
Meant to be interacted with via the user model.
.. code:: python
User.objects # th... |
import sys
c2j_file = open("c2j.txt")
j2c_file = open("j2c.txt")
while 1:
c2j_line = c2j_file.readline().replace('\r', '').replace('\n', '')
j2c_line = j2c_file.readline().replace('\r', '').replace('\n', '')
if c2j_line == '' or j2c_line == '':
exit()
print("C: " + c2j_line)
print("J: " + j2c_line... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Performs project's configuration loading."""
import os
from configparser import C... |
from geopy.distance import geodesic
import datetime
def get_distance_in_km(lprev, lnew):
# l = (lat, lon) tuple
distace = geodesic(lprev, lnew)
distace_in_km = distace.km
return distace_in_km
def get_speed_in_kmph(lprev, lnew, tprev, tnew):
# l = (lat, lon) tuple of lattitude and logitude
... |
import copy
from collections import deque
from collections import defaultdict
from numpy import fft
import time
from activeNote import ActiveNote
from noteParser import Note
from noteProcessors.abstractNoteProcessor import AbstractNoteProcessor
from noteProcessors.continuousNoteProcessor.columnManager import ColumnMa... |
import platform
import sys
from pathlib import Path
PYTHON_VERSION_STR = f"{sys.version_info[0]}.{sys.version_info[1]}"
# Platform logic
if sys.platform == "darwin":
FULL_PLATFORM = "macos" + platform.release().split(".")[0]
elif sys.platform == "win32":
FULL_PLATFORM = "win"
else:
FULL_PLATFORM = "unix"
... |
""" A global dictionary of text variables
"""
#import logging
import pickle
class Dictionary(object):
ENGLISH = "en"
LANGUAGES = [ENGLISH]
__singletons = dict()
def __init__(self, file_path):
with open(file_path, "rb") as dic:
self.__map = pickle.load(dic)
dic.close... |
class Pin:
def __init__(self):
wire = None # attached wire, identification of one of wire's end
return
def connect_node(self, node):
return
def disconnect_node(self):
return
class Instance:
def __init__(self, w, h):
self.w = w
self.h = h
|
class Hospital(object):
def __init__(self, name, capacity):
self.patients = []
self.name = name
self.capacity = capacity
def admit(self, var1, var2):
if len(self.patients) < self.capacity:
self.patients.append(var1)
var1.bed_number = var2
# va... |
import gym
import numpy as np
import math
import matplotlib.pyplot as plt
from collections import deque
env = gym.make('CartPole-v0')
# Prepare the Q Table
# create one bucket for each of the 4 feature
# features are : [cart_position, cart_velocity, pole_position, pole_volecity]
# the first two features are less impor... |
import numpy as np
from scipy.stats import sem
from uncertainties import ufloat
import uncertainties.unumpy as unp
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def Mean_Std(Werte):
s = 1/np.sqrt(len(Werte))
return ufloat(np.mean(Werte), s * np.std(Werte, ddof = 1))
# Wheatstone
Messun... |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Field, Fieldset, HTML, Div, Layout, Submit
from crispy_forms.bootstrap import FormActions
from django import forms
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from core.forms impor... |
#
# PyBullet gym env for Franka Emika robot.
#
# @contactrika
#
import os
import numpy as np
np.set_printoptions(precision=4, linewidth=150, threshold=np.inf, suppress=True)
from gym_bullet_extensions.bullet_manipulator import BulletManipulator
from gym_bullet_extensions.envs.manipulator_env import ManipulatorEnv
c... |
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15, 5)
df = pd.read_csv('graf.csv')
print(df)
df.set_index('Tiempo (segundos)', inplace=True)
df.plot(ylabel='Throughput (Request/sec)',grid=True, figsize=(15, 5), c='b')
plt.show() |
from datetime import datetime
from flask import render_template, session, redirect, url_for
from . import main
from .. import db
from ..models import User
@main.route('/', methods=['GET', 'POST'])
def index():
#return redirect(url_for('.index'))
#return render_tmplate('index.html',form=form, name=session.get(... |
from flask import Flask
# from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__, static_url_path='')
app.config.from_object('config')
# db = SQLAlchemy(app)
from app.routes import index
|
# Copyright 2016 Hewlett Packard Enterprise Development Company LP
#
# 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 applic... |
def backward_string_by_word(text: str) -> str:
return " ".join([i[::-1] for i in text.split(" ")]) |
#este o programa nao aceita
from numpy import*
from numpy.linalg import*
horas=array(eval(input("horas: ")))
zeros=zeros(shape(horas)[0], dtype=int)
for j in range(shape(horas)[0]):
zeros[j]=sum(horas[:,j])
for p in range(shape(horas)[0]):
if (zeros[p]==max(zeros)):
print(p+1)
# esse o programa aceita
from nu... |
'''
def line():
print("---------------------------")
'''
'''
def line(size):
c = '-'
line = c*size
print(line)
'''
def line(size,c='-'):
line = c*size
print(line)
def rectangle(width,height,c='-'):
line=c*width # generated -------
h=0
while (h <= height):
... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks_cwt
from DrawPlots import DrawPlots
from Fft import Fft
import scipy.io.wavfile as wav
# fs, audio_data = wav.read('../wav/pick/normal_pick_4.wav')
# fft = Fft.get_fft(audio_data, 2.75)
#DrawPlots.fft_plot((fft, ), 'log', 'Amplitude... |
import turtle
import winsound
win = turtle.Screen()
win.title("Pong by Sean Moore")
win.bgcolor("black")
win.setup(width = 800, height = 600)
win.tracer(0) # stops window from updating automatically
# Score
score_a = 0
score_b = 0
# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0) # Speed of anim... |
from UIAutomation.Page.Mobile.LongCardPage import LongCardPage
from UIAutomation.TestCase.BaseTestCase import BaseTestCase
from UIAutomation.Utils import get_user_id
from UIAutomation.Utils.HttpWrapper import eject_logged_user
from .FunSmoke004SQL import reduction_transport_contract, get_new_transport_contract, delete_... |
# encoding=utf8
import urllib2
import re
from bs4 import BeautifulSoup
class Tie_Ba_Spider(object):
"""docstring for Tie_Ba_Spider"""
def __init__(self, baseUrl , seeLZ):
super(Tie_Ba_Spider, self).__init__()
self.baseUrl = baseUrl
self.seeLZ = '?see_lz=' + str(seeLZ)
def saveCont(self , mytxt ,filename=N... |
"""added pipeline_catalog logic
Revision ID: f7208a6fdec4
Revises: d809ee2de92e
Create Date: 2016-08-01 19:41:29.335590
"""
# revision identifiers, used by Alembic.
revision = 'f7208a6fdec4'
down_revision = 'd809ee2de92e'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgr... |
double_count = 0
tripple_count = 0
for index, word in enumerate(open('input.txt', 'r', 1)):
found_double = False
found_tripple = False
for char in word:
count = word.count(char)
if (found_double and found_tripple):
break
elif (count == 2 and not found_double):
... |
import argparse
import json
parser = argparse.ArgumentParser(description='Write version of package to env-file', prog='version')
parser.add_argument('--version-file', dest='version_file', help='File storing version number', type=str, required=True)
parser.add_argument('--env-file', dest='env_file', help='File storing... |
import face_recognition
from PIL import Image, ImageDraw
import cv2
import numpy as np
import ffmpeg
import math
import os
# some variables
INPUT_FILE = 'example/horns.mp4' # input video file
SEARCH_FILE = 'example/search.jpg' # image of the face to recognise and replace
REPLACE_FILE = 'example/replace.png' # tran... |
#
# @lc app=leetcode id=389 lang=python3
#
# [389] Find the Difference
#
# @lc code=start
class Solution1:
'''using sort'''
def findTheDifference(self, s: str, t: str) -> str:
s = sorted(s)
t = sorted(t)
for i in range(min(len(s), len(t))):
if s[i] != t[i]:
r... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import requests
from bs4 import BeautifulSoup
from translate import Translator
#gender=f 또는 gender=m 를 url에 포함시킨다 --> 각각 따로 분석하려함
#sellitem = 1을 url에 포함시킨다 --> 현재 판매중인 옷을 입은 사진만 보여줌
#.area=001,002,004,007,003를 url에 포함시킨다 --> 서울지역만 보여줌
#.&age=10,20,30를 ,url에 포함시킨다 -->... |
import os
def check_pid(pid):
""" Check For the existence of a unix pid. """
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
|
__author__ = 'Administrator'
# coding = utf-8
import copy
import datetime
import matplotlib.pyplot as plt
import numpy as np
import os
import socket
import sys
import threading
import time
from ctypes import*
from datetime import datetime
from math import e
sys.path.append(os.path.dirname(os.path.dirname(os.path.absp... |
from gym.envs.registration import register
#---------------------------------------------#
#Dumb Loop - Learning a sequence
register(
id='DumbLoop-v0',
entry_point='Games.Dumb_Loop.loop_perimeter:LoopEnv',
max_episode_steps = 200,
)
register(
id='DumbLoop-v1',
entry_point='Games.Dumb_Loop.loop_of... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import psana
from time import time
from Detector.AreaDetector import AreaDetector
from Detector.GlobalUtils import print_ndarr
import numpy as np
##-----------------------------
ntest = int(sys.argv[1]) if len(sys.argv)>1 else 1
print('Test # %d'... |
from pyrogram import (
Client,
Filters,
Message,
ReplyKeyboardRemove,
InlineKeyboardMarkup,
InlineKeyboardButton
)
@Client.on_message(Filters.create(lambda _, m: m.text == 'My bots / channels / groups') | Filters.command('my'))
async def my_tg_objects_handler(_client: Client, message: Message)... |
import unittest2 as unittest
import sys
import os
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import shorturl.parts
import shorturl.filestore
import shorturl.dirstore
dir_path = os.path.dirname(os.path.realpath(__file__))
class UrlPartTest(unittest.TestCase):
def test(self):
part = shorturl.par... |
import db
def normalize(hashtag):
""" lowercase """
hashtag = hashtag.lower()
return hashtag
def map():
""" create hashtag -> (user_id, tweet_id) list map
frequency of hashtag = len(hashtag_map[hashtag])
rank all hashtags = sorted(hashtag_map.keys(), key = lambda hashtag: len(hashtag_map[hasht... |
#ΔΗΜΙΟΥΡΓΙΑ ΛΙΣΤΑΣ ΜΕ ΤΟΥΣ ΣΥΝΔΥΑΣΜΟΥΣ
def toString(List):
return ''.join(List)
# ΣΥΝΑΡΤΗΣΗ ΠΟΥ ΠΑΡΑΓΕΙ ΤΟΥΣ ΣΥΝΔΥΑΣΜΟΥΣ ΑΠΟ ΤΗ ΛΕΞΗ ΠΟΥ ΔΙΝΩ
# Οι 3 παράμετροι μου είναι:
# 1. Ενα string
# 2. Αρχη του string
# 3. Τέλος του string.
def permute_fun(a, s, e):
if s == e:
print(toString(a... |
"""
通过输入线上的获取第三方验证码图片地址,将其保存到本地image/origin
"""
import json
import requests
import os
import time
import base64
def main():
with open("conf/app_config.json", "r") as f:
app_conf = json.load(f)
# 图片路径
origin_dir = app_conf["origin_image_dir"]
headers = {
'user-agent': "Mozilla/5.0 (Wi... |
# This script is used for implement thrshlhold probing of matched filter response
# generated by mfr.py
# The input image is matched filter reponse with Gaussian filter.
# The output file is the binary image after thresholded by probes.
import numpy as np
import cv2
import sys
import timeit
import copy as cp
import... |
from reading import *
from database import *
# Below, write:
# *The cartesian_product function
# *All other functions and helper functions
# *Main code that obtains queries from the keyboard,
# processes them, and uses the below function to output csv results
# NOTE: the tables used in most examples if not all exampl... |
# cook your dish here
def diet(n,k,a):
b=0
for j in range(n):
b+=a[j]
b-=k
if b<0:
return 'NO '+str(j+1)
return 'YES'
t=int(input())
for i in range(t):
n,k=map(int,input().split())
a=list(map(int,input().split()))
print(diet(n,k,a)) |
# -*- coding: utf-8 -*-
from flask_oauth import OAuth
oauth = OAuth()
from credentials import *
from flask import session
from flask import Flask
from flask.ext.pymongo import PyMongo
app = Flask(__name__, static_url_path='')
mongo = PyMongo(app)
@gFit.tokengetter
def get_gFit_token(token=None):
print 'here\n'
... |
# This class will take care of coding and decoding files from and to
# base64
# This will also take care of converting base64 to string
class B64Ops:
pass |
import sys
sys.path.insert(0, './constraint')
import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
import time
from holder import *
from util import *
from n1 import *
from n2 import *
class WithinLayer(torch.nn.Module):
def __init__(self, opt, shared):
super(WithinLayer, self).... |
import sys
import random
import logging
import numpy as np
import networkx as nx
from pgmpy.models.BayesianModel import BayesianModel
from pgmpy.factors.discrete import TabularCPD
from pgmpy.sampling import BayesianModelSampling
from asciinet import graph_to_ascii
import pcalg
from gsq import ci_tests
logging.basicCon... |
import numpy as np
#from Laser import Laser, Map
from laser import Laser, Map
import math
import matplotlib.pyplot as plt
from copy import copy
height = 467
width = 617
offset_x =0.0
offset_y =0.0
resolution = 0.1
# Create map and laser scans
occ_map = Map.readFromTXT('../map.txt', width, height, offset_x, offset_y, r... |
# 1. Create a dictionary called zodiac with the following inforation.
# Each key is the name of the zodiac
# Aries - The Warrior
# Taurus - The Builder
# Gemini - The Messenger
# Cancer - The Mother
# Leo - The King
# Virgo -The Analyst
# Libra - The Judge
# Scorpio - The Magician
# Sagittarius - the Gypsy
# Capricor... |
import sys
count = int(len(sys.argv))
if(count != 2):
print("Usage: {0} <num>".format(sys.argv[0]))
exit(-1)
num = int(sys.argv[1])
result = 0
while num != 0:
result = result +int(num%10)
num=int(num/10)
print("Sum of digits of {0} is {1}".format(int(sys.argv[1]), result))
|
""":mod:`padak.html5` --- HTML5 template engine
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
|
class Solution(object):
def rainbowSort(self, array):
"""
input: int[] array
return: int[]
"""
if not array:
return
lst = []
sumMinusOne, sumZero, sumOne = self.count(array)
for i in range(sumMinusOne):
lst.append(-1)
fo... |
from csv_loader import CsvLoader
from clustering_analyzer import ClusteringAnalyzer
import df_handler
class MainWrapper:
def __init__(self, df_object):
self.df_object = df_object
def proportion_pressure_of_question(self):
sorted_unique_index = df_handler.get_unique_index(self.df_object)
... |
N, X, Y, Z = map(int, input().split())
S = [tuple(map(int, input().split())) for i in range(N)]
print(sum([Ai >= X and Bi >= Y and Ai + Bi >= Z for Ai, Bi in S]))
|
import time
arr = [22,56,1,34,2,98,5,65,9]
print("unsorted list is ")
print(arr)
for i in range(len(arr)):
min_index = i
for j in range(i+1,len(arr)):
if arr[min_index]>arr[j]:
min_index = j;
arr[i],arr[min_index] = arr[min_index],arr[i]
print("sorted list using selection... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import pandas as pd
from random import randint
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support i... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
from django.http import HttpResponse
from django.views import generic
from .models import Artist, Song
class IndexView(generic... |
#!/usr/bin/env python
"""
Copyright (c) 2018 Alex Forencich
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 rights
to use, copy, modify, merg... |
from enum import Enum
class SeriesStatus(Enum):
Started = 1
Finished = 2
Planned = 3
class UserStatus(Enum):
Watching = 1
Completed = 2
Onhold = 3
Dropped = 4
Planned = 6
|
# 建立一个列表用以保存用户的字典名片
card_list = []
def show_menu():
print("*" * 50)
print("1.新建名片")
print("2.显示全部")
print("3.查询名片")
print("0.退出系统")
print("*" * 50)
def new_card():
print("您正在使用功能[1]--新建名片")
# 1.提示用户输入要添加的用户信息
name = input("请输入要添加的用户姓名:")
age = input("请输... |
from batch_simulator import run_agents_in_environment
#######################################
# Two options about what to do with the agent's log messages in absence
# of a GUI pane
def log_to_console(msg):
print(msg)
def log_null(msg):
pass
########################################
dirt_density = 0.1
w... |
#!/usr/bin/env python3
"""
Alexander Hay
ME449
Assignment 3
"""
import numpy as np
import modern_robotics as mr
# Given: Mlist, Glist, Slist
M01 = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0.089159], [0, 0, 0, 1]]
M12 = [[0, 0, 1, 0.28], [0, 1, 0, 0.13585], [-1, 0, 0, 0], [0, 0, 0, 1]]
M23 = [[1, 0, 0, 0], [0, 1, 0, -... |
import abc
import os
from abc import ABC
from typing import List, NamedTuple
import cpath
from cpath import output_path
from misc_lib import path_join
def normalize255(v, max):
if max==0:
return 0
return v/max * 255
def normalize100(v, max):
if max == 0:
return 0
return v/max * 100
... |
n, mark = input().split(" ")
marks = [int(x) for x in input().split(" ")]
for i in range(len(marks)):
if marks[i] == int(mark):
print(i)
break
else:
print(-1)
|
import sys
import click
from commands.report import report
@click.group()
def cli():
pass
cli.add_command(report)
if __name__ == "__main__":
try:
cli()
except Exception as exc:
print(exc)
sys.exit(1) |
# -*- coding: utf-8 -*-
"""
Created on Tue May 11 21:52:34 2021
@author: Sarat
"""
import rioxarray as rio
import numpy as np
import datetime as dt
import xarray as xr
import pandas as pd
import geopandas as gpd
from shapely.geometry import mapping
import cartopy.crs as ccrs
from cartopy.io.shapereader... |
# This models the data into an object
class PostCode:
def __init__(self, pc_json): # Feed in a json of the API with request
self.status = pc_json['status']
self.result = pc_json['result']
self.postcode = self.result['postcode']
self.quality = self.result['quality']
self.e... |
import numpy as np
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import folium
import plotly.graph_objs as go
import plotly.io as pio
from dash.dependencies import Output, Input
from joblib import load
###########################################... |
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('400x400')
canvas = tk.Canvas(window, bg = 'yellow', height=200, width=400)
image_file = tk.PhotoImage(file='../ins.gif')
imgae = canvas.create_image(10,10, anchor='nw', image=image_file) #anchor是定起始点, NW,N,WE,W,CENTER,E,SW,S,SE
x0,y0,x... |
#!/usr/bin/env python2.7
# -*- coding: utf-8; -*-
"""
This script converts Twitter data from corpus in XML format to a tab separated
value format in which the 1-st field is Tweet's id, the 2-nd field is its
creation time, and the 3-rd field is the actual text.
"""
#####################################################... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Scipy库中的optimiz可以实现matlab中fminunc的功能,来优化函数计算成本和梯度
import scipy.optimize as opt
#高级处理分类的一个信息report
from sklearn.metrics import classification_report as cr
#=================visualizing data
path = 'E:\lessons\ML wu.n.g\coursera-ml-py-master\course... |
from collections import defaultdict
with open("day11.txt") as f:
line = f.read()
initial_list = line.split(',')
x = defaultdict(int)
for count, item in enumerate(initial_list):
x[count] = item
i = 0
relative_base = 0
def run_programme(input_colour, i):
global relative_base
output_count = 0
whi... |
from BeautifulSoup import BeautifulSoup
f = open("main.1","w")
def parse(html):
soup = BeautifulSoup(html)
for link in soup.findAll('img'):
f.write(link.get('src').encode('utf-8')+"\n")
lines = tuple(open("main_jpgs", 'r'))
for i in lines:
parse(i)
|
## normalize.py
## Yuan Wang
from pandas import DataFrame
import pandas
from sklearn.preprocessing import MinMaxScaler, StandardScaler
__DEBUG__ = True
def normalize(df):
"""
Normalizes all feature columns in a given dataframe. Returns a new dataframe.
"""
data = df.values
normalized = scale_ser... |
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class TreeView(QTreeView):
def __init__(self, parent):
QTreeView.__init__(self, parent)
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.setSortingEnabled(True)
|
#877-石子游戏
'''
亚历克斯和李用几堆石子在做游戏。偶数堆石子排成一行,每堆都有正整数颗石子 piles[i] 。
游戏以谁手中的石子最多来决出胜负。石子的总数是奇数,所以没有平局。
亚历克斯和李轮流进行,亚历克斯先开始。 每回合,玩家从行的开始或结束处取走整堆石头。
这种情况一直持续到没有更多的石子堆为止,此时手中石子最多的玩家获胜。
假设亚历克斯和李都发挥出最佳水平,当亚历克斯赢得比赛时返回 true ,当李赢得比赛时返回 false 。
'''
#解法一
'''
1.由于是偶数堆,那么最左边就是奇数位置,最后一位就是偶数位置。
2.那么不管先手取最左边还是最右边,先手的人总可以一直选择奇数位置或者偶数位置的... |
#coding=utf-8
array_num = ['one', 'two', 'three', 'four', 'five', 'six']
for i in range(0,6):
print "array_num %d = %s" %(i, array_num[i])
|
try:
from modules.constants import *
except ModuleNotFoundError:
print('Não foi possível carregar algum módulo.')
def player_move(self):
"""
move o player de acordo com as teclas pressionadas /
moves the player as certain keys are pressed
"""
if self.pressing['Up'] or self.pressing['w'] or ... |
"""
76. Minimum Window Substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
The testcases will be generated such that the a... |
# -*- coding: utf-8 -*-
"""
9-6 文件比较
未完成
"""
import sys,os.path
def compareTxt():
txt1=raw_input("Please enter the first file: ")
txt2=raw_input("Please enter the second file: ")
try:
file1=open(os.path.join(sys.path[0],txt1),'r')
file2=open(os.path.join(sys.path[0],txt2),'r')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.