text
stringlengths
38
1.54M
# 调试添加按照i在for循环里做的test案例执行 # coding=utf-8 import sys sys.path.append("E:\\AppiumProjectAndroid") import unittest import HTMLTestReportCN import threading import multiprocessing from util.server import Server import time # from appium import webdriver # # from business.login_business import LoginBusiness # from util.wri...
#!/usr/bin/env python from flask import Flask import subprocess import os import json app = Flask(__name__) # SERVICE_PORT = os.getenv('PORT', 8000) # APP_NAME = os.getenv('APP_NAME', 'z.py') SERVICE_PORT = os.getenv('PORT') APP_NAME = os.getenv('APPNAME', 'default.py') @app.route("/") def hello(): cmd = ['pyt...
import ctypes testlib = ctypes.CDLL('./libtest.so') #x = testlib._Z7myprintv() x = testlib.myprint() print 'return value: ', x
a3=[] class vertex: def __init__(self,v): self.id=v self.padre=None self.hizq=None self.hder=None self.altura=-1 class arbol: def __init__(self): self.raiz=None def agregar(self,act,ver): if act.id< ver.id: if act.hder!=None: self.agregar(act.hder,ver) else: act.hder=ver ver.padre=act...
# Combination Sum # # Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. # # The same repeated number may be chosen from C unlimited number of times. # # Note: # All numbers (including target) will be positive integers. # Ele...
# Crushing Violence ####################################################################################################################### # # The students of college XYZ are getting jealous of the students of college ABC. ABC managed to beat XYZ in all # the sports and games events. The main strength of the stud...
# # arcus-python-client - Arcus python client drvier # Copyright 2014 NAVER Corp. # # 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 req...
#!/usr/bin/env python # -*- coding: utf-8 -*- import lxml.html import time import datetime import requests url = 'http://landspitali.is' def landspitali(): html = requests.get(url).text root = lxml.html.fromstring(html) space = ' ' strings = root.xpath('//div[@class="activityNumbers activityNumbersNew"]') for s ...
#!/usr/bin/env python3 # Lunatic files.py # Tad Hardesty, aka SpaceManiac, 2011 # Fills 'Lunatic.files' with all files in source/ # usage: 'python tools/files.py' import os with open('Lunatic.files', 'w', encoding='utf-8') as f: for dirpath, dirnames, fnames in os.walk('source'): for file in fnames: ...
import json import boto3 # Path to the config file. CONFIG_PATH = 'src/main/resources/config.json' def create_session(): """Create a boto3 session by reading the config file at CONFIG_PATH. A boto3.Session(...) creates a session that represents an AWS user that can create/read/update/delete AWS resources. ...
from servicesPartidas import ServicesPartidas import os class Ahorcado(): def __init__(self): self.service = ServicesPartidas() def limpiar_pantalla(self): if os.name == 'nt': os.system("cls") else: os.system("clear") def menu(self): self.limpiar_p...
# Tkinter # Framework provides python users with a simple way # to create GUI elements using the widgets foung in Tk toolkit # Tk widgets can be used to construct buttons, menus, data fields etc # To create a tkinter app: # Importing the module – tkinter # Create the main window (container) # Add any number of widget...
# -*- KSding: utf-8 -*- """ Created on Sun Mar 24 10:33:09 2019 @author: me1vi """ import os import requests import urllib.request import pandas as pd import datetime as dt import re #import arcpy import sys import glob #arcpy.env.overwriteOutput = True def getTraceback(): import traceback ...
n = 8 s = "UDDDUDUU" level,mountain,valley = 0,0,0 for char in s: if char == "U": level+=1 else: level-=1 if level == 0: if char == "U": valley += 1 else: mountain += 1 print(valley)
from bs4 import BeautifulSoup def getSiheyi(html): rangqiu_table = {} sort_table = {} soup = BeautifulSoup(html, "html.parser") zhudui_name = soup.select('a.red-color')[0].text.strip() kedui_name = soup.select('a.blue-color')[0].text.strip() # 得到让球表 rangqiu_aa = soup.select('#sp_rangfen') ...
# -*- coding: utf-8 -*- ''' Created on 2014. 8. 28. 디렉토리 생성 모듈. @author: dulee ''' import util import os ds = """ """ ads = ds.split('\n') for p in ads: if(p == "") : continue p = "." + p if( os.path.isdir(p)): continue print p os.makedirs(p) #os.makedirs(p + "/web") #os.makedirs(p + "/service/impl") ...
from ps6 import * def decrypt_story(): story = get_story_string() message = CiphertextMessage(story) return message.decrypt_message()
#!/usr/bin/env python2 # OpenPOWER Automated Test Project # # Contributors Listed Below - COPYRIGHT 2015,2017 # [+] International Business Machines Corp. # # # 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 th...
# Note: Assumes data.csv is sorted by user_id, date import csv import sys SORTED_IN_FILE = sys.argv[1] last_current_show = None last_event = None start_time = None end_time = None user_id = None variation_id = None revenue_sum = 0 TIME_COL = 0 VARIATION_COL = 1 USER_ID_COL = 2 REVENUE_COL = 4 C...
import numpy as np import pandas as pd import re fdc = {'FDC ALARM': 'FDC alarm'} down = {'DOWN': 'tool down'} pilot = {'PILOT': 'Tool/BKM pilot'} rule = [fdc, down, pilot] if __name__ == '__main__': df = pd.read_csv('CSV.csv') #df['Date'] = df['Date'].astype('datetime64[ns]') df.Date = pd.to_datetime(df....
from django.contrib.auth import authenticate,login from django.contrib.auth.forms import UserCreationForm,AuthenticationForm from django.shortcuts import render,redirect from django.contrib.auth.models import User from .forms import signupform from django.http import HttpResponse from .forms import UserProfileInfoForm,...
for i in (x**2 for x in range(10)): print(i) print("间断") for i in [x**2 for x in range(10)]: print(i) print("间断") r = [x**2 for x in range(10)] print(r) print("间断") a = range(100000000) result = map(lambda x: x**2, a) print(list(result))
filename = "myfile.txt" print ("================ diatas jika penagalamatan Path salah ===============") def bacafile(): filename = "myfile.txt" try: file = open("c:/myfile.txt", "r") print(file.read()) except : print("kesalahan pada path nama file") print('tidak ditemukan', filename) pri...
import uvclight from zope.interface import Interface from uvc.design.canvas import IAboveContent #class HelpPage(uvclight.Viewlet): # uvclight.context(Interface) # uvclight.viewletmanager(IAboveContent) # template = uvclight.get_template('helppage.cpt', __file__)
from enum import Enum class Columns(Enum): lat = 'latitude' lon = 'longitude' geometry = 'geometry' duration = 'duration' distance = 'dist' velocity = 'velocity' accuracy = 'accuracy' time = 'time_min' outlier = 'outlier' valid = 'keep' label = 'valid'
import bird as b def main(): #The parameters for the simulation minimum_distance = 2 number_of_birds = 50 return if __name__ == "__main__": main()
import logging import hashlib import os import azure.functions as func from azure.storage.blob import BlobClient # NEED TO REPLACE EACH TIME A NEW RESOURCE GROUP IS MADE connection_string = "DefaultEndpointsProtocol=https;AccountName=md5test;AccountKey=XdOG8O7c8VXc42xqxxhr8nmMYo3Ir3TJ8A4BmFhhf+Mpg2hnPk+xu1DtmkV1g/QfW...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from napixd.client.client import Client as BaseClient from gevent.coros import Semaphore class Client(BaseClient): """ A client made to be used with :mod:`gevent`. The *simultaneous* argument is the maximum number of c...
#!/usr/bin/env python import rospy import sys from lab2_communication.srv import Set_Robot_Model if __name__ == '__main__': rospy.init_node('lab2_comm_client_node') if len(sys.argv) != 2: rospy.loginfo('usage: %s [model]' % str(sys.argv[0])) sys.exit(1) rospy.wait_for_service('Set_Ro...
#from trains.json get the urls for the stations' details page of every train and scrape the data import scrapy import json urls = json.loads(open(r'C:\Users\mvshashank08\Desktop\Scrapy Work\trains.json').read()) ''' for url in urls: print url['url'],"type:",type(url),"\n" ''' class ClearTripSpider2(scrapy.Spid...
import tensorflow as tf import os import sys #We used utils folder that is including many tools. from utils import label_map_util # Object detection imports. There is a counting model from api import object_counting_api #Detcted .avi file input_video = "test_1.mp4" PATH_TO_CKPT = 'My_model_31_22/frozen_inference_grap...
"""Convert Documenter.jl documentation data to Dash docset.""" import os import shutil from pathlib import Path import logging from .documenter import read_search_index from .docset import DocSet, add_index_item # Maps "category" property in item from Documenter.jl's search_index.js to # value of "type" column in D...
# # 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...
# https://github.com/log0/video_streaming_with_flask_example import numpy as np import cv2 from flask import Flask, render_template, Response import time import cv2 import time import core.utils as utils import tensorflow as tf from PIL import Image from tensorflow_serving.apis import predict_pb2 from tensorflow_serv...
"""Dataminr Pulse Integration for Cortex XSOAR - Unit Tests file.""" import io import json import os import pytest from DataminrPulse import BASE_URL, ENDPOINTS, ERRORS, timezone, datetime, DemistoException, \ OUTPUT_PREFIX_WATCHLISTS, OUTPUT_PREFIX_ALERTS, OUTPUT_PREFIX_CURSOR, remove_empty_elements, \ MAX_...
from torch import nn class MYmodel(nn.Module): def __init__(self):#定义网络层结构,类似卷积,线性层,激活层等 super(MYmodel, self).__init__() self.conv1 = nn.Conv2d(1, 64, 3, padding=1) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(64, 32, 3, padding=1) ...
class Employee: ''' Add nums ''' def __init__(self, *, name, age, *vars): self.name = name pass def add(self, first_num=2, *, second_num=3): return first_num + second_num l = [1, 2] A = Employee(name="kas", age=2, l) print(A.add(3, second_num=6))
#!/usr/local/bin/python # coding: UTF-8 import sqlite3 import json import os import glob conn = sqlite3.connect('dublinbikes.sqlite') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS dublinbikes ( dublinbike_id INTEGER PRIMARY KEY AUTOINCREMENT, status TEXT, contract_name TEXT, name TEXT PrimaryKey, bon...
import sys import logging import time from threading import Thread from os.path import exists from scrypt import decrypt from typing import Union from patterns.singleton import * from eth.eth_connector import EthConnector from node.worker_node import * from job.cognitive_job import * from processor.processor import * ...
# import template import numpy as np import pandas as pd from plotly import express as px from plotly import graph_objects as go #
from __future__ import print_function import json from neo4j.v1 import GraphDatabase, basic_auth, constants import boto3 import datetime import time import os import sblambda import urllib2 def request_backup(sandboxIp, sandboxPort, sandboxHashkey): req = urllib2.Request(url='http://%s:%s/?sandbox=%s' % (sandboxIp...
import time from appium import webdriver desired_cap = { 'deviceName': 'Galaxy Note 10', 'platformName': 'Android', 'platformVersion': '11', 'appPackage': 'com.sec.android.app.popupcalculator', 'appActivity': '.Calculator', 'automationName': 'UiAutomator2' } driver = webdriver.Remote('http://...
#!/usr/bin/env python from __future__ import print_function import glob import sys import traceback import os import re import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from nc_reader import NC_Reader from swim_io import NC_writer import date_fun import swim_io as mygis wrf...
import sys import copy import rospy import moveit_commander import moveit_msgs.msg from nav_msgs.msg import Odometry def callback(msg): print msg.pose.pose rospy.init_node('check_odometry') odom_sub = rospy.Subscriber('/odom', Odometry) rospy.spin()
import hatchet.db.models as db from hatchet.apis.api_v1 import api_manager import hatchet.resources.schemas.schemas as schemas ns_ratings = api_manager.add_resource( name="ratings", resource=db.Rating, schema=schemas.RatingSchema, description="TV Ratings" )
import ply.yacc as yacc from lex_ import tokens import AST def p_programme_statement(p): ''' programme : statement ''' p[0] = AST.ProgramNode(p[1]) def p_programme_recursive(p): ''' programme : statement '<' programme ''' p[0] = AST.ProgramNode([p[1]]+p[3].children) def p_statement(p): ''' state...
from rest_framework.pagination import PageNumberPagination class StandardPagination(PageNumberPagination): page_size = 30 page_query_param = 'page' max_page_size = 100 class ProductPagination(PageNumberPagination): page_size = 8 page_query_param = 'page' max_page_size = 100 class Published...
""" QUALITY CHECK AND EPW FILE ANALYSIS MODULE Run with epw files in the folder Creates 'cityname'.txt file with analysis """ import os import glob import re import csv from random import randint k=glob.glob('*.epw') #Check for Solar Radiation num=0 for i in k: num=num+1 with open(i) as f: ...
""" Created on Mon Apr 9 12:12:22 2018 <流畅的Python2.3> @author: Ethan """ #元组:记录-字段的集合,字段的数量和位置信息 不可变列表-相似a,b = b,a #优雅的实现交换 a = 1 b = 2 a,b = b,a divmod(20,8) t = (20,8) # *将可迭代对象元素拆分 divmod(*t) # *处理剩下元素 a,b,*rest = range(5) a,b,rest # 具名元组:这个实例跟普通对象实例要小,因为Python不会用__dict__存放这些实例属性 from collections import namedtu...
## Describe_multi_day_rasters_morphology.py # Describes 3D "islands" of chronologically ordered binomial classification # rasters by numbers of islands, sizes, and frequency distribution ## Import packages import numpy as np import glob import re import gdal import sys import matplotlib.pyplot as plt from matplotlib i...
oracion = input("Ingrese su frase: ") x = 0 i = 0 while x < len(oracion): if oracion[x] == " ": i = i + 1 x = x + 1 print("Espacios en blanco:" , i)
from datetime import datetime import pytz # --------------------------- # Main function & entry point # --------------------------- def run(): bogota_tz = pytz.timezone("America/Bogota") bogota_time = datetime.now(bogota_tz) mexico_tz = pytz.timezone("America/Mexico_City") mexico_time = datetime.now(...
import os root = os.path.abspath(os.path.dirname(__file__)) isa_schema = os.path.join(root, 'schemas/schema_isa.yaml') platform_schema = os.path.join(root, 'schemas/schema_platform.yaml') priv_versions = ["1.10", "1.11"] user_versions = ["2.2", "2.3"]
#!/usr/bin/env python # This script plots color-color diagrams from a csv file. # This should be run in the directory containing your csv magnitude files. # Modification is required on lines 14, 34-38, 40-44, 53, 69, 77, 91, 99, 113, 122, & 136 depending on the particular dataset. import matplotlib.pyplot as plt impo...
# https://github.com/dannysteenman/aws-toolbox # # License: MIT # # This script finds all unattached EBS volumes in all AWS Regions import boto3 ec2 = boto3.client("ec2") count = 0 for region in ec2.describe_regions()["Regions"]: region_name = region["RegionName"] try: ec2conn = boto3.resource("ec2...
#! /usr/bin/env python # Public Domain (-) 2010-2011 The Ampify Authors. # See the Ampify UNLICENSE file for details. """ ========== Amp Engine ========== Amp Engine powers Ampify -- the decentralised social platform. :: ___ _ /'___) ...
#-*- coding:UTF-8 -*- import MySQLdb def insert(): try: # conn=MySQLdb.connect(host='localhost',user='root',passwd='shadow33',db='test',port=3306) conn=MySQLdb.connect(host='172.27.35.11',user='root',passwd='shadow33',port=3306,db='test',charset='utf8') cur=conn.cursor() values=[] for i in range(100): ...
# 6kyu - Basic subclasses - Adam and Eve """ According to the creation myths of the Abrahamic religions, Adam and Eve were the first Humans to wander the Earth. You have to do God's job. The creation method must return an array of length 2 containing objects (representing Adam and Eve). The first object in the arr...
import libpry import array import packet, packet._packetDescriptors import pcaptester class uOptions(libpry.AutoTree): def test_getset(self): i = packet._packetDescriptors.Options(fOo = 1) assert i["foo"] == 1 i["foo"] = 2 assert i["Foo"] == 2 def test_haskey(self): i...
def isValid(row,pos): if pos>=N or row>=N: return False if pos in sol: return False for i in range(len(sol)): if pos == sol[i]+row-i or pos == sol[i]-(row-i): return False return True def solve(pos,Qc): Qc-=1 sol.append(pos) if Qc==0: return True #Try for i in ...
import simuvex class rand(simuvex.SimProcedure): IS_FUNCTION = True def run(self): #additional code trace_data = ("rand") try: self.state.procedure_data.global_variables["trace"].append(trace_data) except KeyError: self.state.procedure_data.global_variables...
import json import logging import requests from celery.task import Task from django.conf import settings logger = logging.getLogger(__name__) class DeliverHook(Task): max_retries = 5 def run(self, target, payload, instance_id=None, hook_id=None, **kwargs): """ target: the url to receive...
from discord.ext import commands import discord class Give_role(commands.Cog): def __init__(self, client): self.client = client @commands.command(name='g_role', help="Give an existent role to a member.") async def giveRoleToMember(self, ctx, member: discord.Member, memberRole: discord.Role): ...
"""Average power level Revision ID: b851801fb0cb Revises: 2b40fe59a18a Create Date: 2020-07-06 17:20:57.658907 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "b851801fb0cb" down_revision = "2b40fe59a18a" branch_labels = None depends_on = None def upgrade(): ...
import requests payload={'serialNo':'3'} request_server=requests.post("http://smartwaterwatch.mybluemix.net/sensor/activate",data=payload) print(request_server.text) #http://smartwaterwatch.mybluemix.net/sensor/activate
from __future__ import absolute_import, division, print_function from astropy import units as u from astropy.io import fits from astropy.table import Table from astropy.wcs import WCS import matplotlib from matplotlib import pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches impor...
# Generated by Django 3.2.4 on 2021-06-21 02:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('video_and_audio', '0008_alter_activitypersession_session'), ] operations = [ migrations.AlterField( model_name='activitypersessi...
import mymodule a = int(input("Enter side 1 of rectangle ")) b = int(input("Enter side 2 of rectangle ")) result = mymodule.rectangle(a,b) print("Area of Rectangle is -",end=' ') print(result) r = int(input("\nEnter radius of circle & Sphere ")) result = mymodule.circle(r) print("Area of Circle is -",end = ' ') pri...
# Copyright 2019, The TensorFlow Federated Authors. # # 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 o...
from utils import paths paths.fix_path() import ee from datetime import datetime def acqtime(feature): # A handler that returns the correctly formatted date, based on asset. msec = feature['properties']['system:time_start'] return datetime.fromtimestamp(msec/1000).isoformat() def id_stack(coll, begin, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import rospy import struct import math import numpy as np from sensor_msgs.msg import NavSatFix from geometry_msgs.msg import Vector3 #from sensor_msgs.msg import PointCloud2 #import sensor_msgs.point_cloud2 as pc2 class CtrlBoat: def __init__(self): self.M_PI = 3.14159...
import urx import math from math import * import math3d as m3d import numpy as np import time import plotly.graph_objects as go import pandas as pd from decimal import * # #Connection Establishment robo = urx.Robot("172.16.101.225") def JointLocations(thetas): d1 = 0.1625 a2 = -0.425 a3 = -0.3922 ...
import unittest from ..utils.data.data import ChartData # Create your tests here. def extract_csv(file_name): with open(file_name) as f: content = f.readlines() lines = [] for line in content: l = line.split(',') lines.append(tuple(float(x) if '.' in x else int(x) for x in l)) ...
import requests import json url = "http://54.229.242.6" token = "/?token=06530a7ae985ed3592b519f99ae86e2e" def taskFinish(): r = requests.post(url + "/task/finish" + token) print(r.text) def taskStart(taskId): r = requests.post(url + "/task/" + str(taskId) + "/start" + token) print(r....
def menor_nome(nomes): min = nomes[0].strip(" ") tam = len(nomes[0].strip(" ")) i = 1 while i < len(nomes): if len(nomes[i].strip(" ")) < len(min): min = nomes[i].strip(" ") i = i + 1 return min.capitalize()
"definition of constants" DOMAIN = "watchman" DOMAIN_DATA = "watchman_data" DEFAULT_REPORT_FILENAME = "watchman_report.txt" DEFAULT_HEADER = "-== WATCHMAN REPORT ==- " DEFAULT_CHUNK_SIZE = 3500 CONF_IGNORED_FILES = "ignored_files" CONF_HEADER = "report_header" CONF_REPORT_PATH = "report_path" CONF_IGNORED_ITEMS = "ig...
#========================================================================== # Rev0.1 - 15/12/2020 - Chris Hui #========================================================================== # Rev0.2 - 20/12/2020 - Chris Hui #========================================================================== import os from cs50 im...
# Generated by Django 2.1.3 on 2019-09-05 20:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Bio', fields=[ ('id', models.AutoField(auto...
from collections import OrderedDict from timeit import default_timer as timer import os class benchmark(object): def __init__(self, msg, fmt="%0.3g"): self.msg = msg self.fmt = fmt def __enter__(self): self.start = timer() return self def __exit__(self, *args): t...
from selenium import webdriver import time driver = webdriver.Chrome() #获取网址 driver.get("http://www.jd.com") #窗口最大化 driver.maximize_window() #输入搜索商品 driver.find_element_by_xpath("//*[@id = 'key']").send_keys("外星人") #点击搜索按钮 driver.find_element_by_xpath("//*[@class ='button']").click() # driver.swi...
import turtle as t import random def b1(): #함수 b1을 정의합니다. while -a< t.xcor() <a and -a< t.ycor()< a and ((t.xcor() < bx or t.xcor() > bx+ba) or (t.ycor() < by or t.ycor() > by+bb)) and ((t.xcor() < cx or t.xcor() > cx+ca) or (t.ycor() < cy or t.ycor() > cy+cb)): # 장애물 블록1,2 벽을 을 제외한 영역일 경우 아래...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompan...
""" ID: yscript1 LANG: PYTHON3 TASK: gift1 """ import sys def print_err(*args): sys.stderr.write(' '.join(map(str,args)) + '\n') fin = open ('gift1.in', 'r') fout = open ('gift1.out', 'w') np = int(fin.readline().strip()) members = {} for i in range(np): # read np members' name name = fin.readline().strip() ...
""" Module containing abstract classes for web services """ from typing import List from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.abstract.services.database_service.config import DatabaseConnectionConfig from app.abstract.services.database_service.db_connection import Database...
from google.appengine.ext import ndb from util.password_hashing import PasswordHashing from util.token_hashing import TokenHashing class User(ndb.Model): email = ndb.StringProperty(required=True) password = ndb.StringProperty(required=True) name = ndb.StringProperty() phone = ndb.StringProperty() ...
from rest_framework import serializers from .models import Gradient class GradientSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Gradient fields = ('gradient_css', 'gradient_name', 'gradient_author')
import numpy as np import pandas as pd import matplotlib.pyplot as plt #reading dataset dataset_train=pd.read_csv('Google_Stock_Price_Train.csv') dataset_train dataset_train.info() #visualization plt.figure(figsize=(10,5)) plt.plot(dataset_train['Open']) plt.title('Stock Price') plt.xlabel('Latest Pric...
#!/usr/bin/env python # coding: utf-8 from splinter import Browser from bs4 import BeautifulSoup as bs import requests import pandas as pd # Part 2 def scrape(): mars = {} # # NASA Mars News - BeautifulSoup # URL of page to be scraped url = 'https://mars.nasa.gov/news/' # Retrieve page with ...
import requests from pprint import pprint def courses(token='', id='15'): rh = {"Authorization": "Bearer %s" % token} BASE_PARAMS = {'per_page': '50'} CANVAS_DOMAIN = "usu.instructure.com" BASE_DOMAIN = "https://%s" % CANVAS_DOMAIN endpoint = '/api/v1/accounts/%s/courses' URI = BASE_DOMAIN + (en...
import numpy as np import cv2 from gender_prediction import gender_pred import random face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') font = cv2.FONT_HERSHEY_SIMPLEX def image_crop(img): roi_gray=[] img =cv2.imread(img) img1=img.copy() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRA...
from time import time import math # cover es una lista de 0s, 1s y Nones. # Si i es la posicion de un 1, el i-esimo nodo esta en el cover. # Si i es la posicion de un 0, el i-esimo nodo no esta en el cover. # Si i es la posicion de un None, no sabemos si el i-esimo nodo estara en el cover. # # partial_validity_check c...
# encoding:utf-8 from django import forms # from apps.process_admin.models import LegalDiscounts, GeneralDiscounts from apps.payroll.models import DiscountsApplied, IncreasesApplied from django.contrib.auth.models import User class DiscountsAppliedForm(forms.ModelForm): def __init__(self, *args, **kwargs): ...
# Generated by Django 3.0.4 on 2020-03-18 05:33 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(...
from __init__ import * def ident_select(col): new_ident = [] for i in range(col): wtdb_cursor.execute('select newID()') new_ident.append(wtdb_cursor.fetchone()[0]) return new_ident for x in range(len(ident_select(8))): print(ident_select(8)[x])
# -*- coding: Latin-1 -*- """ Verify that lists can add and remove items and stay the correct size. Check that user vars get stored using mock objects. """ from __future__ import unicode_literals import logging import unittest try: # Python 3.3 and higher (LibreOffice) from unittest import mock HAS_MOCK = ...
#!/usr/bin/python3 import json from os import path, remove import sys import time print("Client dialed in") info_raw = sys.stdin.readline() info = json.loads(info_raw) print("Recieved info: {}".format(info), file=sys.stderr) client_file = path.join("/var/run/rmtadm/", info["hostname"] + ".client") with open(client...
import unittest from chargify import Chargify, ChargifyError class ChargifyHttpClientStub(object): def make_request(self, url, method, params, data, api_key): return url, method, params, data class ChargifyTestCase(unittest.TestCase): def setUp(self): subdomain = 'subdomain'...
class MiojoSolver: def __init__(self, ampulheta1, ampulheta2): self.ampulheta1 = ampulheta1 self.ampulheta2 = ampulheta2 def resolver_para(self, tempo_miojo): maior = max(self.ampulheta1, self.ampulheta2) menor = min(self.ampulheta1, self.ampulheta2) if (maior - menor) ...
import os from datetime import datetime from datetime import timedelta from TZmyApp import models #import datetime import matplotlib.pyplot as plt #%matplotlib inline import pandas as pd import numpy as np def LoadDataFrame(filename): df = pd.DataFrame() if os.path.isfile(filename): df...
def solve(a1, a2, k, n): a1.sort() a2.sort(reverse=True) for i in range(n): if a1[i]+a2[i] < k: return "NO" return "YES" t = int(raw_input()) for i in range(t): n, k = map(int, raw_input().split(' ')) a1 = map(int, raw_input().split(' ')) a2 = map(int, raw_input().split(...