text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-13 23:27
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Category, Base, Item, User
# import authorization
engine = create_engine("sqlite:///catalog.db")
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession in... |
import json
import os
import traceback
from glob import glob
from typing import Dict, List
from colorama import Fore
from mysql.connector import MySQLConnection
from mysql.connector.cursor import MySQLCursor
from console import console
fields = {
"author": {"type": "string"},
"dynasty": {"type": "string"},
... |
from celery import app
from .service import send_order_to_restaurant, send_delivery_notification_to_customer
@app.shared_task
def send_order_to_restaurant(restaurant_email, meal):
send_order_to_restaurant(restaurant_email, meal)
@app.shared_task
def send_delivery_notification_to_customer(user_email, meal, orde... |
import Tkinter
import tkMessageBox
import numpy as np
import caffe
import glob
import pylab as pl
from tkFileDialog import askdirectory
import cv2
import sys
classes = {0: "safe driving", 1:"texting right", 2: "talking on the phone right",
3: "texting (left)",4: "talking on the phone (left)",5: "operating the radi... |
' Find line numbers for specific latlon locations using the compare.prn file '
from numpy import *
compareFile = open ('compare.prn','rb')
compareArr = compareFile.readlines(); compareFile.close()
inputfile = raw_input ('Input filename: ')
infile = open (inputfile,'rb')
infileArr = infile.readlines(); infile.close()... |
import sys
from PyQt5.QtWidgets import *
class QLineEditEchoMode(QWidget):
"""QLineEdit类是一个单行文本控件,可输入单行字符串,可以设置回显模式(Echomode)和掩码模式
1. 回显模式(Echomode)
回显模式就是当键盘被按下后,显示了什么
Normal 正常的回显模式
NoEcho 不回显模式(什么都没出现)
Password 密码
PasswordEchoOnEdit 先是显示,然后过了几秒就不显示
"""
def __init__(self):
super(QLineEditEchoMode,... |
# Generated by Django 2.2.6 on 2020-11-02 14:10
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('p_pols', '0009_poll_pub_date'),
]
operations = [
migr... |
# 查询指定规划师完成的订单列表
select_planner_complete_order_list = "SELECT du.`Id`,du.`DemandServiceId`,du.`UserId`,du.`OrderStatus`,du.`CreateUserID`,du.`CreateTime`, " \
"ds.PriceStart,ds.PriceEnd, " \
"ds.TimeStart,ds.TimeEnd,sa.Name AS ServiceAreaName,st... |
import logging
from flask import request
from flask_restplus import Resource
from api.serializers import wishlist, wishlist_response, wishlist_item, wishlist_item_response, wishlist_items_list_response, response
from api.parsers import pagination_arguments
from api.restplus import api, token_required
from services.wish... |
from survey import AnonymousSurvey
# 定义一个问题, 并创建一个表示调查的AnonymousSurvey对象
question = "你会什么语言?\n"
my_survey = AnonymousSurvey(question)
# 显示问题并存储答案
my_survey.show_question()
print("输入q退出程序\n")
while True:
response = input("会的语言是: ")
if response == 'q':
break
my_survey.store_response(res... |
from django.urls import path, include
from . import views
urlpatterns = [
path('hello', views.hello, name="hello"),
path('schedule', views.schedule, name="schedule"),
] |
def calculateArea(radius) :
pie = 3.143
return pie * radius * radius
# Needed to run the file as a CLI program from the command line
def main():
radius = float(input("\nPlease, enter the radius here: "))
area = calculateArea(radius)
print(f"The Area of the circle with radius {radius:.2f} is {area:.2f}")
# Ru... |
import random
import math
import numpy as np
from scipy.stats import multivariate_normal
def expectation_maximization(df, pca_df):
"""
Main method for classification using Expectation Maximization
Uses the PCA features from part 5
:param df: Loaded data as a DataFrame
:param pca_df: DataFrame... |
'''
Definitions for nodes in the abstract syntax tree.
'''
from __future__ import absolute_import, print_function
from frontend import typesys
class Node(object):
def accept(self, visitor, arg=None):
return visitor.visit(self, arg)
@property
def children(self):
return list()
def rep... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 22:26:06 2020
@author: jakerabinowitz
"""
import numpy as np
import pandas as pd
import statistics as stat
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Problem 2a
def read_sat_data():
"""Read the satellite and su... |
# -*- coding: utf-8 -*-
import Xerces
from __XQilla import *
# Initialize XQilla
XQillaPlatformUtils.initialize()
# XQillaImplementation
gXPath2_3_0 = Xerces.XMLString('XPath2 3.0')
|
#!/usr/bin/env python2
# -*-coding:utf-8-*-
# Author:SesameMing <blog.v-api.cn>
# Email:admin@v-api.cn
# Time:2017-03-28 16:45
def fact(x):
if x == 1:
return 1
else:
return x * fact(x-1)
print fact(6) |
#Import CSV to Postgresql
import psycopg2
import pandas as pd
conn = psycopg2.connect("host=localhost dbname=homework_users user=postgres password=Winchester110283")
cur = conn.cursor()
df_users = pd.read_csv('predefined_users.csv', index_col=0)
for idx, u in df_users.iterrows():
cur.execute('''INSERT INTO users (... |
import boto3
# ec2を立ち上げてelbに紐付ける
# INSTANCE_ID, ARNはlambdaの環境変数で設定
# エラーハンドリングもできてないし、ログも出ない
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
ec2_response = ec2.start_instances(
InstanceIds = [
INSTANCE_ID,
]
)
print ec2_response
waiter = ec2.get_waiter('i... |
from django import forms
import datetime
class CommentForm(forms.Form):
name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control mb-2', 'rows': 2, 'cols': 2}))
content = forms.CharField(max_length=1000, widget=forms.Textarea(attrs={'class': 'form-control mb-2', 'rows': 4, 'col... |
# -*- python -*-
# This file contains rules for Bazel; see drake/doc/bazel.rst.
package(default_visibility = ["//visibility:public"])
cc_binary(
name = "schunk_driver",
srcs = [
"crc.h",
"defaults.h",
"position_force_control.h",
"position_force_control.cc",
"schunk_dri... |
# 从左到右,从上向下
# 一维数组打印成行,二维数组打印成矩阵,三维数组打印成矩阵列表
import numpy as np
print(np.arange(1,6,2))
print(np.arange(12).reshape(3,4)) # 可以改变输出形状
print(np.arange(24).reshape(2,3,4))# 2页,3行,4列
|
from django.conf.urls import url, patterns
from newswall.feeds import StoryFeed
from newswall import views
urlpatterns = patterns(
'',
url(r'^feed/$', StoryFeed()),
url(r'^get/$',
views.FeedDataView.as_view(),
name='newswall_feed_data'),
url(r'^$',
views.ArchiveIndexView.as_vi... |
"""
The JSON Extension adds the :class:`JsonOutputHandler` to render
output in pure JSON, as well as the :class:`JsonConfigHandler` that allows
applications to use JSON configuration files as a drop-in replacement of
the default :class:`cement.ext.ext_configparser.ConfigParserConfigHandler`.
Requirements
------------... |
from database_services.RDBService import RDBService
class UserRDBService(RDBService):
def __init__(self):
pass
@classmethod
def get_user_and_address(cls, template):
wc, args = RDBService.get_where_clause_args(template)
sql = "select * from db.users left join db.addresses on " + ... |
# -*- coding: utf-8 -*-
"""
@Project : show_project
@File : savedb.py
@Author : 王白熊
@Data : 2021/3/22 14:20
"""
# -*- coding:UTF-8 -*-
import pandas as pd
from Log import Logger
from sqlalchemy import create_engine
logger = Logger('excel_to_db').getlog()
import psycopg2
from io import StringIO
def psycopg2_... |
import constants as const
def get_value_by_key_from_answer(answer, key):
return answer[key]
def split_chosen_coffee_with_price(answer):
chosen_coffee = get_value_by_key_from_answer(answer, const.COFFEE_TYPE)
spl = chosen_coffee.split()
coffee_type = spl[0]
price_for_one_coffee = int(spl[1])
... |
from functools import reduce
from math import log, pow, inf
from statistics import mean
BASE = 2
JUMP = 0.05
def frange(x, y, jump):
"""
Like `range()`, but for floats
http://stackoverflow.com/a/7267280/2250435
"""
while x < y:
yield x
x += jump
def trigram_lambdas():
"""
... |
#
# @lc app=leetcode id=12 lang=python3
#
# [12] Integer to Roman
#
# @lc code=start
class Solution:
def intToRoman(self, num: int) -> str:
dic = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', \
100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
res = ""... |
# AirBnB RPA Functions
import os
import rpa as r
import shutil
URL = "https://www.airbnb.com.sg"
USERNAME = "rpatestuser001@gmail.com"
PASSWORD = "P@$$w0rd123"
def initialize():
print('Initializing...')
r.init()
r.timeout(15) #set timeout to wait longer
r.url(URL)
while r.exist('//*/button[@type=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-26 06:57:59
# @Author : mutudeh (josephmathone@gmail.com)
# @Link : ${link}
# @Version : $Id$
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
de... |
import os
import zlib
import math
import struct
import copy
import chromosome.gene as gene
import chromosome.serializer as serializer
import chromosome.deserializer as deserializer
PNG_SIGNATURE = '\x89\x50\x4e\x47\x0d\x0a\x1a\x0a'
class PNGGene(gene.AbstractGene):
'''
The PNGGene represent a png chunk.... |
# -*- coding: utf-8 -*-
"""
activity stream
Customer Portal Home
:copyright: (c) 2012-2013 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
from decimal import Decimal
import pytz
import hashlib
import base64
import urllib
from datetime import timede... |
import requests
from lxml import etree
import sys
def login():
pass
def getcsrfmiddlewaretoken():
url = 'https://www.appannie.com/account/login/?_ref=header'
headers = {"user-agent":'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0'}
html = requests.get(url,headers=headers)
csrfmiddlewaret... |
import os
import glob
from subprocess import call
def list_raster(indir):
tif_list = glob.glob(indir+'\*.tif')
with open(indir+'\\tif_list.txt', 'wb') as f:
for fn in tif_list:
path, name = os.path.split(fn)
print fn
f.writelines(fn+'\n')
return
def build_vrt(i... |
from asyncio import Transport
class MockTransportBase(Transport):
def __init__(self, myProtocol=None, extra=None):
super().__init__(extra)
self.writeCount = 0
self.loop = None
self.delay = None
self.sink = None
self.protocol = myProtocol
self.closed... |
from googleapiclient.discovery import build
from pymongo import MongoClient
from datetime import datetime
import json
#requests da lib no lambda - para rodar localmente -> import requests
# import requests
from botocore.vendored import requests
def lambda_handler(event, context):
my_api_key = "####################... |
"""
Programma voor het berekenen van de frequenties voor staande
golven in een half gesloten buis.
"""
import numpy as np
import matplotlib.pyplot as plt
class Freq(object):
"""
Frequentie object
Berekent tabel met staandegolf frequenties
"""
def __init__(self, l, v):
sel... |
"""this is a example package that im ..."""
from datetime import date
from math import pi
import webbrowser as w
from random import choice
import turtle as t
import wikipedia # You must install wikipedia before you're useing wikipedia_info
__version__ = '0.0.5'
MAXPOOWER = 39.99999999999999
MINPOOWER = -39.99999... |
import numpy as np
import os
import matplotlib.pyplot as plt
from scipy import signal
from helperFunctions import *
from math import log
root_dir = os.path.abspath('./')
data_dir = os.path.join(root_dir, '../dataset', 'dataset3.5', 'subject1_ascii')
data_to_be_referred = [7,8,11,12,18,21,22,31]
files = ['train_subject1... |
from keras.models import load_model
import numpy as np
def load_models():
model1 = load_model('Halloween_model_edition_80.h5')
print("\nmodel1 loaded")
model2 = load_model('Halloween_model_edition_73.h5')
print("\nmodel2 loaded")
model3 = load_model("Halloween_model_edition_78.h5")
print("\nmode... |
import setuptools
with open("docs/README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="linkcheck-pkg-MLJBrackett",
version="1.1",
author="Michael Brackett",
author_email="mljbrackett@gmail.com",
description="A simple link checking program",
long_description=long_des... |
import tensorflow as tf
import horovod.tensorflow as hvd
# Ground Truth Shape: [npoint, 7 (w, l, h, x, y, z, r)]
# Prediction Shape: [npoint, 7 (w, l, h, x, y, z, r)]
'''
x (w)
^
0 | 1
|---------------|
| * | ---> y (l)
|---------------|
3 2
'''
eps = ... |
import logging
import time
import requests
from eodag import EOProduct
from eodag.api.product.metadata_mapping import (
format_query_params,
mtd_cfg_as_conversion_and_querypath,
properties_from_json,
)
from eodag.plugins.search.base import Search
from eodag.utils import GENERIC_PRODUCT_TYPE, string_to_jso... |
import re, json, requests
import cv2
# api-endpoint
URL = "http://127.0.0.1:8000/"
# defining a params dict for the parameters to be sent to the API
# sending get request and saving the response as response object
img = cv2.imread('uploads/00000103_001.png')
# print(img)
data= {"photo":img}
resp = requests.post(url... |
from ipywidgets import Dropdown
from IPython.display import display, clear_output, Markdown, HTML
def _display(arg):
display(HTML("""
<style>
.output {
display: flex;
align-items: center;
text-align: right;
}
</style>
"""), arg)
EMPTY = ... |
import pytest
from selenium import webdriver
@pytest.fixture(name='sub11')
def sub1():
return 9
@pytest.fixture(name='driver1')
def driver():
driver=webdriver.Chrome()
driver.get("http://www.baidu.com")
yield driver #用yield 相当于yield前的是setup 后的是teardown阶段。
driver.close()
|
import numpy as np
import scipy.optimize as opt
from scipy import *
import matplotlib.pyplot as plt
import cosmolopy.constants as cc
import cosmolopy.distance as cd
import cosmolopy.perturbation as cp
#=============Functions ====================
def func(p,x):
w=10.**p[0]* x**p[1] * np.exp(-p[2]*x)
print w.siz... |
from django.contrib.auth.views import login as auth_login
from allauth.socialaccount.models import SocialApp
from allauth.socialaccount.templatetags.socialaccount import get_providers
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.shortcuts import render
from .for... |
import numpy as np
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from torchvision.datasets import ImageFolder
from options import Options
def load_data(opt):
""" Load Data
Args:
opt ([type]): Argument Parser
Raises:
IOError: Cannot load dataset
Re... |
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Comment
from django.urls import reverse_lazy
from .forms import CommentForm
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your ... |
import tempfile
from pathlib import Path
import cv2
from fpdf import FPDF
from PIL import Image
import utils
def create_markers(marker_type):
marker_ids = utils.get_marker_ids(marker_type)
if marker_type == 'robots':
marker_ids = 5 * marker_ids + marker_ids[:4]
elif marker_type == 'cubes':
... |
"""Вычислить квадратное уравнение ax2 + bx + c = 0 (*)
D = b2 – 4ac;
x1,2 = (-b +/- sqrt (D)) / 2a
Предусмотреть 3 варианта:
Два действительных корня
Один действительный корень
Нет действительных корней
"""
import math
a = int(input())
b = int(input())
c = int(input())
try:
d = b ** 2 - 4 * a * c
x1 ... |
import tensorflow as tf
def get_tensor_shape(x):
a = x.get_shape().as_list()
b = [tf.shape(x)[i] for i in range(len(a))]
return [aa if type(aa) is int else bb for aa, bb in zip(a, b)]
# [b, n, c]
def sample_1d(
img, # [b, h, c]
y_idx, # [b, n], 0 <= pos < h, dtpye=int32
):
b, h, c ... |
class Chapter:
def __init__(self, title, url):
self.title = title
self.url = url
self.text = None
def set_body_text(self, text):
self.text = text
def get_post_id(self):
if "threads" in self.url:
return f"post-{self.url.split('-')[-1]}"
elif "post... |
from django.core.management import BaseCommand
from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements
class Command(BaseCommand):
help = ('Update facility_supervision cases with indicators collected '
'in DHIS2 over the last quarter.')
def handle(self, *args, **options):
... |
from rest_framework.exceptions import APIException
class NotFoundException(APIException):
status_code = 404
|
from zope.interface import Interface
from zope.interface import implements
from zope.component import adapts, getMultiAdapter
from plone.memoize.instance import memoize
from plone.app.portlets.portlets import navigation
from plone.app.layout.navigation.interfaces import INavtreeStrategy
from plone.app.layout.navigation... |
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.IN)
rearm = 6 #delay for rearming the PIR
startup = 2 #startup delay
delay = 0.1 #loop delay
try:
sleep(startup)
while True:
if(GPIO.input(16)):
... |
import math
NUMBER_OF_EPSILON = 1000
def dichotomy(function,l, r, epsilon):
interval = r - l
iteration = 0
delta = epsilon / 2
left_border = l
right_border = r
# print('start_point', 'end_point', 'length', 'lenght/prev_lenght', 'x1', 'f(x1)', 'x2', 'f(x2)')
while abs(right_b... |
# Copyright (c) 2019-2023, Jonas Eschle, Jim Pivarski, Eduardo Rodrigues, and Henry Schreiner.
#
# Distributed under the 3-clause BSD license, see accompanying file LICENSE
# or https://github.com/scikit-hep/vector for details.
from __future__ import annotations
import math
import pytest
import vector.backends.obje... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randint, random, shuffle
import math
from collections import namedtuple
import numpy as np
import matplotlib.pyplot as plt
from copy import copy
Point = namedtuple("Point", ['x', 'y'])
#lengths = None
def length(point1, point2):
return math.sqrt((point1... |
#!flask/bin/python
from flask import Flask, jsonify
from bs4 import BeautifulSoup
import requests
from nltk.corpus import wordnet as wn
from textblob import TextBlob
from nltk.tokenize import sent_tokenize, word_tokenize
from flask.ext.cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/<subject>')
def inde... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 19 13:52:15 2017
@author: william2
"""
import sqlite3
db=sqlite3.connect("GrandeFortaleza.db")
c=db.cursor()
CHANGE="DELETE FROM ways_tags WHERE key='fixme';"
c.execute(CHANGE)
CHANGE="DELETE FROM nodes_tags WHERE key='fixme';"
c.execute(CHANGE)
db... |
# 10/04/2020 --- DD/MM/YYYY
# https://www.hackerrank.com/challenges/mark-and-toys/problem?h_l=interview&h_r=next-challenge&h_v=zen&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=sorting
def maximumToys(prices, k):
result = 0
# Sort first
prices.sort()
# Then greedy
... |
"""
每个磁盘大小d[i]
每个分区大小p[i]
"""
def is_allocable(d: list, q: list):
# 磁盘分区下标
index = 0
# 磁盘数量
length = len(d)
for space in q: # 分区大小
# 找到符合条件的磁盘
while index < length and space > d[index]:
index += 1
if index >= length:
return False
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 10 19:51:40 2017
@author: LALIT ARORA
"""
# This is a Credential class to send credentials to the mail app.
class cred:
def sendid():
return "ENTER SENDER'S EMAIL ID"
def sendpass():
return "ENTER YOUR PASSWORD HERE"
|
#!/usr/bin/env python3
"""
This is a good foundation to build your robot code on
"""
import wpilib
import rev
from networktables import NetworkTables
from networktables.util import ntproperty
import math
from wpilib.drive import DifferentialDrive
class MyRobot(wpilib.TimedRobot):
def robotInit(self):
... |
from TuringMachine import *
from FileReader import readFile
filename = " "
while len(filename) > 0:
try:
filename = input("Enter filename of Turing Machine (Leave blank to exit): ")
tm = readFile(filename)
inputStr = " "
while len(inputStr) > 0:
try:
inputStr = input("Enter space separated input (integ... |
import tkinter as tk
import random
class Grid:
def __init__(self,n):
self.size=n
self.cells=self.generate_empty_grid()
self.compressed=False
self.merge=False
self.moved=False
self.current_score=0
def generate_empty_grid(self):
... |
from math import *
T = int(input())
for cas in range(T):
a,b,c,d,e,f,g = map(int,input().split())
if(a**d+b**e+c**f==g):
print("Yes")
else:
print("No")
|
import tensorflow as tf
import tensorflow.contrib.slim as slim
import scipy.io as sio
import matplotlib.pyplot as plt
def attention(x, ch, scope='attention', reuse=False,bs=10):
with tf.variable_scope(scope, reuse=reuse):
f = slim.conv2d(x, ch // 8, 1, stride=1, scope='f_conv')
g = slim.conv2d(x, ... |
# -*- coding: 850 -*-
from datetime import datetime, timedelta, date
from pytz import timezone
from openerp import SUPERUSER_ID
from openerp import api, fields, models, _
import openerp.addons.decimal_precision as dp
from openerp.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT
from open... |
from light.effect.resolved_effect import ResolvedEffect
from light.rgbw import RGBW
from light.effect.effect_priority import EffectPriority
class PartialEffect:
def __init__(self, startTime=0):
self.startTime = startTime
self.isModifier = False
def getEffect(self):
return ResolvedEffec... |
# Module file for implementation of ID3 algorithm.
import pandas as pd
import numpy as np
from helper import *
from tree import Node
import pickle
# You can add optional keyword parameters to anything, but the original
# interface must work with the original test file.
# You will of course remove the "pass".
import o... |
from __future__ import unicode_literals
import csv
from django.core.management.base import BaseCommand
from django.utils.encoding import force_text
from ...models import HistoricalStockData, Stocks
SILENT, NORMAL, VERBOSE, VERY_VERBOSE = 0, 1, 2, 3
class Command(BaseCommand):
help = (
"Imports movies from... |
"""
Think of your favorite mode of transportation, such as a motorcycle or a car, and make a list that stores several examples.
Use your list to print a series of statements about these items, such as “I would like to own a Honda motorcycle.”
"""
my_list = ['Ducati', 'audi', 'bmw']
print(f"I don't like {my_list[... |
from dataclasses import dataclass, field
from project_management.entities.task import Task
from datetime import datetime, timezone
from project_management.asana import util
# Asana application Specific Task entites
@dataclass
class AsanaTask(Task):
task_completed: bool = False
due_date: str = None
t... |
import requests
from bs4 import BeautifulSoup
import random
req = requests.get("https://dhlottery.co.kr/gameResult.do?method=byWin&drwNo=837").text
soup = BeautifulSoup(req, 'html.parser')
for i in range(6):
lucky = soup.select_one(".ball_645").text
print(lucky)
#article > div:nth-child(2) > div > div.win_re... |
import sys
import dictionary
import logging
from grammar import Sentence, Action
'''
The main running code of the program, probably.
Might later be either renamed "__main__.py" or replaced with a file named __main__.py so that we can simply run the wat package.
'''
__author__ = "SAI"
class Translator:
'''
?... |
from django.db import models
from eSchoolGateProject import settings
class Subject(models.Model):
name = models.CharField(max_length=100,)
teacher = models.ManyToManyField(settings.AUTH_USER_MODEL)
classroom = models.CharField(max_length=7,)
def __unicode__(self):
return self.name + ' - ' + s... |
# Copyright (c) 2015, Dataent Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import dataent, unittest, os
from dataent.utils import cint
from dataent.model.naming import revert_series_if_last, make_autoname, parse_naming_series
class TestDocument(unittes... |
from selenium import webdriver
import time
from selenium.webdriver.support.select import Select
def driver_uu():
driver = webdriver.Chrome('../chromedriver/chromedriver.exe')
driver.get('http://192.168.60.146:8080/demo1.html')
time.sleep(3)
input_el = driver.find_element_by_xpath('/html/body/table/tbo... |
"""
Author: Yash Soni
Date: 23_Jan_2021
Purpose: Python Learning Purpose
"""
import random
def Random_generaotr(new_list):
while True:
Random=random.randint(1,len(new_list))
if Random%2!=0:
Surname=Random
break
else:
continue
return Surname
if __name__... |
import bcrypt
from django.shortcuts import render, redirect
from .models import Users, Posts, Comments
from django.contrib import messages
from .decorators import login_required
@login_required
def index(request):
context = {
'users' : Users.objects.all(),
'posts' : Posts.objects.all().order_by('-c... |
import re
def abbreviate(words):
return ''.join([word[0].upper() for word in re.split('[\s|_|-]+\W?', words)])
|
#coding=utf-8
import re
import requests
from lxml import etree
import lxml.html
import os
import time
import threading
def url_1(n): #定义爬取得页数
urls=[]
for i in range(1,n+1):
url = 'http://www.kzj365.com/category-9-b0-min0-max0-page-'+str(i)+'-default-DESC-pre2.htm... |
#x= 1 #int
#y=2.5 #float
#name = 'John' #str
#is_cool = True #bool
x, y, name, is_cool = (1, 2.5, 'John', True)
a= x+y
x=str(x)
print ('Hello')
print(is_cool, a)
print(type(x))
|
from linked_list import LinkedList as LL
from node import Node
# def reverse_ll(list1):
# """Reverse a singly linked list."""
# current = list1.head
# list2 = LL()
# while current is not None:
# # list2.insert(current)
# list2.head = Node(current.val, list2.head)
# current = cu... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that app bundles are built correctly.
"""
import TestGyp
import os
import sys
if sys.platform == 'darwin':
print "This tes... |
with open("input.txt") as f:
lines = f.readlines()
dict = {}
for line in lines:
if "goes" in line:
line = line.split()
val = int(line[1])
bot = int(line[5])
if bot in dict.keys():
dict[bot].append(val)
else:
dict[bot] = [val]
q = []
for key in di... |
BANK_CSV_CONFIGS = {
"bank1": {
"has_header": True,
"columns_order": ["created_date", "type", "amount", "source", "destination"],
"date_format": "%b %d %Y"
},
"bank2": {
"has_header": True,
"columns_order": ["created_date", "type", "amount", "destination", "source"],
... |
# -*- coding: utf-8 -*-
__author__ = 'rasmus svebestad'
__email__ = 'rasmus.svebestad@nmbu.no'
# Task B
# Importing pytest for the test_empty_list function
import pytest
def median(data):
""""
The function is fetched from the INF200 exercise repository on GitHub
"""
sdata = sorte... |
import numpy as np
import matplotlib.pyplot as plt
from oj.axes import pcolormesh
def plotfaces(x,y,c,faces,slices,mask=None,axes=None,**kwargs):
if 'norm' not in kwargs:
vmin = kwargs.get('vmin',None)
vmax = kwargs.get('vmax',None)
if vmin is None or vmax is None:
cglob = c.tog... |
import sys
import nfldb
import datetime
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell
import json
def cleanTeamNameDK(team):
ret = team.upper()
ret = ret.replace('JAX', 'JAC')
return ret
def cleanPlayerNameDK(name):
ret = name
ret = ret.replace('Jamarcus Nelson', 'J.J. Nelson'... |
def run_minimax (tree_node, minv, maxv, heuristic):
'''Runs a minimax search on the given minimax tree node down to
a depth of d and returns the (score, move). move is in the range
0..6 '''
if (tree_node.isLeaf == True):
return (heuristic(tree_node.board, tree_node.turn), tree_node.lastMove)
if (tree_node.ty... |
s = input()
d = { 'SUN' : 7,
'MON' : 6,
'TUE' : 5,
'WED' : 4,
'THU' : 3,
'FRI' : 2,
'SAT' : 1
}
if s in d.keys():
print(d[s])
|
n = int(raw_input())
boys = [int(x) for x in raw_input().split()]
m = int(raw_input())
girls = [int(x) for x in raw_input().split()]
boys.sort()
girls.sort()
pairs = 0
for i in range(n-1,-1,-1):
boy = boys[i]
for j in range(m-1,-1,-1):
if girls[j]==0:
continue
if abs(boy-girls[j])<=1:
pairs+=1
girls[... |
"""
Fake Company class object
Copyright (c) 2019 Julien Kervizic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.