text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
# -----------------------------------------------------------------------
# rebook.py
# Author: Sophie Li, Connie Xu, Jayson Wu
# -----------------------------------------------------------------------
import os
from sys import stderr
from flask import Flask, request, make_response, redirect, url_... |
import logging
def get_default_format():
return '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
# old formatter: return '%(asctime)s %(levelname)-8s %(message)s'
def get_console_logger(name):
logger = logging.getLogger(name)
stream_handler = logging.StreamHandler()
stream_handler.setLevel... |
'''
MappingSettings.py: Objected Orientated Google Maps for Python
ReWritten by Chris Pham
Copyright OSURC, orginal code from GooMPy by Alec Singer and Simon D. Levy
This code is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free S... |
def chknum(n):
if n>0:
print("Positive Number");
elif n<0:
print("negative Number");
else:
print("zero");
if __name__=='__main__':
n=int(input());
chknum(n); |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2013 Gergely Nagy <algernon@madhouse-project.org>
# Copyright (c) 2013 James King <james@agentultra.com>
# Copyright (c) 2013 Julien Danjou <julien@danjou.info>
# Copyright (c) 2013 Konrad Hinsen <kon... |
# -*- coding: utf-8 -*-
# Copyright 2022 Network to Code
#
# 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 ... |
import numpy as np
import cv2 as cv
import tensorflow as tf
def guided_filter_cv(I, p, r, eps):
h, w = I.shape
r = (2*r, 2*r)
mean_I = cv.boxFilter(I, -1, r)
mean_p = cv.boxFilter(p, -1, r)
mean_Ip = cv.boxFilter(I*p, -1, r)
cov_Ip = mean_Ip - mean_I * mean_p
# this is the covariance of(I... |
#|default_exp p02_opencv_mediapipe_segment
# sudo pacman -S python-opencv rocm-opencl-runtime python-mss
import time
import numpy as np
import cv2 as cv
import mss
import mediapipe as mp
import mediapipe.tasks
import mediapipe.tasks.python
start_time=time.time()
debug=True
_code_git_version="fe5991e8e673fa16f0e56b68c53... |
#!/usr/bin/python
import smbus
import math
import time
import pyfirmata
# Register
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
AngleDegX = 0
AngleDegY = 0
AngleDegZ = 0
# First serial harcware body control serial connection
try:
hardware = pyfirmata.ArduinoMega("/dev/ttyACM0")
print("Catbot hardware serial co... |
def has_palindrome_permutation(s):
s = list(s)
hashset = set()
for c in s:
if c in hashset:
hashset.remove(c)
else:
hashset.add(c)
return len(hashset) <= 1
|
def pick_peaks(arr):
prev_dex = prev_val = None
result = {'pos': [], 'peaks': []}
upwards = False
for i, a in enumerate(arr):
if prev_val == a:
continue
elif prev_val is None or prev_val < a:
upwards = True
else:
if prev_dex and upwards:
... |
import torch
from torch import nn
from torch.nn import functional as F
from .utils.utils import (
drop_connect,
get_same_padding_conv2d,
Swish,
MemoryEfficientSwish,
calculate_output_image_size
)
class MBConvBlock(nn.Module):
"""Mobile Inverted Residual Bottleneck Block.
Args:
bloc... |
"""print ตั๋ว"""
print('[CONSOLE] Program starting...')
import spreadsheet as sh #spreadsheet.py
from pathlib import Path
from tkinter import *
# Explicit imports to satisfy Flake8
from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage, ttk
from PIL import Image, ImageTk, ImageFont, ImageDraw
OUTPUT_PATH = ... |
import argparse
from data_manager import DataManager
from da_manager import DaData
from plotter import Plotter
from plotter import ATTR
from intersect import Intersect
from modes import BUFFER_LIST
from modes import BUFFER_METHOD
# from my_utils import base_path_from_date
class Runner(object):
"""
This pro... |
"""
Michael Heskett
10X single cell rna-seq pipeline
This script uses pandas data frames and numpy ndarrays somewhat loosely.
"""
import os
import re
import csv
import numpy as np
import pandas as pd
import scipy.io
import matplotlib.pyplot as plt
from scipy import linalg
from sklearn.cluster import KMeans
from sklear... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-08-10 09:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('host', '0005_hostdetails_uuid'),
]
operations = [
migrations.RenameField(
... |
i = input("Enter Frst name")
j = input("Enter last name")
print(i+""+j)
|
def mineLocation(field):
for arr_idx, arr in enumerate(field):
if 1 in arr:
return [arr_idx, arr.index(1)]
'''
You've just discovered a square (NxN) field and you notice a warning sign.
The sign states that there's a single bomb in the 2D grid-like field in front of you.
Write a function mine... |
# -*- coding: utf-8 -*-
"""
界面选项卡模型
"""
__author__ = 'JohnnyB0Y'
class ItemModel:
def __init__(self):
self.property_atomic_text = ['nonatomic', 'atomic']
self.property_assign_text = ['assign', 'strong', 'weak', 'copy']
self.property_readonly_text = ['readonly', 'readwrite']
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 27 14:33:10 2020
@author: user
"""
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
import time
x,y,z = mc.player.getTilePos()
mc.player.setTilePos(x,y,z)
time.sleep(5)
y = y + 100
mc.player.setTilePos(x,y,z)
time.sleep(5)
y = y + 100... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 10 15:14:02 2018
@author: Kazantsev Andrey
03.02.2019
Changes"
Rewriting file for work with best params from file
"""
import os
import numpy as np
import matplotlib.pyplot as plt
name_pulsar = input('Enter name pulsar: ')
par_data = np.g... |
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import inv, cholesky
import math as mt
def sigma_points(x_esti, Sigma, kappa):
n = len(x_esti)
Xi = np.zeros((n, 2*n+1))
W = np.zeros(2*n+1)
kappa=3-n
Xi[:, 0] = x_esti
W[0] = kappa / (n + kappa)
U = cholesky((n + kap... |
import numpy as np
import math
from ntpath import basename
from os.path import getsize
import os
import pprint
def CalcMSE(OrigY,OrigU,OrigV,ReconY,ReconU,ReconV):
OrigYRow, OrigYCol, _ = OrigY.shape
OrigURow, OrigUCol, _ = OrigU.shape
OrigVRow, OrigVCol, _ = OrigV.shape
ReconYRow, ReconYCol, _ = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, sys, subprocess, functools
from PyQt5 import QtWidgets, QtGui, QtCore
from playerVLC import *
import mainWindow # import of mainWindow.py made with pyuic5
from musicBase import *
from musicDirectory import *
from database import *
from dialogMusicDirectoriesL... |
"""
Robotritons troubleshooting version for gps navigation.
Purpose: Use reliable GPS data to navigate the vehicle
Requirements: A vehicle with at least one speed controller and one servo, and one Ublox NEO-M8N Standard Precision GNSS Module. The python modules sys, time, GPSConfigBackEnd, and VehiclePWMModule
Use: I... |
from series_types import SeriesType
from choices import Choice
from questions import Question
from user_question_answer import UserQuestionAnswer
from question_test_series import QuestionTestSeries
from subject import Subject
from topic import Topic
from series_types import SeriesType
|
import requests
import lxml.html
data = []
r = requests.get("https://turb0translation.blogspot.com/p/blog-page.html")
root = lxml.html.fromstring(r.content)
#links = root.xpath('//li[@title="Bookmark Chapter"]/a')
links = root.xpath('//*[@id="post-body-6306637228371808967"]/div[2]/a')
for link in links:
print(f"{l... |
import visual_recognition
import json
import random
local_image = 'test/kevin.jpg'
with open('util/advices.json') as json_file:
advices = json.load(json_file)
def predict_image(image):
classes_result = visual_recognition.predict_mood(image)
result = json.dumps(classes_result, indent=2)
return result... |
__author__ = 'AdminZJ'
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'equal'
else:
return y
print(maximum(12, 35)) |
num = int(input('Write a number from 1 to 10: '))
while num > 10 or num < 1:
print('Your number is incorrect!')
num = int(input('Write a number from 1 to 10: '))
for element in range(1, 11):
result = element * num
print(f"{element} * {num} = {result}") |
import heapq
def kClosest(iterable, k, x):
smallest = []
closest = []
for value in iterable:
newValue = abs(value - x)
heapq.heappush(smallest, (-newValue, -value))
if len(smallest) > k:
heapq.heappop(smallest)
if (len(smallest) < k):
return None
print(s... |
t = int(input())
while t > 0:
r,b,d = map(int,input().split())
packs = min(r,b)
if (d+1)*packs < max(r,b):
print("NO")
else:
print("YES")
t = t-1 |
from django_pipes.middleware.stats_middleware import PipesStatsMiddleware
|
import unittest
import datetime
from test.util import ClangTest
'''Test if macro are correctly generated.
'''
import logging
# logging.basicConfig(level=logging.DEBUG)
class Macro(ClangTest):
# @unittest.skip('')
def setUp(self):
# we need to generate macro. Which is very long for some reasons.
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('basketball', '0027_statline_ast_points'),
]
operations = [
migrations.AddField(
model_name='statline',
... |
def mergeSort(array):
if len(array) == 1:
return array
middleIdx = len(array) // 2
leftHalf = array[:middleIdx]
rightHalf = array[middleIdx:]
return mergeSortedArrays(mergeSort(leftHalf), mergeSort(rightHalf))
def mergeSortedArrays(leftHalf, rightHalf):
sortedArrays = [None] * (len(le... |
import sys
sys.path.append('../500_common')
import lib_reserve
a = "Chrome1res"
b = "Profile 1"
path = "../504_kyoto01/data/result.html"
lib_reserve.main(a, b, None, None, waitTime=10, preTime=20)
|
from Minecraft_Blog import db,login_manager
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from datetime import datetime
@login_manager.user_loader
def Load_user(user_id):
return User.query.get(user_id)
class User (db.Model, UserMixin):
__tablename_... |
import os
import requests
import time
uid = os.environ['UID42']
secret = os.environ['SECRET42']
url = 'https://api.intra.42.fr/'
urlv2 = 'https://api.intra.42.fr/v2/'
def getToken():
payload = {
'grant_type': 'client_credentials',
'client_id': uid,
'client_secret': secret
}
r = requests.post(url + '... |
from datetime import datetime
from django.conf import settings
from django.db import models
from model_utils.models import TimeStampedModel
class Posts(TimeStampedModel):
"""
Model for user Posts
--- Methods ---
1) get_comments() : Return all comments on post
2) get_time() : Return modified ... |
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^(?P<user_id>[0-9]+)/$', views.user_profile, name='user'),
#url(r'^$', views.all_profile, name='all'),
#url(r'^$', views.user_profile, name='user'),
url(r'^$', views.login_page, name='login'),
]
#fix user_id regex
|
# Generated by Django 2.0.5 on 2018-06-14 12:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('calculation', '0023_auto_20180613_1651'),
]
operations = [
migrations.AlterField(
model_name='m... |
# -*- coding: utf-8 -*-
import xml.etree.cElementTree as ET
import numpy as np
import pandas as pd
def parseXML2object(filepath):
parsedFile = ET.parse(filepath)
root = parsedFile.getroot()
return root
def combineChildrenAttributeValuesInADicionary(root, *args):
dict = {}
for arg in args:
... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name = 'index'),
path('geolocate',views.geolocate,name = 'geolocate')
] |
# -*- coding: utf-8 -*-
"""Export from the 3DNL database.
Copyright (c) 2019, 3D geoinformation group, Delft University of Technology
The MIT License (MIT)
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... |
from ._base import IterativeInitialGuess, _IterativeSolver
import src.matrix_operations as matops
class JacobiSolver(_IterativeSolver):
def __init__(self, **kwargs):
"""
:key matA: Matrix A
:key matb: Matrix b
:key guess_source: how guess should be derived, should be an IterativeIn... |
print round(1.23, 1)
print round(1.27, 1)
print round(-1.27, 1)
print round(1.25361, 3)
a = 1627731
print round(a, -1)
print round(a, -2)
print round(a, -3)
x = 1.23456
print format(x, '0.2f')
print format(x, '0.3f')
print "value is {:0.3f}".format(x)
a = 2.1
b = 4.2
c = a + b
print c
print round(c, 2) |
#!/usr/bin/env python
# encoding: utf-8
"""Usage:
named_id.py train <protocol> <experiment_dir> [options] [--from=<epoch>] [(--augment=<ratio> [--uniform])]
named_id.py validate <protocol> <train_dir> [options] [--evergreen --interactive]
named_id.py test <protocol> <validate_dir> [options] [--interactive]
named_id.py... |
city_choices = {
'lahore' : 'Lahore',
'sialkot' : 'Sialkot',
'karachi' : 'Karachi',
}
price_choices = {
'1000':'1000',
'2000':'2000',
'3000':'3000',
'5000':'5000',
'6000':'60000',
'10000':'10000',
}
state_choices = {
'Alaska': 'Alaska',
'Alabama': 'Alabama',
'Punjab': ... |
# Generated by Django 2.0.3 on 2018-03-19 10:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0002_aboutus_basic_info_faq'),
]
operations = [
migrations.CreateModel(
name='Slider',
fields=[
... |
from django.shortcuts import render
from .models import OtherUser, Category, Item, ItemImageAndVideos, Offers, Searches, Message, Notifications, ShipmentDetails, ContactUs
import json
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from djang... |
n = int(input())
a = list(map(int,input().split()))
ans = []
tmp = []
flag = 0
for i in range(len(a)):
if len(tmp) == 0:
tmp.append(a[i])
elif flag == 0:
flag = 1 if tmp[-1] < a[i] else -1 if tmp[-1] > a[i] else 0
tmp.append(a[i])
elif (flag == 1 and tmp[-1] <= a[i]) or (flag == -1 ... |
#__date__ = 6/14/18
#__time__ = 4:08 PM
#__author__ = isminilourentzou
import torch
import torch.nn as nn
import torch.nn.functional as F
class WordRepr(nn.Module):
def __init__(self, opt, vocabs):
super(WordRepr, self).__init__()
self.opt = opt
self.word_vocab, self.char_vocab, self.case... |
import os.path as osp
import pandas as pd
from .manager import BaseManager
from utils import seed_everything, make_datapath_list, show
from dataset import TestDataset, Anno_xml2list, DataTransform, od_collate_fn, get_dataloader
from models import ObjectDetectionModel
class Infer(BaseManager):
def __call__(self):
... |
factors = [1, 2, 5, 10]
names = ['Anand', 'April', 'Justin']
mixed = [3, True, 'Yellow']
print(factors[3])
print(names[0])
print(mixed[0:2])
print(len(names))
s = 'hello'
# For a string, both a single position and a slice return strings
print(type(s[0]))
print(type(s[0:1]))
# For a list, a single position returns a ... |
import sqlite3
class DBHelper:
def __init__(self,db_name):
self.conn=sqlite3.connect(db_name,check_same_thread=False)
self.conn.row_factory=sqlite3.Row
self.cursor=self.conn.cursor()
def get_regions(self):
# print('assskdjsjjakjka diskskskkscks')
return self.cursor.execute('SELECT id, ibora,meaning FROM... |
from model.Group import Group
import logging
def loadGrupos(measurs):
try:
grupos = {}
grupos['5'] = Group(5,30)
grupos['10'] = Group(10,50)
for grupo in grupos.values():
for measur in measurs.values():
if measur.grupo_time == grupo.time_interval: ... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/',methods=["GET","POST"])
@app.route('/persona/<cadena>/<int:edad>',methods=["GET","POST"])
def saluda(cadena="NADIE",edad=0):
nombre = cadena
return render_template("inicio.html",nombre=nombre,edad=edad)
@app.route("/articulos/<int:numer... |
from django.apps import AppConfig
class Blog22Config(AppConfig):
name = 'blog22'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
f = open("水聯盟資料清單 - 水太少.csv", "r")
all_row = []
for row in f:
e_row = []
new_row = row.split(",")
for item in new_row:
e_row.append(item)
all_row.append(e_row)
# Text = "<html><p><b>水聯盟資料清單 水太多</b><p><html>\n"
# Text = Text + "<p>新... |
# -*- coding: utf-8 -*-
import pytest
from fractions import Fraction
from openprocurement.auction.esco.utils import prepare_initial_bid_stage
@pytest.mark.parametrize(
'input,expected', [
(
{
'bidder_name': '2',
'bidder_id': '5675acc9232942e8940a034994ad883e',... |
import os
import ray
import json
import tqdm
import torch
import logging
from typing import List
logger = logging.getLogger(__name__)
class FullDocIterator:
def __init__(self):
pass
class FullDocBatchIterator:
def __init__(self):
pass
|
from django.db import models
class Comment(models.Model):
user= models.CharField(max_length=50)
comment= models.TextField()
|
sal = float(input('Qual é o salário do funcionário? R$'))
aum = (sal * 15) / 100
Nsal = (sal + aum)
print('Um funcionário que ganhava R${:.2f}, com 15% de aumento, passa a receber R${:.2f}'.format(sal, Nsal))
|
# created by Ryan Spies
# 3/24/2015
# Python 2.7
# Description: generate an input file with for the MAT preprocessor
# MAT input format: http://www.nws.noaa.gov/oh/hrl/nwsrfs/users_manual/part3/_pdf/38mat.pdf
import os
import math
import dateutil
os.chdir("../..")
maindir = os.getcwd()
################### user input... |
import math
import googlemaps
from scipy.optimize import bisect
import pandas as pd
import glob
def distance_on_unit_sphere(lat1, long1, lat2, long2):
"""
Convert latitude and longitude to spherical coordinates in radians.
phi = 90 - latitude
theta = longitude
Compute spherical distanc... |
from django.db import models
from django.utils import translation
from django_extra_referrals.models import AbstractPayable, AbstractReceivable
_ = translation.ugettext_lazy
class Donation(AbstractReceivable):
fullname = models.CharField(max_length=150)
def __str__(self):
return self.fullname
clas... |
class Bank:
name = None
def assignName(self,bname):
self.name = bname
def displayName(self):
print(self.name)
#Object Creation
b1 = Bank()
#Calling Function's
b1.displayName() #None
b1.assignName("Kotak")
b1.displayName() #Kotak
#Object Creation
b2 = Bank()
#Calling Funct... |
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import time
import random
import tweepy
import os
import json
import io
# Go to http://dev.twitter.com and create an app.
# The consumer key and secret as well as the access_token and secret will be generated for ... |
from collections import defaultdict
def data_to_dict(data, get_mean=True):
result = defaultdict(dict)
for place in data.split('\n'):
all_temps = []
key, temps = place.split(':')
temps_sum = total_temps = 0.0
for temp in temps.split(','):
t = float(temp.split()[1])
... |
import numpy as np
import csv
import matplotlib.pyplot as plt
""""对男女声音进行辨别"""
class NaiveBayes():
def load_data_set(self,file_name):
"""
:param file_name: 文件名字
:return
train_mat:离散化的训练数据集
train_classes: 训练数据集所属的分类
test_mat:离散化的测试数据集
test_classes:测试数据集所述的分类
... |
import os
import definitions
import wsdm.ts.helpers.persons.persons as p_lib
import wsdm.ts.helpers.nationalities.nationalities as nat_lib
import wsdm.ts.helpers.train.common_train as common_train
def init_all_positive_nationalities():
global persons
result = common_train.init_nationalities_empty_dict()
t... |
import datetime
name = str(input("Enter your name"))
age = int(input("Enter your age"))
currentyear = int(datetime.date.today().strftime("%Y"))
futureyear = (currentyear) + 100 - (age)
print("\nHello " + name + " will turn 100 years in " + str(futureyear)) |
from django.db import models
from django.conf import settings
from rest_framework.exceptions import ValidationError
from django.utils.timezone import localdate
from ..common.models import CommonModel
from .managers import MenuManager, OptionManager
from ..common.utils import throwable
class Menu(CommonModel):
"""... |
from django.contrib import admin
# Register your models here.
from .models import toDoList
class toDoListadmin(admin.ModelAdmin):
list_display=["userdetails","taskName","description","status","ts"]
admin.site.register(toDoList,toDoListadmin) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import argparse
from train import train_full
from model.model import UNet
from dataloader.dataloader import InriaDataset
import pandas as pd
var= pd.read_json('variables.json')
# Root
#root = '/home/ign.fr/ttea/Code_IGN/AerialImageDataset'
#train_dir = os... |
def load_file(filename):
f = open(filename, "r")
data = f.read()
f.close()
return data
def load_lines(filename, sep=","):
return [line.split(sep) for line in\
load_file(filename).splitlines()[1:]]
def groupby(d,cols,callback=None):
if hasattr(d, "keys"):
return _group_line... |
from tetris.menu.AbstractComponents import *
from tetris.menu.AbstractEntities import *
from Systems import *
from Entities import *
from tetris.game import GameComponent
class Menu(MenuComponent):
def __init__(self, window, world):
super(Menu, self).__init__(window, world)
self.entity = MenuEntit... |
from art import logo
from art import logo
import random
print(logo)
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
testdict = {
'mike':20,
'dave': 21,
}
def deal_a_card(deck):
deck.append(random.choice(cards))
return deck
def deal():
two_cards = []
for num in (0,2):
two_cards.append(random.choic... |
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
from django.db import transaction
from .forms import UserForm, ProfileForm
fr... |
import os
import re
path_to_read_file = os.path.join('in.txt')
path_to_write_file = os.path.join('out.txt')
words_pattern = re.compile(r'[0-9+]')
numbers_pattern = re.compile(r'[^0-9]')
result = ''
with open(path_to_read_file, 'r') as file_reader:
s = file_reader.readline().strip()
words_list = re.sub(words_patt... |
import cv2
import numpy as np
import os
import pickle
# AN=1, DI=2, FE=3, HA=4, NE=5,SU=6, SA=7
left_eye_cascade = cv2.CascadeClassifier('haarcascade_lefteye_2splits.xml')
right_eye_cascade = cv2.CascadeClassifier('haarcascade_righteye_2splits.xml')
mouth_cascade = cv2.CascadeClassifier('haarcascade_mcs_mouth.xm... |
class Item:
def __init__(self, name, location, stock):
self.name = name
self.location = location
self.stock = stock
def dictify(self):
return {
'name' : self.name,
'location' : self.location,
'stock' : self.stock
}
def adapt(sel... |
some_string = input("Input some string:")
print(some_string[2], some_string[len(some_string)-2], some_string[:5], some_string[:len(some_string)-3],
some_string[0:len(some_string):2], some_string[1:len(some_string):2], some_string[::-1],
some_string[::-2], len(some_string))
|
from django.contrib.auth import logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.shortcuts import get_object_or_404
from django.urls import... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from pants.util.frozendict import FrozenDict
@dataclass(frozen=True)
class NativeParsedPythonDependencies:
impo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
import ujson
from sanic import Blueprint
from sanic import response
from geojson import FeatureCollection
from sanic.request import Request
from sanic_jwt import inject_user
from .service import (
get_hw_module_position_last_point_list, delete... |
import pika
import time
connection = pika.BlockingConnection(
pika.ConnectionParameters(
'localhost'
)
)
channel = connection.channel()
channel.queue_declare(queue='task_queue_2', durable=True)
def callback(ch, method, properties, body):
print(' [x]... |
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
import os
import cPickle
from .._utils import ui
__all__ = ('pickle',)
def pickle(obj, dest=None, protocol=cPickle.HIGHEST_PROTOCOL):
"""Pickle a Python object.
Parameters
----------
dest : None | str
Path to destination where to save... |
# -*- coding:UTF-8 -*-
from urllib import request
from bs4 import BeautifulSoup
import collections
import re
import os
import time
import sys
import types
import pymysql
import requests
import json
import random
"""
类说明:下载《笔趣看》网小说: url:http://www.biqukan.com/
Parameters:
target - 《笔趣看》网指定的小说目录地址(string)
Returns:
无... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
a, b, c, d = float("-inf"), float("-inf"), float("inf"), float("inf")
for num in nums:
if num > a:
a, b = num, a
elif num > b:
... |
# -*- coding: utf-8 -*-
# @Time : 2018/7/15 11:04
# @Author : xnbo
# @Site :
# @File : websocket_base.py
# @Software: PyCharm
import threading
class WebSocketBase(object):
def __init__(self, service_base, url=None):
""" Connect to the websocket and initialize data stores ."""
... |
from alignment import *
I = np.mat('-1 1 0; 0 -1 0; 0 1 -1')
m, n = np.shape(I)
r = 2
iter = 100
eps = 1e-4
(V, U) = mixed_alignment(I, eps, iter, True)
J = np.eye(3)*-1
J[0,1:3] = 1
(V, U) = simple_alignment(2, J)
|
def calculate_ratio(w,h):
c_gcd = gcd(w,h)
ar_w,ar_h = w//c_gcd,h//c_gcd
return '{}:{}'.format(ar_w,ar_h) if ar_w and ar_h else 'You threw an error'
def gcd (a,b):
if b==0:
return a
return gcd (b,a%b)
'''
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine imag... |
import json
class Record(object):
"""记录模块,用于记录断点和将抓取的结果写入文件"""
def __init__(self):
# 断点记录文件路径
self.breakpoint = r'E:\20190320\taobao\breakpoint.txt'
# 抓取结果文件路径
self.result = r'E:\20190320\taobao\result.json'
# 无搜索结果文件路径
self.no_result = r'E:\20190320\taobao\no_r... |
RAW_WEBPAGES = "WEBPAGES_CLEAN"
BOOKKEEPING = "WEBPAGES_CLEAN/bookkeeping.json"
TOP_N_results = 500
INDEX_PATH = 'index.json'
HEADER_PATH = "header.json"
|
import torch
class WarmLR(torch.optim.lr_scheduler._LRScheduler):
def __init__(self, optimizer, lr_lambda, last_epoch=-1):
self.optimizer = optimizer
if not isinstance(lr_lambda, list) and not isinstance(lr_lambda, tuple):
self.lr_lambdas = [lr_lambda] * len(optimizer.param_grou... |
# -*- coding: utf-8 -*-
import heapq
from collections import Counter
class Solution:
def topKFrequent(self, words, k):
counter = Counter(words)
most_common = []
for el in counter.items():
heapq.heappush(most_common, (-el[1], el[0]))
return [el[1] for el in heapq.nsma... |
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import threading
from time import sleep
import cv2
import numpy as np
from cv2 import aruco
import array
import serial
from math import radians
from smbus import SMBus
# Set busial address
try:
addr = 0x... |
from django.conf import settings
if not settings.configured:
settings.configure()
import json
import urllib
import simplejson
import googlemaps
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
import requests
from lxml import h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.