text stringlengths 38 1.54M |
|---|
import requests
from selenium import webdriver
from bs4 import BeautifulSoup
import json
import os
url = 'https://turbo.az'
r = requests.get(url)
# JSON File to hold the data
cars_json = []
if r.status_code == 200:
html = BeautifulSoup(r.text, 'lxml')
divs = html.find_all('div', 'products-i')
for div i... |
#!/usr/bin/env python3
import argparse
import re
import subprocess
import datetime
def get_author_date(commit):
p = subprocess.run(f"git --git-dir=/media/adam/b52e403a-28d8-494d-ae31-ecc7f80de2d7/opensim-core/.git show --format='%ai' --quiet {commit}", shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL... |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(ListofCards)
admin.site.register(Boards)
|
import math
def f1(x, y, z):
math_op_top = math.tan(z)-math.cos(y)
math_op_bot = y - math.log(y)
first_sqrt = math.sqrt(math_op_top / math_op_bot)
math_op_top = pow(z, 7) - math.tan(y) - 46
math_op_bot = math.cos(y) + pow(z, 4)
second_op = math_op_top / math_op_bot
second_sqrt = math.sqrt(... |
from django.shortcuts import render
from django.shortcuts import HttpResponseRedirect
from .models import ToDoList, Item
from .forms import CreateNewList
# Create your views here.
def view(request):
return render(request, "main/view.html", {})
# inside views.py
def index(request, id):
ls = ToDoList.objects.ge... |
# PyAlgoTrade
#
# Copyright 2011-2018 Gabriel Martin Becedillas Ruiz
#
# 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 ap... |
#Brandon Jones
#1/22/19
#Jones_grader
#This program will calculate the grade average
import Jones_Grade_Functions
# main function that will do all of the functions calls
def main():
# function call and return # of grades to enter
num = Jones_Grade_Functions.get_input()
# function call and return average
... |
"""
1.
"""
def return_largest(a, b, c):
""" Return the largest of 3 numbers. """
if a > b and a > c:
largest = a
elif b > a and b > c:
largest = b
else:
largest = c
return largest
"""
2.
"""
def return_count(n, last):
""" Return the number of occurences of n between 0 an... |
'''
Defines the abstract base class for bindings to the graphics calls
from PyFerret. Specific engine bindings should create a subclass of
AbstractPyFerretBindings and re-implement the methods to call the
methods or functions for that engine. This class definition should
then be registered with PyFerret (pyferret.gra... |
# -*- encoding:utf-8 -*-
import os
import time
import numpy as np
import tensorflow as tf
from keras.models import load_model
from keras.utils import to_categorical
def validTest(validFile, modelPath, num_classes):
start_time = time.time()
validVisit = np.load('data/npy/validVisit.npy')
validImage = np.loa... |
#!/usr/bin/env python3
import os, sys
import re
#--------------------------------------------------------------------------------
def read_config(filename):
""" Reads the config file and returns a dictionary where keys are
groups and values are lists of items within the group.
The items are tuples of (ite... |
# Queue Reconstruction by Height
# after sorting people with height, try to add people with height
# from high to low. since the taller people has already been added,
# the index to insert will be the same as num of people ahead
class Solution(object):
def reconstructQueue(self, people):
"""
:type p... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""LangVisNet backend Python server."""
# Standard lib imports
import os
import sys
import logging
import argparse
import motor
import time
import os.path as osp
# Tornado imports
import tornado.web
import tornado.ioloop
# Local imports
# from cortech.db import RiakDB
... |
print("팩토리얼 값 계산 프로그램")
n = int(input("정수 입력: "))
i = 1
fact = 1
while i<= n :
fact *= i
i += 1
print("계산결과 %d! = %d" % (n,fact))
input()
|
# Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
def reverseNodesInKGroups(l, k):
if k == 1 or k == 0:
return l
tmp1 = l
for i in range(0,k-1):
tmp1= tmp1.next
start = tmp1
... |
from django.conf.urls import url
from . import views
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import *
urlpatterns = [
url(r'^login_page$', views.login_page),
url(r'^regprocess$', views.user_proce... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class DangdangItem(scrapy.Item):
# define the fields for your item here like:
#定义需要爬取的变量名
name=scrapy.Field()#定义保存书名的变量
author=scrapy.F... |
from pathlib import Path
import os
from ctapipe.io import read_table
from ctapipe.containers import EventType
import numpy as np
test_data = Path(os.getenv("MAGIC_TEST_DATA", "test_data")).absolute()
test_cal_path = (
test_data / "real/calibrated/20210314_M1_05095172.001_Y_CrabNebula-W0.40+035.root"
)
config = Pa... |
#!/usr/bin/env python
import rospy
from nav_msgs.msg import OccupancyGrid
from nav_msgs.msg import MapMetaData
import roslaunch
import numpy as np
def create_map():
test_map = OccupancyGrid()
test_map.info.resolution = 1.0
test_map.info.width = 10
test_map.info.height = 10
test_map.info.origin.pos... |
import imaplib
import email
import email.parser
import imaplib_connect
with imaplib_connect.open_connection() as c:
c.select('INBOX', readonly=True)
typ, msg_data = c.fetch('1', '(RFC822)')
for response_part in msg_data:
if isinstance(response_part, tuple):
email_parser = email.parse... |
l=[]
for i in range (1000,3001):
n=i
c=0
while(n!=0):
r=n%10
n=n//10
if r%2==0:
c=c+1
if c==4:
l.append(i)
for i in range (0,len(l)):
l[i]=str(l[i])
print(','.join(l))
|
from nose.tools import *
import re
def assert_response(resp,contains=None,matches=None,headers=None,status="200"):
assert status in resp.status,"Expected response %r not in %r" % (status,resp.status)
if status == "200":
assert resp.data, "Response data is empty."
if contains:
assert contains in resp.data , "... |
# Ref: https://leetcode.com/problems/invalid-transactions/solutions/1230813/python-o-n-solution-o-n-space/
# Time: O(N)
# Space: O(N)
class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
res = []
trans_map = {}
for i in transactions:
split = i.spl... |
from twisted.internet import reactor, protocol
from random import seed, randint
from struct import pack, unpack
from optparse import OptionParser
import re
import xml.etree.ElementTree as xml
settings = {
'port': None,
'pw': None,
'id': None,
'q': None,
'g': None,
'M': None,
'N': None,
... |
import unittest
from sort_array import sort_fractions
class TestSortFractions(unittest.TestCase):
def test_with_two_fractions(self):
fractions = [(2, 3), (1, 2)]
excpected = [(1, 2), (2, 3)]
fractions = sort_fractions(fractions)
self.assertEqual(fractions, excpected)
def test_with_descending_argument_gi... |
import pandas as pd
class Pollutant:
def __init__(self, path, name):
self.df = pd.read_csv(path, sep=';')
self.df['dtvalue'] = pd.to_datetime(self.df['dtvalue'])
self.name = name
def getName(self):
'''
:return: nazov znecistujucej latky
'''
return self.n... |
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView
from django.views.generic.edit import FormView
from django_tables2 import RequestConfig
from django.urls import reverse_lazy
from datetime import datetime
from django.contrib import messages
from django.template ... |
import collections
import operator
def product(sequence, initial=1):
"""like the built-in sum, but for multiplication."""
if not isinstance(sequence, collections.Iterable):
raise TypeError("'{}' object is not iterable".format(type(sequence).__name__))
return reduce(operator.mul, sequence, initial... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 9/7/2020
@author: Alun Brain (Dr. Brain Stats)
"""
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import scrolledtext
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import seaborn as sns
import stat... |
""""
class Point():
def __init__(self, inputX, inputY):
self.x = inputX
self.y = inputY
p = Point(2, 5)
print(p.x)
print(p.y)
"""
class Flight():
def __init__(self, capacity):
self.capasicy = capacity
self.passengers = []
def add_passenges(self, name):
if not sel... |
#!/bin/python3
# Filename: lab06_1-random_password.py
# Course: Full Stack Developer Evening Bootcamps
# Author: Peter Chow, Student
# Assignment: Lab 6: Password Generator - Version 1
# Date: 10/14/2020
# Version 1.0
'''
Let's generate a password of length n using a while loop and random.choice, this will be a string... |
# -*-coding: utf-8 -*-
import torch
import torch.nn as nn
import torchvision.transforms as transform
import os
from matplotlib import pyplot as plt
from tqdm import tqdm
#from tensorboardX import SummaryWriter
from torch.utils.data.dataset import Dataset
import numpy as np
import glob
import pandas as pd
# Hyper Param... |
import poplib, json, queue, time, mail_sender
from config import data, kwd, save_json
from re import sub, search, compile, findall
from email.parser import Parser
from email.utils import parseaddr
from email.header import decode_header
from slog import logger
############################## 功能介绍 ######################... |
from replit import clear
import time
import random
from replit import audio
from colorama import Fore, Back, Style
from bird_generator import *
def end_of_game():
'''print statements to end the game'''
#closing statment
print(f"Well I think those were enough birb duties for one day.\nAs you can see, it's... |
#runfile('C:/Users/chibi/.spyder-py3/backprop/test.py', wdir='C:/Users/chibi/.spyder-py3/backprop')
import cv2
import numpy as np
import torch
def max(a,b):
if a>b:
return a
else:
return b
def min(a,b):
if a<b:
return a
else:
return b
cap = cv2.VideoCapture(0)... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Video Receiver
# Generated: Thu Jun 15 15:30:58 2017
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platfor... |
import random
class GA(object):
def __init__(self, chromosome):
self.chromosome = chromosome
def execute(self):
pop = self.chromosome.init()
while True:
# char는 아스키 코드 캐릭터를 의미하며, 이는 다음과 같이 변환된다.
# 49='1', 50='2', 51='3', 52='4'
fitPop = [(self.chromosome.fitness(char), char) for char in p... |
#prints a 2D array numbered num through n*n with n rows and n cols
def main():
print '2x3 matrix =',array(2,3)
print '1x2 matrix =',array(1,2)
print '3x5 matrix =',array(3,5)
def array(rows,cols):
board = []
num = 1
for i in range(rows):
board.append([])
for j in range(cols):
... |
#If statements
friend="Abhi"
user_name=input("Enter your name: ")
if user_name.lower() == friend.lower():
print("Hello, friend.")
else:
print("Hello, stranger!")
friends = ['rajan','raja','sam']
family = ['ashu','ash','sri']
user_name=input("Enter your name: ")
if user_name.lower() in friends:
print("He... |
def readFile(fileName):
lines = []
with open(fileName, 'r') as file:
for line in file:
lines.append(line.strip())
return lines
def trieMatching(text, trie):
matchingOccurs = []
for root in range(0, len(trie)):
for pattern in text:
if trie[root] =... |
""" The mitochondria is the powerhouse of the cell...
Defines tables along with the ORM and the SQL core of SQLAlchemy """
from sqlalchemy import create_engine, String, BigInteger, Integer, Column, ForeignKey, Table, MetaData
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import ... |
import pandas as pd
buro = pd.read_pickle('buro')
buro_balance = pd.read_pickle('buro_balance')
#----------------Buro_balance pre-processing
# Bureau and bureau_balance numeric features
buro_grouped_size = buro_balance.groupby('SK_ID_BUREAU')['MONTHS_BALANCE'].size()
buro_grouped_max = buro_balance.groupby('SK_ID_BU... |
#-*- coding: utf-8 -*-
__author__ = 'muti'
__copyright__ = 'npcomms'
from .zplayer import ZplayerXBlock |
import scrapy
from scrapy import Request
from ..items import MovieDetailItem
class MovieDetailSpider(scrapy.Spider):
name = 'moviedetail'
with open(r'start_urls.txt', 'r') as f_handle:
start_urls = [line.strip('\n') for line in f_handle.readlines()]
def start_requests(self):
for url ... |
import time
import json
import numpy
#import pandas as pd
from oct2py import octave as oct
class OctaveAPIs:
def call_detection_api(self,reading,train_adapt,sensor,failure_status):
reading = numpy.matrix(reading)
detect = oct.feval("detection", reading, sensor, train_adapt,failure_status)
... |
#!/usr/bin/env python3
from pdspy.constants.physics import c, m_p, G
from pdspy.constants.physics import k as k_b
from pdspy.constants.astronomy import M_sun, AU
from matplotlib.backends.backend_pdf import PdfPages
import pdspy.modeling.mpi_pool
import pdspy.interferometry as uv
import pdspy.spectroscopy as ... |
from dataclasses import dataclass
##
# an event is a measuremt in time
##
@dataclass(frozen=True)
class Event:
user_id: int
timestamp: int # make use of epoch
location: 'Coords'
@dataclass(frozen=True)
class Coords:
lon: int # as in X
lat: int # as in Y
projection: int = 4326 # as in WGS... |
# -*- coding: utf-8 -*-
# @Author: Macsnow
# @Date: 2017-05-15 14:00:33
# @Last Modified by: Macsnow
# @Last Modified time: 2017-05-19 17:21:28
import socket
from src.workers.base_worker import Worker
class Listener(Worker):
BUFFER = 1024
CHANNELS = 2
def __init__(self, frames, port=1200... |
import mss
from PIL import Image
import numpy as np
import scipy.cluster
import time
class ScreenReactive:
"""
A class that manages all actions related to Screen Reactive Script
"""
def __init__(self, period=0.1):
"""
An initializer method for class Screen Reactive.
@params {fl... |
#!/usr/bin/python
import os
import sys
import time
import subprocess
if len(sys.argv) > 1:
time_window = sys.argv[1]
else:
time_window = '3'
# get the interface
output = subprocess.check_output(["ip", "link", "show"])
output = output.strip('\n').split('\n')
output = [line.split()[1].strip(':') for line in ou... |
import numpy as np
import pandas as pd
import argparse
from Bloom_filter import BloomFilter
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', action="store", dest="data_path", type=str, required=True,
help="path of the dataset")
parser.add_argument('--threshold_min', action="st... |
from tkinter import *
from tkinter import messagebox
from items_db import Login
from customer_page import user_registration
class user_login:
def __init__(self, window):
self.window = window
self.window.title("Login")
self.mainframe = LabelFrame(self.window, width=1500, height=800)
... |
import re
from serif.theory.serif_theory import SerifTheory
from serif.theory.syn_node import SynNode
from serif.xmlio import ET
class SerifParseTheory(SerifTheory):
def _init_from_etree(self, etree, owner):
SerifTheory._init_from_etree(self, etree, owner)
if self.root is None:
if sel... |
from django.shortcuts import render
def forumavisos(request):
return render(request, 'blog2/forumavisos.html', {})
|
# Generated by Django 3.2.5 on 2021-07-24 15:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0003_alter_post_options'),
]
operations = [
migrations.AlterField(
model_name='post',
name='reading_time',
... |
with open("input.dat", 'r') as f:
questions = set()
counter = 0
for l in f:
line = l.strip()
if line == "":
counter += len(questions)
questions.clear()
else:
for char in line:
questions.add(char)
counter += len(questions)
... |
from math import gcd
nums = []
with open('p099_base_exp.txt') as f:
for row in f.readlines():
base, exponent = row.strip().split(',')
nums.append([int(base), int(exponent)])
def compare_nums(num_0, num_1):
base_0, exp_0 = num_0
base_1, exp_1 = num_1
if base_0 > base_1 and exp_0 > exp_1... |
from collections import defaultdict
class Test:
def __init__(self, num_points = 0):
self.xeye = []
self.xeyo = []
self.xoye = []
self.xoyo = []
self.num_points = num_points
self.winners = 0
def addPoint(self, pair):
x = pair[0]
y = pair[1]
... |
from numpy import*
s = input("digite uma string:").upper()
s = s.replace('','')
inv = ""
i =-1
b = 1
c = 0
while i>=-len(s):
inv = inv + s[i]
if(s[c])!= (s[i]):
b = 0
c = c+1
i = i-1
print(s)
print(b)
|
import os
import sys
import random
import logging
import telegram
import time
import json
import sqlite3
import pygal
import emoji
from time import sleep
from telegram import Bot, User, ReplyKeyboardRemove
from telegram.ext import Updater, CommandHandler, Dispatcher,\
MessageHandler, Filters
sys.path.append(os.pat... |
n=int(input())
l=list(map(int,input().split()))
r=[1]
for i in range(1,n,1):
r.insert(i-l[i], i+1)
for i in r:
print(i, end=' ') |
'''
静态方法与类方法 访问 实例变量 会报错
'''
class Studen():
sum = 10
# 实例方法
def __init__(self,name,age):
self.name = name
self.age = age
print(self.name) # 实例变量
# Studen.sum+=1 # 实例方法操作类变量
print(self.age)
# 类方法
@classmethod
def plus_sum(cls):
cls.sum+=1
print(cls.sum)
# 静态方法
@st... |
import numpy as np
from qiskit import QuantumCircuit
from input.data_handler import DataHandler
class NEQRSVDataHandler(DataHandler):
"""
A statevector data handler. This will represent the input data as a state vector and then ask Qiskit
to find a circuit which initializes this state.
"""
def _... |
# @noindex
try:
from reaper_python import *
except ImportError:
pass
try:
import sys
sys.argv=["Main"]
if sys.hexversion >= 0x03000000:
import tkinter
from tkinter import ttk, Tk, StringVar, TclError, Button, Spinbox, Label
from tkinter import *
from tkinter.ttk imp... |
# -*- coding: utf-8 -*-
from hello_world_axpo_helio.api.items import search
def test_search_items():
"""Search items
"""
assert len(search()) == 2
|
n = input('用空格分隔多个数据:')
list = n.split()
for i in range (len(list) // 2):
list[i],list[len(list) - 1 - i] = list[len(list) - 1 - i],list[i]
print(list)
|
import random
from datetime import datetime
from personalSpotifyInfo import album_art_playlist_id, client_id, client_secret, redirect_url, user
import spotipy
import spotipy.util as util
playlist_id = album_art_playlist_id
filename = "judgingTracksByTheirAlbumCover.html"
stylesheet = "albumCoverStylesheet.css"
c... |
# -*- coding: utf-8 -*-
"""Profile - Non Companies House company enter your email verification code"""
from requests import Response, Session
from directory_tests_shared import PageType, Service, URLs
from tests.functional.utils.context_utils import Actor
from tests.functional.utils.request import Method, check_respo... |
'''
Created on Jun 29, 2017
@author: demon
'''
import numpy as np
def load_qa(path):
import ast
with open(path) as json_data:
json_txt = json_data.readlines()
json_obj = [ast.literal_eval(x) for x in json_txt]
#print(json_obj[3]['question'])
x = np.array(json_obj[::]['question'... |
from django.conf.urls import url
from movies.views import (
CommentDetail, CommentsList, MovieDetail, MoviesList, TopList
)
app_name = 'movies'
urlpatterns = [
url(r'^movies/$', MoviesList.as_view(), name='movies-list'),
url(r'^movies/(?P<pk>\d+)/$', MovieDetail.as_view(), name='movie-detail'),
url(r... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from linearRegression.linearRegression import LinearRegression
import pandas as pd
x = np.array([i*np.pi/180 for i in range(60,300,4)])
np.random.seed(10) #Setting seed for reproducibility
y = 1*x + 2 + np.random.normal(0,1,len(x))
LR = LinearReg... |
from django.contrib import admin
from .models import Reference
@admin.register(Reference)
class ReferenceAdmin(admin.ModelAdmin):
list_display = ['title', 'description', 'link', 'author', 'publish'] |
import re
import os
def build_file_structure():
dirs = [
'data/',
'data/dataset',
'data/dataset/train',
'data/dataset/test',
'data/dataset/cache/train',
'data/dataset/cache/test',
]
for dir in dirs:
os.makedirs(dir, exist_ok=True)
build_file_struct... |
import torch
import random
from random import shuffle
import config
import pickle
import numpy as np
def saveToFile(object, filename):
with open(filename, "wb") as file:
pickle.dump(object, file)
def loadFromFile(filename):
with open(filename, "rb") as file:
return pickle.load(file)
class Da... |
# self:类实例自身的引用
# python中交换变量
import os
from pprint import pprint
from random import randrange
import sys
a,b=1,2
a,b=b,a
print(a,b)
# __buildins__模块,在程序开始或在交互解释器中给出提示之前,由解释器自动导入的
# python对象,python使用对象模型来存储数据,构造任何类型的值都是一个对象
# 类型包括:
# 整型、浮点、字符串、元祖、列表、字典
# 对象、None、集合、函数、模块、累
print(1//2)
print([randrange(1,10) fo... |
from typing import Dict
from src.forexgenerator.forexgenerator import FOREXGenerator
def create_default_forex_generators() -> Dict[str, FOREXGenerator]:
"""Default currency pairs and their starting prices."""
starting_values = {
"AUDJPY": 81.44,
"AUDUSD": 0.77,
"CADJPY": 87.36,
... |
import sys
from subprocess import *
from time import gmtime, strftime
from PySide.QtCore import *
from PySide.QtGui import *
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("Simple tools")
# a... |
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
arr = [0] * (length + 1)
for s, e, i in updates:
arr[s] += i
arr[e+1] -= i
for i in range(1, length):
arr[i] += arr[i-1]
return arr[:-1]
|
from sqlalchemy import create_engine
import pandas as pd
from databasing.db_conn_strings import conn_string
conn = create_engine(conn_string)
#: Transfer over any lift_data not currently in the backup
query = '''
SELECT
*
FROM lift_data
'''
tmp = pd.read_sql(query, conn)
tmp.to_sql('lift_data_backup', conn, i... |
print('\n########## Simple dictionary ############')
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
print('\n########## Accessing Values ############')
new_points = alien_0['points']
print(f'You just earned {new_points} points!')
print('\n########## adding new kye value pa... |
# #########################################################################
# Copyright (c) 2018, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2018. UChicago Argonne, LLC. This software was produced #
# under U.S. Gov... |
from django import forms
from .models import Contractor, Rubble, RubbleRoot, RubbleQuality, Destination, Place, Consignee, Employer, Consignor
class TaskForm(forms.Form):
date = forms.DateTimeField(widget=forms.DateTimeInput, label="Дата формирования")
contractor = forms.ModelChoiceField(widget=forms.Select, ... |
s = "oneTwoThree"
# Since first word is always counted, started counting from 1
wordCount = 1
for i in range(len(s)):
if s[i] == s[i].upper():
wordCount += 1
print wordCount |
# -*- coding: utf-8 -*-
from __future__ import division
import re
from nltk.corpus import stopwords
from nltk.stem.snowball import RussianStemmer
from collections import Counter
from pytils import translit
__author__ = 'anna'
def cleanup_words(text):
"""
Get words from text (exclude all punctuation and other... |
"""
APAS Problem 7: Reverse Integer
Description: "Given a 32-bit signed integer reverse digits of an integer."
Examples: "Input: 123, Output: 321"; "Input: -123, Output: -321", "Input: 120, Output: 21"
"""
def revInt(int):
strInt = str(int)
arrInt = []
for i in reversed(strInt):
if i != "0" and i !=... |
from app import app
import json
import jsend
def test_decode():
cli = app.test_client()
src = 'aGVsbG8gd29ybGQ='
r = cli.post(
'/api/decode',
headers={'X-Base64-Access-Key': 'helloworld'},
content_type='application/json',
data=json.dumps({'src': src})
)
assert 200 =... |
# -*- coding: utf-8 -*-
###################################################################################
# Copyright (C) 2019 SuXueFeng
# 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
#
# ... |
#coding=utf8
import openpyxl
from openpyxl import workbook
import sys
from collections.abc import Iterable
import os
base_path = os.getcwd()
sys.path.append(base_path)
class HandExcel:
def load_excel(self,filepath = None):
'''
加载excel
'''
if filepath == None:
filepath =... |
import json
import os
from data.CocoData import COCODataset
from model.yolo.YoloNet import YoLoService
from model.frcnn.Models import FRCnnService
def doEval(modelName,model_path):
if modelName=='yolo':
service=YoLoService(model_path=model_path)
if modelName=='frcnn':
service=FRCnnService(mod... |
import tensorflow as tf
import numpy as np
__all__ = [
'read_dataset',
'process_dataset',
]
def read_dataset(filename, num_channels=39, labels_shape=[], labels_dtype=tf.string):
"""Read data from tfrecord file."""
def parse_fn(example_proto):
"""Parse function for reading single sequence exa... |
from django.urls import path
from .views import *
urlpatterns = [
path('login', GetToken.as_view()),
path('renew', RenewToken.as_view()),
path('logout', Logout.as_view()),
path('logouteverywhere', LogoutEverywhere.as_view()),
path('changepassword',ChangePassword.as_view())
]
|
# O(n²)
# n = len(head)
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
head = ListNode(float("-inf"), head)
prev = head
... |
#!/usr/bin/python
"""list of libraries and functions imported"""
from numpy import*
#from os import listdir
import numpy as np
#from sklearn.multiclass import OneVsRestClassifier
from sklearn.externals import joblib
#from sklearn.metrics import confusion_matrix
from sklearn import svm
from pca import principal_componen... |
"""
Rhino Python Script Tutorial
Exercise 07
Let's reorganize the previous code to store the coordinates of our points in a list.
This list is called an array.
The following lesson explains why this is useful.
"""
import rhinoscriptsyntax as rs
import math
def Main():
n = 50
radius_0 = 3
poin... |
#!/usr/bin/python
import sys
import os
import subprocess
#These are the paths to check
KnownComponents = ['WS', 'SC']
PathsToCheck = {
'SC' : '/disk1/storage/eucalyptus/instances/volumes',
'WS' : '/disk1/storage/eucalyptus/instances/bukkits'}
class PermsChecker(object):
def __init__(self):
self... |
# Initialize outside modules to be used
import pygame, sys
sys.path.insert(0, '..')
from entity.entity import Entity
pygame.init()
# Colors for placeholder sprites
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Screen size
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HE... |
import numpy as np
import matplotlib.pyplot as plt
import skimage as ski
from skimage.util import view_as_windows
from skimage.color import rgb2gray
from numpy import linalg as LA
import numba
import pickle
import collections
import glob
rng = np.random.RandomState(seed=42)
def compute_psnr(img1, img2):
"""
:... |
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
#import pandas as pd
BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0'
JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'
RESIZED_INPUT_TENSOR_NAME = 'ResizeBilinear:0'
class ... |
# -*- coding: utf-8 -*-
import copy
from typing import List
import pyperclip
from wox import Wox
from .constants import *
from .templates import *
class Main(Wox):
messages_queue = []
def sendNormalMess(self, title: str, subtitle: str):
message = copy.deepcopy(RESULT_TEMPLATE)
message['T... |
#init
from prof import *
#Regras
# se a entrada do usuario em empreendedor exemplo for 2 e a da vocaçao dele for 2 tambem , entao e considerado "bom"
# se a entrada do usuario em empreendedor exemplo for 1 e a da vocacao dele for 3 , entao e considerado Tem , mas nao e bom
# se a entrada do usuario em emp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.