text stringlengths 38 1.54M |
|---|
# [Bisect-Lower-Bound, Classic]
# https://leetcode.com/problems/find-k-th-smallest-pair-distance/
# 719. Find K-th Smallest Pair Distance
# https://www.youtube.com/watch?v=WHfljqX61Y8&t=1180s
# Given an integer array, return the k-th smallest distance among all the
# pairs. The distance of a pair (A, B) is defined as... |
import json
import pyrebase
from helpers import find
import time
import re
class Etl:
def __init__(self, data_path=None, config_path=None):
if data_path == None:
self.data_path = ""
if config_path == None:
config_path = "../"
# with open(data_path+"data.json") as ... |
import sys
if(len(sys.argv) < 2) or (len(sys.argv) > 2):
print('Incorrect argument count')
fp = open('counters.txt','r')
raw = fp.readlines()
fp.close()
counters = []
for line in raw:
counters.append(int(line.strip()))
currentCounter = counters[0]
usedCounter = sys.argv[1]
fp = open('counters.txt','w')
fp.write... |
# This code has to be added to __init__.py in folder .../devices/sensor
class Power():
def __family__(self):
return "Power"
def __getWatt__(self):
raise NotImplementedError
@api("Power", 0)
@request("GET", "sensor/power/*")
@response(contentType=M_JSON)
def powerWildcard(sel... |
from lesson_package import utils
def sing():
return 'fdklgoirhkshj'
def cry():
return utils.say_twice('fkoguoujnsbwrg') |
import numpy as np
from tfsnippet.dataflows import DataMapper
from tfsnippet.utils import generate_random_seed
__all__ = ['BaseSampler', 'BernoulliSampler', 'UniformNoiseSampler']
class BaseSampler(DataMapper):
"""Base class for samplers."""
def sample(self, x):
"""
Sample array according t... |
#coding=utf-8
#1.导入selenium库
from selenium import webdriver
#2.设置启动所需浏览器
br=webdriver.Chrome()
#3.打开目标网页
br.get("https://www.baidu.com")
#通过id进行定位
# br.find_element_by_id("kw").send_keys("55开")
#通过name定位
# br.find_element_by_name("wd").send_keys("美国大选")
#通过class定位
# br.find_element_by_class_name("s_ipt").se... |
from app import app, db
import pandas as pd
import sqlalchemy as sa
from uszipcode import ZipcodeSearchEngine
import numpy as np
import datetime
from sklearn import preprocessing
import xml.etree.ElementTree as ET
#to check if the db is empty
def is_db_empty():
con = sa.create_engine(app.config['SQLALCHEMY_DATABAS... |
import torch.nn as nn
import torch.nn.functional as F
class NetworkNvidia(nn.Module):
"""NVIDIA model used in the paper."""
def __init__(self):
"""Initialize NVIDIA model.
NVIDIA model used
Image normalization to avoid saturation and make gradients work better.
Convol... |
"""Utilities for stitching south east asia domains
Example Use:
stitch_and_save(year=2017, month=1,
input_pattern="wrfout_d0{domain}_{year}-{month}*",
out_pattern="{year}/{month}/", overlap=15, n_domains=4,
max_levels=10)
This will combine 4 domains... |
calls = 0
def tracer(func):
def wrapper(*args, **kwargs):
global calls
calls += 1
print(f"call {calls} to {func.__name__}")
return func(*args, **kwargs)
# return wrapper()
return wrapper
@tracer
def spam(a, b, c): # same as : spam = tracer(spam)
print(f"{a + b + c} ins... |
def dot_product(vec1,vec2):
sum = 0
for num in range(len(vec1)):
sum += vec1[num] * vec2[num]
return sum
print(dot_product([1,1],[1,1]))
print(dot_product([1, 2], [1, 4]))
print(dot_product([1, 2, 1], [1, 4, 3]))
|
from django.http import HttpResponse, Http404,HttpResponseRedirect
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404,HttpResponseRedirect
from .forms import NewPostForm,ProfileForm,CommentForm,UserForm
from .models import... |
# vim:tw=50
"""Numbers
There are several numeric types built into Python,
including integers (types |int| and |long|),
floating point numbers (type |float|), and complex
numbers (type |complex|).
10 # This is an 'int'
10.5 # This is a 'float'
6 + 3.2j # This is a 'complex'
The interactive Python ... |
# coding=utf-8
from datetime import datetime
from random import randint
from sqlalchemy.exc import IntegrityError
from faker import Faker
from . import db
from .models import User, Post, Comment, Tag
fake = Faker(locale='zh-CN')
def users(count=100):
i = 0
while i < count:
u = User(email=fake.email(),
... |
from sys import stderr, exit, argv
from flask import Flask, jsonify, request, session, escape
app = Flask(__name__, static_url_path='/static')
@app.route('/feedback', methods=['POST'])
def store_feedback() :
post = request.get_json()
print >> stderr, post
with open('INTERACTION_DATA.json', 'a') as f :
... |
# -*- coding: utf-8 -*-
import cv2
import os
from matplotlib import pyplot as plt
from PIL import Image, ImageEnhance, ImageFilter
import pytesseract
from PIL import ImageFont, ImageDraw
import numpy as np
video_src = 'D:/PROJECTS/Python/HUMAN COUNT/dataset/VID_20191029_185101.mp4'
video_src = 'E:/PROJECT ALL/ka... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# Generated by Django 3.2.3 on 2021-10-13 13:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Sam', '0012_asset_expences_income_liabilities'),
]
operations = [
migrations.CreateModel(
name='Cash',
fields=[
... |
import os
from flask import Flask, session, render_template, request, flash, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess secure key'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# setup SQLAlchemy
basedir = os.path.abspath(o... |
import requests
def get_url_status(url):
con = requests.get(url)
return con.status_code
def run():
url_list = ["http://www.baidu.com", "http://www.163.com"]
for url in url_list:
status = get_url_status(url)
if status == 200:
print("{} 正常".format(url))
else:
... |
import torch.optim as optim
import torchvision
import torch
from torch.autograd import Variable
import numpy as np
from torch.nn import functional as F
import dataset
import helpers
import models
from config import *
# assert(file_name == 'triplet' or file_name == 'bigbottle' or file_name == 'tripletpro')
writer, save... |
# first line: 12
@memory.cache
def detrend(rasterclass):
print("\n Detrending \n")
#perform detrending by applying a gaussian filter with a std of 200m, and detrend
trend = gaussian_filter(rasterclass.raster,sigma=200)
rasterclass.raster -= trend
rasterclass.detrend_ = True
|
from django.db import models
from simple_history.models import HistoricalRecords
import pandas as pd
class Table(models.Model):
id = models.AutoField(primary_key=True)
col_1 = models.CharField(max_length=250, blank=True, null=True, verbose_name="№")
col_2 = models.CharField(max_length=250, blank=True, null... |
n = int(input())
x = [int(i) for i in input().split(' ')][::-1]
p = [0] * n
d = [0] * (n + 1)
longest_subs = 0
for i in range(n):
lo = 1
hi = longest_subs
# binary search for longest subs able to hold curr elem
while lo <= hi:
mid = (lo + hi) // 2
if x[d[mid]] <= x[i]:
... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
from .source import SourcePardot
__all__ = ["SourcePardot"]
|
liste_caracteres_bloques = ["1", "2", "3", "5", "6", "i", "j", "k", "l", "u", "v"]
liste_caracteres_fleche = ["w", "x", "y", "z"]
liste_caracteres_maison = []
coordonnees_interieur_maison = []
coordonnees_porte_maison = []
maison_shop = False
maison_grotte = False
niveau_monstres = 1
fond_ecran_combat = "imagesCombat/f... |
import sys
import oracledb
oracledb.version = "8.3.0"
sys.modules["cx_Oracle"] = oracledb
import cx_Oracle
import urllib3
urllib3.disable_warnings()
from .base import *
from logging.config import dictConfig
DEBUG = True # Always run in debug mode locally
# Dummy secret key value for testing and local usage
SECRET... |
from os import getenv
from pymongo import MongoClient
# Default database name to use
DEFAULT_DATABASE = getenv("SMART_SCHOOL_DEFAULT_DB", "SmartSchool")
class DBClient:
def __init__(self, connection):
"""
Initializing database with given mongodb connection string.
"""
self.client ... |
from keras.datasets import mnist
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
print(X_train[1])
print(Y_test[1])
print(X_train.shape) # (60000,28,28)
print(X_test.shape) # (10000,28,28)
print(Y_train.shape) # (60000,)
print(Y_test.shape) # (10000,)
from keras.utils import np_utils
from keras.models impo... |
"""策略工厂,根绝配置文件或者运行参数初始化一只股票的策略"""
from singleton import singleton
from pc_parity_strategy import PcParityStrategy
@singleton
class StrategyFactory:
def __init__(self):
pass
def create(self):
"""根据股票创建股票的策略"""
return PcParityStrategy()
|
__author__ = 'grant'
a = 10
if a - 10 == 0:
print('a is ten')
if True:
print('tis true')
if 1:
print('its a one')
if 't':
print('the non-empty is treated as true')
if a / 3 == 0:
print('variable a is probably 3')
else:
print('variable a is something else')
weather = 'rainy'
if weather ==... |
def find_max(a):
n = len(a)
max = 0
for i in range(1, n):
if a[i] > a[max]:
max = i
return max
def sort(a):
result = []
while a:
max = find_max(a)
value = a.pop(max)
result.append(value)
return result
d = [2, 4, 5, 1, 3]
print(sort(d))
|
#!/usr/bin/env python
nx, ny, nz = 4, 5, 6
for idx in xrange(nx*ny*nz):
i = idx/(ny*nz)
j = idx/nz
k = idx%nz
j2 = (idx - i*ny*nz)/nz
k2 = idx - i*ny*nz - j2*nz
print i,j,k,'\t',j2,k2
|
import metar
import matplotlib.dates as mdates
import datetime as dt
stations = [('KDLS', 'The Dalles', 'OR'),
('KHRI', 'Hermiston', 'OR'),
('KPSC', 'Pasco', 'WA')]
startdate = dt.datetime(1980,1,1)
enddate = dt.datetime(2012,5,27)
timestep = dt.timedelta(days=1)
for station in stations:
o... |
import re
from unicodedata import normalize
from photosandtext2 import app, db
from photosandtext2.models.photo import *
from photosandtext2.models.user import *
import datetime
ALLOWED_EXTENSIONS = app.config["ALLOWED_EXTENSIONS"]
def init_env():
"""
Used to initialize the environment. (Need to import photo ... |
from time import sleep, time
from config import config
class Session:
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
# Wild Apricot uses "APIKEY" as the client ID
CLIENT_ID = 'APIKEY'
def __init__(self):
client = self.BackendApplicationCli... |
import random
SIX_HANDS = []
PLAYER_LIST = []
if len(PLAYER_LIST) > 6:
PLAYER_LIST.pop()
class Deck(object):
def __init__(self,):
self.two_hands = []
self.current = ['2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', '10c', 'Jc', 'Qc', 'Kc', 'Ac',
'2s', '3s', '4s', '5s'... |
#!/usr/bin env python
# -*- coding: utf-8 -*-
#Project Neutrino
#Por Cleiton Lima <cleitonlima@fedoraproject.org>
#This file is part of Neutrino Project.
# Neutrino is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Softw... |
import dash
from dash.dependencies import Output, Input, State
import dash_core_components as dcc
import dash_html_components as html
import plotly
import random
import plotly.graph_objs as go
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(external_stylesheets=external_s... |
# Заповнюємо масив випадковоми числами
import random
def generuvaty_masyv( n, min, max ):
m = []
for _ in range(0,n):
m.append(random.randint(min,max))
return m
N = 20
masyv = generuvaty_masyv( N, 1, 20 )
print("Заданий масив:", masyv)
# Задача (викладка з легендою)
# В черзі на завантаженн... |
from django.conf.urls import patterns, include, url
from views import GLogListView, GLogDetailView, GLogCreateView, GLogUpdateView
urlpatterns = patterns('',
url(r'^$', GLogListView.as_view(), name='glog-list'),
url(r'^create/$', GLogCreateView.as_view(), name='glog-create'),
url(r'^edit/(?P<id>\d+)/$', G... |
from django.core.management.base import BaseCommand, CommandError
import sisyphus.models
import sisyphus.analytics
import django.http
import json
import time
import re
class Command(BaseCommand):
args = "<file_to_load file_to_load ...>"
help = "Load analytics from Google Analytics Top Content report in CSV fo... |
#!/usr/bin/python3
# safely-remove: A command-line tool to eject external data devices.
#
# (c) 2020 Alicia Boya Garcia
#
# 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, ... |
# -*- coding: utf-8 -*-
# Copyright (C) 2008 Frederik M.J. Vestre
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of condi... |
from django.shortcuts import render
from rest_framework import generics
from core.models import Comunidad, Evento,AgentesPatorales,Solicitud
from .serializers import ComunidadSerializer, EventoSerializer,AgenteSerializer,SolicitudSerializer
# Create your views here.
class ComunidadLista(generics.ListCreateAPIView):
... |
from __future__ import unicode_literals
import logging
from mopidy import backend
from mopidy.models import SearchResult
logger = logging.getLogger(__name__)
class SubsonicLibraryProvider(backend.LibraryProvider):
def __init__(self, *args, **kwargs):
super(SubsonicLibraryProvider, self).__init__(*args... |
class Solution(object):
def __init__(self):
self.k = 0
'''
这种方法超时了,让求第k个,没必要把所有的排列都求出来
'''
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
nums = []
for i in xrange(1, n + 1):
nums.a... |
from os.path import join as pjoin
# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
_version_major = 0
_version_minor = 1
_version_micro = '' # use '' for first of series, number for 1 and above
_version_extra = 'dev'
# _version_extra = '' # Uncomment this for full releases
# Construct fu... |
b = 7
def verdubbelB():
b = b + b
verdubbelB()
print(b)
import time
print(time.strftime(("%H:%M:%S")))
def f(y):
return 2*y + 1
print(f(3)+g(3))
def g(x):
return 5 + x + 10 |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... |
from airflow import DAG
from datetime import datetime, timedelta
from airflow.providers.amazon.aws.operators.glue import AwsGlueJobOperator
default_args = {
"owner": "airflow-user",
"start_date": datetime.today(),
"depends_on_past": False,
"email_on_failure": False,
"email_on_retry": False,
"email": "<your-email... |
# Copyright 2015 Google Inc. 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. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
import sys
sys.stdin = open('input.txt')
def preorder(node):
if node == '.':
return
print(node, end='')
preorder(graph[node][0])
preorder(graph[node][1])
def inorder(node):
if node == '.':
return
inorder(graph[node][0])
print(node, end='')
inorder(graph[node][1])
de... |
import boto3
import uuid
import sys
s3 = boto3.resource('s3')
bucket_name = "image-pattern"
bucket = s3.Bucket(bucket_name)
for obj in bucket.objects.all():
print(obj.key)
response = s3.get_bucket_location(
Bucket=bucket_name
)
# LIST AVAILABLE BUCKETS
for bucket in s3.buckets.all():
print "Bucket... |
# Generated by Django 2.0.9 on 2018-11-10 15:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crm', '0017_auto_20181110_1456'),
]
operations = [
migrations.RemoveField(
model_name='project',
name='duration',
... |
# -*- coding: utf-8 -*-
import sys
from dill import dill
from MyAPI.InderScience import InderScience
from MyAPI.MyBs import MyBs
from MyAPI.MySele import MySele
from MyAPI.ScienceDirect import ScienceDirect
from MyAPI.Tandfonline import Tandfonline
tand = {
40: 4,
41: 4,
42: 4,
43: 4,
44: 4,
4... |
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from notifications.signals import notify
from django.shortcuts import reverse
# 注册的时候,发送通知到刚注册的账号
@receiver(post_save, sender=User)
def send_user_save_notifications(sender, instance, **kwarg... |
# 90-degree turnning matrix func
def rotate_a_matrix_by_90_degree(a):
n = len(a)
m = len(a[0])
result = [[0]*m for _ in range(n)]
for i in range(n):
for j in range(m):
result[j][n-1-i] = a[i][j]
return result
# a = [[1, 2], [3, 4]]
# print(rotate_a_matrix_by_90_degree(a))
def check(length, new_lock):
f... |
from django.core.management.base import BaseCommand
from ktapp import models
class Command(BaseCommand):
help = "Merge users"
def add_arguments(self, parser):
parser.add_argument("source_user_id", type=int)
parser.add_argument("target_user_id", type=int)
def handle(self, *args, **option... |
#!/usr/bin/python
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from tensorflow.python.platform import gfile
def reformat(dataset, labels):
if use_cnn:
dataset = dataset.reshape((-1, image_sizeX, image_sizeY, num_channels)).astype(np.f... |
'''
Тест позволяет проверить работу функции, сымитировать набор данных на виртуальной клавиатуре пользователем.
Данные берутся из внешенго файла -- data_OGZ_plane.tsv.
'''
# Инициализация полей ввода
x_field = "{container=':mainWidget.qstw_mode_QStackedWidget' name='qle_ogz_x' type='QLineEdit' visible='1'}"
y_field = ... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread("lena.bmp", cv2.IMREAD_GRAYSCALE)
cv2.imwrite("1_original_lena.bmp", image)
plt.hist(image.reshape(image.size), bins = range(256))
plt.savefig("1_original_histogram.png")
devide3 = image / 3
cv2.imwrite("2_devide3_lena.bmp", devide3)
pl... |
#!/usr/bin/python3
"""find the number that occure only one time in an array"""
def solution(A):
for i in A:
if A.count(i) == 1:
return i
#This algorithm is correct by it will take O(n²) to pass, which is not so optimal
#another solution is:
def solution(A):
for i in range(len(A)):
A... |
#!/usr/bin/env python3
import re
import sys
import json
import base64
import ipaddress
def decode_address(address):
hex_ip, hex_port = address.split(':')
ip_join, ipv6 = (':', True) if len(hex_ip) == 32 else ('.', False)
if ipv6:
ipv6_string = ":".join([hex_ip[i:i + 4] for i in range(0, 32, 4)])
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from ana_bsec import log
import torch,copy,math,numpy
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class NN_EXP(nn.Module):
def __init__(self):
super(NN_EXP,self).__init__()
self.fc1=nn.Linear(1,4)
self.fc2=... |
from PyQt5.QtCore import pyqtSignal, QObject
from DataSocket import TCPReceiveSocket
import time
# a client socket
class QDataSocket(QObject):
reconnecting = pyqtSignal()
new_data = pyqtSignal(tuple)
def __init__(self, tcp_port, tcp_ip='localhost'):
super().__init__()
self.socket = TCPRe... |
from numpy import *
from ConvNet import *
import time
import struct
import os
#mnist has a training set of 60,000 examples, and a test set of 10,000 examples.
#log檔作用:紀錄檔案(logfile)是一個記錄了發生在執行中的作業系統或其他軟體中的事件的檔案
#
def train_net(train_covnet, logfile, cycle, learn_rate, case_num = -1) :
# Read data
# Change it t... |
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('login/', views.loginPage , name='login'),
path('logout/', views.logoutUser , name='logout'),
path('register/',views.registerUser , name='register'),
path(''... |
#!/usr/bin/env python
import os
import sys
from recipes.examples import Examples
from recipes.apport import Apport
from recipes.packages import Packages
from recipes.bashrc import Bashrc
from recipes.node import Node
from recipes.gedit import Gedit
from recipes.git import Git
from recipes.fstab import Fstab
from recip... |
#包含min函数的栈
class stack():
def __init__(self):
self._item = []
self._min = []
def pop(self):
if self._item:
self._min.pop()
return self._item.pop()
else:
print("stack is empty!")
def push(self,item):
self._item.append(item)
... |
import random
def intercalar_iguais(v1, v2, vf):
x = 0
for i in range(len(v1)):
vf[x] = v1[i]
x += 1
vf[x] = v2[i]
x += 1
return vf
def contem(v, qtd, e):
for i in range(qtd):
if v[i] == e:
return True
return False
def gerar(v1, v2):
qtd_v1... |
import fractions
from functools import reduce
def gcd_list(numbers):
return reduce(fractions.gcd, numbers)
n, x0 = map(int, input().split())
x = list(map(int,input().split()))
x.append(x0)
x.sort()
xdiff = []
tmp = x[0]
for xs in x:
if xs - tmp == 0: continue
xdiff.append(xs-tmp)
print(gcd_list(xdiff)) |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 19 17:28:13 2021
@author: gawe
"""
import numpy as _np
mu0 = 4.0*_np.pi*1e-7 # [H/m], approximate permeability of free space
cc = 299792458 # [m/s], defined speed of light, weird flex: 3e8 m/s is fine
eps0 = 1.0/(mu0*(cc**2.0)) # [F/m], permittiv... |
from django.db import models
class Ornanization(models.Model):
name = models.CharField(max_length=20)
department = models.CharField(max_length=40)
email = models.EmailField(max_length=50)
duty = models.CharField(max_length=20)
cell_phone = models.IntegerField(max_length=11)
plane_number = models.IntegerField(ma... |
# Generated by Django 2.0 on 2018-01-19 09:30
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Machine',
fields=[
... |
import numpy as np
import sys
# have a quick look of a file containing numpy array that you saved
file = sys.argv[1]
array = np.load(file)
print(array)
print('shape:', np.shape(array))
|
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
print ("Calculator v2")
print("______________________")
num1 = float(input("Enter a number: "))
operand = input("+, -, *, / : ")
num2 = fl... |
import os
from flask import Flask
# create_app 是一个应用工厂函数
def create_app(test_config=None):
# 用于创建和配置Flask应用
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY="dev",
DATABASE=os.path.join(app.instance_path, "flask.sqlite"), # 这里定义了数据库的路径和名称
)
... |
# Détecte si un mot est un palindrome
un_mot = "kayak"
nb_lettres = len(un_mot)
est_palindrome = True
for i in range(0, nb_lettres): # Rq: pour optimiser la boucle, on peut parcourir uniquement la moitié du mot
if not un_mot[i] == un_mot[nb_lettres - 1 - i]:
est_palindrome = False
break
print(f... |
import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
from zipline.api import order_target, record, symbol,set_commission, commission
from zipline.algorithm import TradingAlgorithm
start = datetime.datetime(2016, 1 ,2)
end = datetime.datetime(2016, 1, 31)
data = web.DataReader("000660.K... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import numpy as np
from IPython import embed
class ReLU:
def forward(self, x):
self.grad_mask = x < 0
return np.maximum(x, 0)
def backward(self, grad_input):
grad_input[self.grad_mask] = 0
return grad_input
def test_ReLU(input, gra... |
def input_number():
x = 10
try:
y = int(input('請輸入數字:'))
z = x / y
except ZeroDivisionError as e:
print('分母不可 = 0, 請重新輸入~', e)
input_number()
except ValueError as e:
print('輸入資料錯誤, 請重新輸入~', e)
input_number()
except Exception as e:
print("發生了一個我... |
import numpy as np
class Utils:
def Sigmoid(self, z):
return (1/(1+np.exp(-z)))
def CrossEntropy(self, a, y):
return np.mean(y * np.log(a) + (1-y) * np.log(1-a))
def DistEuclidean(self, dato, dato1):
x = 0
for i in range(len(dato1.columns)-1):
x += (((dato.ilo... |
from __future__ import annotations
from soda.sodacl.check_cfg import CheckCfg
from soda.sodacl.location import Location
class GroupByCheckCfg(CheckCfg):
def __init__(
self,
source_header: str,
source_line: str,
source_configurations: dict | None,
location: Location,
... |
import os
import psycopg2
DEBUG = False
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = 'https://recipe-ingredient-catalog.herokuapp.com/static/'
A... |
from include.data_load import DataSets
from include.regression import Regression
import numpy as np
def main() -> None:
datasets_obj = DataSets()
datasets_obj.load_boston_housing_dataset()
train_data, train_target = datasets_obj.get_train_data()
test_data, test_target = datasets_obj.get_test_data()
... |
# Generated by Django 2.1.3 on 2019-01-10 10:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0002_auto_20190110_1055'),
]
operations = [
migrations.RemoveField(
model_name='game',
name='id',
)... |
from django.db import models
class Button(models.Model):
value = models.BooleanField(default = True)
mapped_io = models.CharField(max_length=25, default = 'a')
def __str__(self):
return "Digital: " + str(self.mapped_io)
class Slider(models.Model):
value = models.IntegerField(default = 0)
... |
#863. All Nodes Distance K in Binary Tree
#We are given a binary tree (with root node root), a target node, and an integer value K.
#Return a list of the values of all nodes that have a distance K from the target node.
#The answer can be returned in any order.
#Example 1:
#Input: root = [3,5,1,6,2,0,8,null,null... |
import h5py, sys
for fname in sys.argv[1:]:
print 'loading '+fname+'...'
with h5py.File(fname, 'a') as h5f:
for key in h5f.keys():
if key in ['scstiffness_rho', 'scstiffness_rho3d', 'scstiffness_rho3dinterlayer',
'josephsonexchange', 'josephsonexchange_j3d', 'scstiffn... |
from django.contrib import admin
from . models import NetVisCache
admin.site.register(NetVisCache)
|
import csv,sys
from get_relationship import GetRelationship
from add_relationship import AddRelationship
import globals
def read_csv(filepath):
data = []
with open(filepath) as f:
reader=csv.reader(f)
# next(reader, None)
for row in reader:
if row:
data.append(row)
return data
def request_tree(reque... |
"""Cancer data classification
Classifying the Wisconsin cancer data from UCI repository
into benign and malignant classes with k Nearest Neighbors
"""
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# File : cancer_knn.py
# find whether cancer is malignant or benign using kNN
import time
import warnings
... |
# defnination function
def name():
name = input('Enter name: ') # variable to Receive the input
if len(name) <= 10: # if condetion to check len of name
return name
else:
return name[0] + str(len(name[1:-2])) + name[-1]
# ptint fun
print(name())
|
"""
step1: choose a starting point x0 and set k = 0
step2: determine a descent direction d_k
step3: determine step size by line search, choose step size tau_k > 0
step4: update x[k + 1] = x[k] + tau_k * d_k, k += 1
repeat until stopping criterion is satisfied
Linear approximation:
Suppose that f is differentiable and ... |
length = float(input("Enter length of rectangle :"))
width = float(input("Enter width of rectangle :"))
PerimeterOfRectangle = 2*(length+width)
AreaOfRectangle = length*width
print ("Perimeter of Rectangle: {}".format(PerimeterOfRectangle))
print("Area of Rectangle: {}".format(AreaOfRectangle)) |
__author__ = 'ole'
from core.plugin import Plugin
# This plugin is necessary to keep the connection alive.
class Pong(Plugin):
def on_ping(self, message):
self.logger.info("PONG {0}".format(message.content))
self.send("PONG {0}\r\n".format(message.content).encode())
|
#def char_frequency(str1):
str1=raw_input("enter the string")
dict1 = {}
for n in str1:
if n in dict1:
dict1[n] += 1
else:
dict1[n] = 1
print dict1
#print(char_frequency('google.com'))
|
from evaluation import fit_and_score
import random
def _query(item):
""" Default query. """
return True
def _accept(pred):
""" Default acceptor. """
return True
class Sampler(object):
def __init__(self, pipeline, batch_size=30, query=_query,
key=None, accept=_accept):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.