text
stringlengths
8
6.05M
from cvs import login from cvs import create_driver from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select def test_items_shopping_basket(): driver = crea...
"""Write a program that prompts for an integer—let’s call it X—and then finds the sum of X consecutive integers starting at 1.""" value_str = input("Enter a value ") sum = 0 count = 0 try: #convert input to int value_int = int(value_str) print("Consecutive sums: ") for i in range(1, value_int + 1): ...
""" This file is part of pysofar: A client for interfacing with Sofar Ocean's Spotter API Contents: Classes used to connect to the Sofar API and return data Copyright 2019-2022 Sofar Ocean Technologies Authors: Mike Sosa et al. """ from datetime import datetime from itertools import chain from multiprocessing.pool i...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-14 17:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("election_snooper", "0001_initial")] operations = [ migrations.AlterField( mod...
import pandas as pd import pymysql as db import logging import sys import os import numpy as np import sqlalchemy from datetime import datetime import json import streamlit as st import pandas as pd def ssh_auto(for_accounts,cred_path): server_port = [] localhost_port = [] cred = pd.read_csv(cred_path) ...
import pytest from spectree.response import Response from spectree.spec import SpecTree from spectree.utils import ( has_model, parse_code, parse_comments, parse_name, parse_params, parse_request, parse_resp, ) from .common import DemoModel, DemoQuery, get_model_path_key api = SpecTree() ...
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # __author__ = caicaizhang # 迭代器 class yield_im(object): def __init__(self,start=0,stop=0): ''' ref blog: http://www.codebelief.com/article/2017/02/python-advanced-programming-generator/ 生成器的工作方式与迭代器相同,可以被视为是迭代器的一种。需要注意的是,生成器只支持一遍的迭代。当...
# ============================================ #datasetName = "RelValTTbar" #datasetPath = "/RelValTTbar_13/CMSSW_7_3_0-MCRUN2_73_V7-v1/MINIAODSIM" #prodTag = "crabTest" import os userName=os.getlogin() outputPath="/store/user/"+userName+"/FlatTrees/"+prodTag+"/" # ============================================ ...
a=int(input()) cnt=0 while(a>0): cnt=cnt+1 a=int(a/10) print(cnt)
#!/usr/bin/env python # -*- coding: utf-8 -*- #准备好r.txt文件,将要索引的单词输入到r.txt文本文件中,每行一个单词,每行为一页. #每页含有两个以上的词,每行的单词间用'|'分开:ab|ac|ad #python pyprint.py,结果写入index.txt文件 #for mac osx f = open('index.txt','w') r = open('r.txt') count = 1 line = len(open('r.txt').readlines()) print >> f,'<?xml version="1.0" encoding="UTF-8"?>...
import pickle TRUE_LABEL_DICT_dir = '../SYN-IG/new-SYN10wLabelDict.pickle' TRUE_NOTE_DICT_dir = '../SYN-IG/new-SYN10wNoteDict.pickle' SAMPLES_dir = '../SYN-IG/new-SYN10w.pickle' #INITIAL_STRATIFICATION = [(0, 0.20), (0.20, 0.40), (0.40, 0.60), (0.60, 0.80), (0.80, 1.01)] INITIAL_STRATIFICATION = [(0, 0.10), (0.10, 0...
print("The number of students involved in are %d" , 8) print("This Github is very nice")
with open("input.txt","r") as f: s=f.read() f.close with open("output.txt","w") as f: f.write(s) f.close
import os, time t=input(u'请输入几点几分关机(格式 05:59) : ') h_off, m_off = t.strip().split(":") h_off, m_off = int(h_off), int(m_off) t = time.localtime() h, m = t.tm_hour, t.tm_min print(f'当前时间:{h}:{m}') if h > h_off: time_shut = h_off*3600 + m_off*60 - h*3600 - m*60 + 24*3600 else: time_shut = h_off*3...
ages = [19, 20, 18] for x in ages: sum += x sum /=len(ages) print(sum)
import os from flask import Flask from database import db import config from dotenv import load_dotenv from authentication import authentication_bp from views.algorithms import algorithms_bp from views.general import general_bp load_dotenv() # creating app app = Flask(__name__) app.config.from_object(os.environ['APP_S...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from PyQt4 import QtGui, QtCore from datetime import datetime, date, time, timedelta import calendar class App(QtGui.QWidget): def __init__(self): super(App, self).__init__() self.initUI() def initUI(self): #Agregamos los nombres de los personajes ...
import os from config import DEBUG, LOCAL_DATABASE_URL, DATABASE_URL, USE_LOCAL_VARIABLES basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = DEBUG TESTING = False CSRF_ENABLED = True SQLALCHEMY_DATABASE_URI = LOCAL_DATABASE_URL if USE_LOCAL_VARIABLES else DATABASE_URL ...
#!/usr/local/bin/python # coding: UTF-8 from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream, API from hyphen import Hyphenator, dict_info from threading import Thread from time import sleep import os import csv import sys import re import string import json import rando...
from collections import deque class MaximumIndependentSet: def __init__(self, bipartite_graph : dict): self.bipartite_graph = bipartite_graph def compute(self): # Hopcroft-Karp gets the maximal matching of the bipartite graph in O(E sqrt(V)) self.hopcrofKarp() # Using Koenigs theorem we can ret...
import pandas as pd import matplotlib.pyplot as plt airquality_df=pd.read_csv('E:\csvdhf5xlsxurlallfiles/airquality.csv')
## ENTIRE RUN FILE FOR THE PUNE PROTOTYPE __author__ = 'hassaankhan' import time import pandas as pd import numpy as np import logging import shapefile log = logging.getLogger(__name__) from __future__ import division from pynsim import Network from pynsim import Simulator from dateutil.relativedelta import relative...
#!/usr/bin/env python # Implementation of https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm import logging def get_max_vote_2(arr): """ Get value that appears at least in n/2 + 1 places in list """ i = 0 m = 0 for x in arr: if i == 0: m = x ...
import time string_1="MNSS Rai" def stringCopies(n): if n<0: time.sleep(1) print("Please enter a positive integer :") else: print("Printing",n,"copies of string ...") time.sleep(1) print(string_1*n) stringCopies(3) stringCopies(-2)
from django.contrib import admin from django.urls import path, include from pyweb.views import base_views urlpatterns = [ path('admin/', admin.site.urls), path('pyweb/', include('pyweb.urls')), path('common/', include('common.urls')), path('', base_views.index, name='index'), ]
from django.apps import AppConfig class AcsysSystemConfig(AppConfig): name = 'acsys_system'
s1,s2,n=input().split() d={} c=0 for i in range(len(s1)): if(s1[i] not in d.keys()): d[s1[i]]=s2[i] else: if(d[s1[i]]==s2[i]): continue else: c+=1 if(c==n or c==0): print("yes") else: print("no")
a=input() n=input().split() s=sorted(n,reverse=True) print("".join(s))
""" 求解编辑距离: ----------- 题意 ----------- 给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 ----------- 题解 ----------- 动态规划: 两个指针i,j分别指向word1和word2 定义dp[i][j]表示word1[:i]转换成word2[:j]需要的最少步骤 初始化时,dp[i][0] = i, dp[0][j] = j 如果word1[i-1] == word2[j-1]时: dp[i][j] = dp[i-1][j-1] /...
"""豆瓣电影 """ import json from urllib.request import urlopen from urllib.parse import urlencode class Movie(): url = 'https://api.douban.com/v2/movie/' def __init__(self): pass def get_subject_by_id(self, movie_id): url = self.url + 'subject/' + movie_id response = urlopen(url) ...
from django.contrib.auth import authenticate from django.contrib.auth.models import User from django import forms from game.models import Game from phase10Scorer.settings import PASSWORD class LoginForm(forms.Form): """ Form used to log in to the web application. """ username = forms.CharField(widget...
from flask import Flask, render_template, request, redirect app = Flask(__name__) @app.route("/") def home(): return render_template("index.html") @app.route("/ninja") def ninja(): return render_template("ninja.html") @app.route("/ninja/<userinput>") def userinput(userinput): if userinput == "blue": ...
l=[100, 10, 5, 25, 35, 14] n=11 mul=1 for i in l: mul=mul*i print(mul%n)
# Copyright (c) Members of the EGEE Collaboration. 2004. # See http://www.eu-egee.org/partners/ for details on the copyright # holders. # # 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 #...
""" This file builds on the C extension _distributions.c and contains python classes that are used to evaluate PDFs and CDFs of distributions and draw samples from a range of distributions. The following distributions are currently implemented - Exponential (http://en.wikipedia.org/wiki/Exponential_distribution) - Log...
import json import datetime import time import os import dateutil.parser import logging import boto3 import re region = 'us-east-1' logger = logging.getLogger() logger.setLevel(logging.DEBUG) ec2 = boto3.resource('ec2', region_name=region) ec2_client = boto3.client('ec2') lex_client = boto3.client('lex-models') # St...
import numpy as np def one_hot_encode_along_channel_axis(sequence): to_return = np.zeros((len(sequence),4), dtype=np.int8) seq_to_one_hot_fill_in_array(zeros_array=to_return, sequence=sequence, one_hot_axis=1) return to_return def seq_to_one_hot_fill_in_array(zeros_array,...
import json import unittest import sqlparse from sje import extractor ONE_LEVEL_JSON = [ {"name": "name", "type": "STRING"}, {"name": "age", "type": "NUMERIC"}, ] NESTED_JSON = [ {"name": "name", "type": "STRING"}, { "name": "metadata", "type": "RECORD", "fields": [ ...
import csv, math strInputFilename = 'PcieTrace.csv' strOutputFilename = 'PcieTrace.log' adminQueueBaseAddress = 0 adminQueueSize = 0 barAddress = 0xDF000000 # Queue Id, SQ Base Address, SQ Size, CQ Base Address, CQ Size, SQ Tail Doorbell, CQ Head Doorbell, SQ Head Pointer QueueTable = [ # Qid, Sq...
# Conway's Game of Life - Python Implementation # Author: Daniel: dan@imdany.com import pygame from config import * # Logic of the Cell class Cell: def __init__(self, gameDisplay, c, r, state=0): self.c = c self.r = r self.state = state self.gameDisplay = gameDisplay ...
from elements.code_elements import GenericElement, CommandElement from abc import abstractproperty from elements.return_types import * class CompareElement(CommandElement): def __init__(self, a: GenericElement, b: GenericElement): if a.return_type != b.return_type and a.return_type is not self.return_typ...
def insertionsort(list): for i in range(1, len(list)): j = i while j > 0 and list[j-1] > list[j]: temp = list[j] list[j] = list[j-1] list[j-1] = temp j -= 1 return list if __name__ == "__main__": list = [55,51,74,86,36,67,88,0,49] print insertionsort(list)
#! /usr/bin/env python """ Author: Zhiqiang Liang Program: fd_faceboxes.py Date: Tuesday, Mar. 12 2019 Description: re-write demo.py functionalities of faceboxes. """ import sys import os import numpy as np import matplotlib.pyplot as plt import cv2 import argparse caffe_root = r'../' # os.chdir(caffe_root) sys.path....
"""Entry point for pydantic-aioredis""" from .config import RedisConfig # noqa: F401 from .model import Model # noqa: F401 from .store import Store # noqa: F401
import base64 encoded = base64.b64encode('user:pass'.encode('UTF-8')).decode('ASCII') print(encoded)
# -*- coding: utf-8 -*- """ Created on Sat May 23 14:54:43 2015 @author: Martin Nguyen """ from __future__ import division import simpy import csv from MonitorClass import Monitor from PatientClass import Patient simulationTime = 500 class SimulationSystem(object): def __init__ (self,size,file_name): self....
import os import pandas as pd import torch import time from train import train from test import test def main(model_name, parameters_name, save_name, cuda_device=0): train_loss_list = [] valid_loss_list = [] train_accuracy_list = [] valid_accuracy_list = [] test_accuracy_list = [] time_list = [] base_path = o...
## Santosh Khadka - Tic Tac Toe Game #Globals row1 = ['-', '-', '-'] row2 = ['-', '-', '-'] row3 = ['-', '-', '-'] def print_start(): print("===============================") print(' Lets play Tic-Tac-Toe!') print("===============================") print("[Type 'exit' to leave anytime.]") prin...
from symbolTable import ST from util import strToBinary16 from lockuptable import getMachineCode def assemblePh3(code): # // out = open("output.txt", 'w') # // linesAgain = open(assemblesFile.name, 'r').readlines() ph3_out = '' addressNumber = 0 for line in code.splitlines(True): if(line.f...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from contextlib import contextmanager def assert_logged( caplog, expect_logged: list[tuple[int, str]] | None = None, exclusively: bool = True ) ->...
# functions that implement the Logistic Regression from scipy import exp, dot, log, array, asarray, linspace, zeros, ones, append import matplotlib.pyplot as plt def sigmoid(z): ''' Compute the Sigmoid function g = sigmoid(z) returns the sigmoid of z z can be a matrix, vector, or scalar ''' ...
import time import numpy as np import scipy.sparse as sps import scipy.sparse.linalg as spsl from Vertex import Vertex from matplotlib import pyplot as plt from true_field import true_field # starting with nu = 0 and Neumann boundary conditions for simple precision matrix class GMRF_Regression: def __init__(self, ...
import sys, os, operator ''' Sorts grouped characters from greatest number of words to least. ''' def sort_grouped(input, output): try: with open(input, 'r') as inputf, open(output, 'w') as outputf: words = {} lineDelim = ": " wordDelim = ", " for line in inputf: line_info = line.strip('\n').split(...
#!/usr/bin/env python import sys import pandas as pd import fetch from progress import ProgressBar USERNAME = 'stephenroller' ACCESS_KEY = '5b22bd3303fe4c21a4463d37cca0353813a56109' MAPPING_URL = 'http://www.image-net.org/api/text/imagenet.synset.geturls.getmapping?wnid=%s' HYPO_URL = 'http://www.image-net.org/api/...
import itertools import sys import classes import string import csv import exceptions class Strand: def __init__ (self, material, name, sequence): """ specifies whether DNA or RNA, gives name, and gives sequence and checks self.correct_type(sequence) """ self.material = material self.name = name self.se...
# Generated by Django 3.0.6 on 2020-05-31 20:33 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import torch from torch.jit import script, trace import torch.nn as nn from torch import optim import torch.nn.functional as F import csv import random import...
# Anki addon for SRS Collector # Author: Eric Kidd <http://kiddsoftware.com/> # # This is free and unencumbered software released into the public domain. # This program comes with ABSOLUTELY NO WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # For more information, ...
OUTPUT = "I don't think you {} today, I think you {} {} {}!".format def alan_annoying_kid(phrase): words = phrase.split() action = ' '.join(words[2:]).rstrip('.') if "didn't" in phrase: return OUTPUT(action, 'did', words[3], 'it') return OUTPUT(action, "didn't", words[2][:-2], 'at all')
from nab.database import Database class AltTitles(Database): """ Adds additional titles for shows and seasons. """ def __init__(self, **shows): """ Args: shows: A structure of titles. """ self.shows = dict((s.lower(), v) for s, v in shows.iteritems()) ...
import simplegui import random x = 500 y = 500 screen_text = "Khoa doesn't do homework" #change screensaver text input field handler def change_text(screensaver): global screen_text screen_text = screensaver def draw(canvas): canvas.draw_text(screen_text,(x,y),20,"Red") def timer_handler(): ...
from __future__ import unicode_literals, absolute_import import django DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } TIME_ZONE = 'America/Chicago' USE_TZ = True LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N =...
#! /usr/bin/env python3.10 from User import User, Credential def create_user(user_name, password): new_user = User(user_name, password) return new_user def save_user(user): user.save_user() def display_user(): return User.display_user() def login_user(user_name, password): check_user = Cred...
from .dataset_utils import get_dataset_per_pixel_mean, make_batch_one_hot, make_single_pattern_one_hot from .theano_utils import make_theano_training_function, make_theano_validation_function, \ make_theano_feature_extraction_function, make_theano_inference_function, LasagneHeNormal from .training_utils import extr...
import sys from loguru import logger from {{cookiecutter.project_slug}}.config import settings async def setup_logger() -> None: if settings.is_debug: level = 'DEBUG' diagnose = True else: level = 'INFO' diagnose = False logger.remove() logger.add( sys.stdout,...
#to run: python turnON.py GPIO_number #where GPIO_number have to be an integer. e.g. 29 import RPi.GPIO as GPIO import sys # Set the GPIO number where LEDs control is conected if len(sys.argv)==2: GPIO_num = str(sys.argv[1]) # e.g. Timelapse else: GPIO_num = 29 #GPIO 29 is used as the default G...
'''David Naccache based Identity-Based Encryption | From: "David Naccache Secure and Practical Identity-Based Encryption Section 4" | Available from: http://eprint.iacr.org/2005/369.pdf * type: encryption (identity-based) * setting: bilinear groups (asymmetric) :Authors: Gary Belvin :Date: 06/2011 ''' from __...
from collections import deque class Vertex: def __init__(self, value, adj_list=None): self.value = value if adj_list is None: adj_list = [] self.adj_list = adj_list class Graph: def __init__(self): self.vertices = [] def insert(self, value, adj_list): ...
# -*- coding: utf-8 -*- # Since NoneType is not actually defined, yet is returned by 'type(None)' NoneType = type(None) def optional(t): if isinstance(t, tuple): return t + (NoneType, ) return (t, NoneType) class Mixin(object): """ Base mixin class used for describing objects that share mu...
import unittest from katas.beta.find_the_middle_element import gimme class GimmeTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(gimme([2, 3, 1]), 0) def test_equals_2(self): self.assertEqual(gimme([5, 10, 14]), 1)
def mean(arr): letters = [] sum_of_digits = total_digits = 0.0 for a in arr: try: sum_of_digits += int(a) total_digits += 1 except ValueError: letters.append(a) return [sum_of_digits / total_digits, ''.join(letters)]
#! /usr/bin/env python3 # # -*- coding: utf-8 -*- ################################################################# # get modbus data from CU and save to log file # Norihito Nov.2020 # # Usage: python client_modbus_sample.py ################################################################# import time import datet...
''' Имплементирајте ги функциите: - Range compression (слајдот број 7 од презентацијата со име Оператори на ниво на пиксели во слика). Функцијата како влезени аргументи треба да има слика над која ќе се направи трансформацијата и параметарот C. ''' import cv2 import math def range_compression(img, c): m, n = im...
#Exercise 1 # n = 1 # while n < 101: # print(n*(n+1)/2) # n += 1 #Exercise 2 Given a number, print its factors. #Exercise 3 # name = "" #empty string is giving an empty value here, b/c variables must be given a value # while name != "clint": # name = input("please say your name is...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-31 20:29 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('catalogues', '0017_auto_20170831_2304'), ] operations = [ migrations.RemoveField( ...
from selenium import webdriver from time import sleep # import xlrd import random import os import time import sys sys.path.append("..") # import email_imap as imap # import json import re # from urllib import request, parse from selenium.webdriver.support.ui import Select # import base64 import Chrome_driver import em...
from wob_data_upload.handles.spark_handle import SparkCassandra from cassandra.cluster import Cluster from django.core.cache import cache from unicodedata import normalize from datetime import timedelta import pandas as pd import numpy as np import time import os def getDevConnection(): cluster = Cluster([os.envir...
# Generated by Django 2.0.5 on 2018-06-28 08:40 import django.core.validators from django.db import migrations, models import django.db.models.deletion import re class Migration(migrations.Migration): dependencies = [ ('calculation', '0038_auto_20180628_0714'), ] operations = [ migratio...
import os import pathlib from setuptools import setup, find_packages # Package meta-data. NAME = "greenponik-sht40" DESCRIPTION = "Read SHT40 through Python3 on raspberry pi" URL = "https://github.com/GreenPonik/GreenPonik_SHT40" EMAIL = "contact@greenponik.com" AUTHOR = "GreenPonik SAS" REQUIRES_PYTHON = ">...
# -*- coding: utf-8 -*- class Solution: def licenseKeyFormatting(self, S, K): S = S.upper() S = "".join(S.split("-")) S = S[::-1] parts = [S[i : i + K] for i in range(0, len(S), K)] return "-".join(parts)[::-1] if __name__ == "__main__": solution = Solution() as...
import numpy as np import sys input_file_path = "in.txt" output_file_path = "out.txt" class TempMatrix: def initializeElements(self): return np.zeros((self.rows, self.columns)) def __init__(self, rows, columns): self.rows = rows self.columns = columns self.elements = self.in...
__author__ = "Narwhale" import socket sk = socket.socket() sk.bind(("localhost",8080)) sk.listen() conn,address = sk.accept() conn.sendall(bytes("Hello world",encoding="utf-8"))
""" Model objects for images. """ from __future__ import absolute_import, division, unicode_literals import attr from json import dumps from mimic.model.rackspace_images import OnMetalImage from mimic.model.nova_objects import not_found from mimic.canned_responses.mimic_presets import get_presets @attr.s class Reg...
import pandas as pd import os import matplotlib.pyplot as plt import numpy as np import statsmodels.formula.api as smf def get_data_Rmagic(): path_data = "../data/ReplicationDataset_ThePriceofForcedAttendance.dta" df = pd.read_stata(path_data) df["grade"] = df["grade"].astype(float) ### Treatment v...
# Crea un archivo de Python llamado for_loop_basic1.py que realice las siguientes tareas. # Básico : imprime todos los enteros del 0 al 150. for x in range(151): print(x) # Múltiplos de cinco : imprime todos los múltiplos de 5 de 5 a 1,000 for x in range(5,1001,5): print(x) # Contar, Dojo Way - imprime e...
# Write a Python program to create a list of empty dictionaries def createEmptyDict(n): listEmptyDict = [] for i in range(n): new_dict = dict() listEmptyDict.append(new_dict) return listEmptyDict n = int(input("Please enter the number of empty dict you want to create :")) output = createEm...
# @Author : bamtercelboo # @Datetime : 2018/07/19 22:35 # @File : model_CNN.py # @Last Modify Time : 2018/07/19 22:35 # @Contact : bamtercelboo@{gmail.com, 163.com} import argparse import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import random im...
def is_balanced(s, pairs): closing_chars = [] pair_dict = dict(zip(pairs[::2], pairs[1::2])) keys = set(pair_dict.iterkeys()) values = set(pair_dict.itervalues()) for a in s: in_keys = a in keys in_values = a in values if in_keys and in_values: try: ...
import tensorflow as tf import tensorflow.contrib.slim as slim import sys sys.path.append('/home/oushu/lixingyu/git_repo/attention_OCR') from tensorflow.contrib import rnn from models import cnn_basenet from config.global_config import CFG import numpy as np class ShadowNet(cnn_basenet.CNNBaseModel): def __init...
import json import requests from urllib.request import urlopen ''' def get_json(url): with urlopen(url) as json_file: json_data = json.loads(json_file.read()) return json_data ''' def get_json(url): response = requests.get(url) return json.loads(response.content.decode('utf-8'))
import minimalmodbus import serial import pandas as pd import time import random # Special Functions Registers. Parameters registers range from 0 - 4095 # Read Only: indicates the total number of parameters TOTAL_NUMBER_OF_PARAM = 4097 # Read Only: indicates the state of the inverter (on/off, cw/ccw, etc.) STATE = 41...
def computepay(h,r): if (h <= 40): return h * r if (h > 40): return 40 * r + (h - 40) * 1.5 * r hrs = input("Enter Hours:") h = float(hrs) rate = input("Enter Rate per hour:") r = float(rate) pay = computepay(h,r) print(pay)
from flask import Flask, render_template from flask_bootstrap import Bootstrap app = Flask(__name__) bootstrap = Bootstrap(app) @app.route('/') def index(): title = 'Flask test' return render_template('index.html', title=title) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
class MaxHeap: def __init__(self, data, attr): self.__data = data self.__attr = attr self.__build() def __build(self): n = (len(self.__data) // 2) - 1 for i in range(n, -1, -1): self.__heapify(i, len(self.__data)) def __heapify(self, parent_index, n): ...
"""Treadmill application environment. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os if os.name == 'nt': from ._windows import WindowsAppEnvironment as AppEnvironment else: from ._linux import ...
import matplotlib.pyplot as plt from matplotlib.ticker import (MultipleLocator) import numpy as np import csv from scipy.integrate import odeint beginYear = 2011 endYear = 2018 endYearSim = 2025 scale = 100000 def f(p0, t, consta, constb, beta): p = p0 d_i = consta[4]-consta[8] d_t = consta[...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-14 20:18:22 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learning # @Version : $Id$ _id = (id for id in range(1,100000)) print(next(_id)) print(next(_id))
""" Train and Evaluation Script of Combined Model AutoEncoder and Classifier. These are trained separatly. """ import numpy as np import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.optim as optim from torch.utils.data import Dataset, DataLoader import matplotl...
# -*- coding: utf-8 -*- ############################################################################# # Copyright Vlad Popovici <popovici@bioxlab.org> # # 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 ...
# coding=utf-8 ##################################### # Imports ##################################### # Python native imports from PyQt5 import QtCore, QtWidgets, QtGui import logging import rospy from rover_arm.msg import ArmStatusMessage from rover_control.msg import GripperStatusMessage ############################...