text stringlengths 38 1.54M |
|---|
import requests, json
# a Python dictionary that will be turned into a JSON object
resourceParams = {
'restype_id': 'http://www.knora.org/ontology/anything#ThingPicture',
'properties': {
},
'label': "Zuerich",
'project_id': 'http://data.knora.org/projects/anything'
}
# the name of the file to be submi... |
#~ f_in = open('B-small-practice.in')
#~ f_out = open('B-small-practice.out', 'w')
#f_in = open('B-large-practice.in')
#f_out = open('B-large-practice.out', 'w')
## The number of test cases
t = int(raw_input()) # read a line with a single integer
for i in xrange(1, t + 1):
#~ n, m = [int(s) for s in r... |
from django.shortcuts import render,redirect
from django.views import generic
from django.urls import reverse_lazy
import datetime
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.contr... |
#!/usr/bin/python
import sys
import os
class TodoCommandParser(object):
def __init__(self, commandLineArgs):
# split the arguments by space and skip the first (command name)
A = commandLineArgs.split()
A = A[1:]
self.command = ''
self.arg1 = ''
self.arg2 = ''
if len(A) < 1:
return
A[0] = A[0].low... |
#!/usr/bin/env python
__VERSION__ = '1.0'
import immlib
import argparse
import immutils
import getopt
import pelib
import pefile
from immutils import *
imm = immlib.Debugger()
"""
Funcitons
"""
def CheckIntersectionJMP(inst):
imm.log("trying to locate intersection jmp")
return "Done"
def CheckPushAdd(inst):
... |
import perceptron
from point import *
from tkinter import *
canvas_width = 700
canvas_height = 700
brain = perceptron.Perceptron(2)
points = []
point_graphique = []
nb_point = 1000
i = 0
while i < nb_point:
new_point = Point(canvas_width,canvas_height)
points.append(new_point)
i += 1
fenetre = Tk()
c... |
#from pyimagesearch.io import HDF5DatasetWriter
import numpy as np
import argparse
from imutils import paths
import cv2
import os
import imutils
import random
def rotate_bound(image, angle):
# grab the dimensions of the image and then determine the
# center
(h, w) = image.shape[:2]
(cX, cY) = (w // 2,... |
def remove(duplicate):
list_ = []
for num in duplicate:
if num not in list_:
list_.append(num)
return list_
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print(remove(duplicate))
|
import numpy as np
import matplotlib.pyplot as plt
import copy
#Define sigmoid activation function
def sigmoid(x, derivative=False):
#activation function and derivative
#x: input
#derivative: boolean. If True will return the derivative
f = 1 / (1 + np.exp(-x))
#derivative
... |
from getpass import getpass
from test_object import Test
class AccountsTest(Test):
username = None
password = None
def __init__(self):
self.username = raw_input("Username: ")
self.password = getpass()
def test_myaccount(self):
try:
self.driver.get("http://myacco... |
# like = open('likeCounter.txt','r').read()
# like = int(like)
# like += 1
# storeLike = str(like)
# openFile = open('likecounter.txt','w')
# openFile.write(storeLike)
# openFile.close()
# like = open('likeCounter.txt','r').read()
# print(like)
#function to increase the like counter...
#1
def likeMe(like... |
from pig import Dice, Player, Game, ComputerPlayer
dice = Dice()
player1 = Player()
player2 = ComputerPlayer()
def test_dice_exists():
new_dice = Dice()
assert type(new_dice) == Dice
def test_dice_equality():
dice1 = Dice()
dice2 = Dice()
assert dice1 == dice2
def test_dice_will_roll_within_par... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
price = models.CharField(max_length=20)
image = models.URLField(max_length=200)
des... |
# Copyright 2021, Google LLC.
#
# 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 to in writing... |
from interfaces.expr import Expr, UnaryOp, BinOp
from parsing.visitor import Visitor
def expr_size(e:Expr) -> int:
""" Counts the number of binary and unary operations. """
class Walker(Visitor):
def __init__(self):
self.size = 0
def visit_binary_op(self, binary_op:BinOp):
... |
# Программ считает сумму товаров и делает скидку 5 % на товар,если его стоимость превышает 1000
price = float(input('Введите цену на товар:'))
cost = 0
while price >= 0:
if price > 1000:
cost = cost + (price - 0.05 * price)
else:
cost = cost + price
price = float(input('Введите цену ... |
import logging
from lncrawl.templates.novelmtl import NovelMTLTemplate
logger = logging.getLogger(__name__)
class WuxiaNHCrawler(NovelMTLTemplate):
base_url = "https://www.wuxianovelhub.com/"
|
import math as math #sqrt
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.naive_bayes import GaussianNB
## Settings ##
DATA_LOCATION = "Iris.csv"
DEPENDENT = "Species"
SKIP_PLOT_GENERATION = True
IGNORE = ["Id", DEPENDENT]
TRAINING_PERCENT = 0.8 # These ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'modificacionDeStockHerramientas.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
... |
from instapy_cli import client
from postObject import post
import json
class agent:
def __init__(self, username: str, password: str):
self.username = username
self.password = password
def upload_to_instagram(self, post):
with client(self.username, self.password) as cli:
... |
from Reader import reader, make_arrays
from visualization import plot_graphics
from scr.algorithms import correlation_function, normalization
if __name__ == '__main__':
data = reader("../data/21022518.txt")
arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10, arr11, arr12 = make_arrays(data)
... |
# Generated by Django 2.0.3 on 2018-03-28 12:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0012_auto_20180328_1523'),
]
operations = [
migrations.AlterField(
model_name='project',
name='status',... |
#MAIN PROGRAM FILE
import numpy as np
from itertools import combinations
#finds the intersection between two lists
def intersectscore(i,j):
return len(set(i).intersection(j))
def v_combiner(pd,id,combinations_of_pairs):
array_of_intersect_score=[]
no_of_pic=id["N"]
pic_array=a=[i for i in range(no... |
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import Polygon
from django.db import transaction
from api.models import Region
class Command(BaseCommand):
help = "update regions with bbox. To run, python manage.py update-region-bbox"
@transaction.atomic
def handle(self, *args, *... |
import os, sys, time
from psychopy import visual, core, data, logging
from .task_base import Task
from ..shared import config
STIMULI_DURATION = 4
BASELINE_BEGIN = 5
BASELINE_END = 5
ISI = 1
IMAGES_FOLDER = "/home/basile/data/projects/task_stimuli/BOLD5000_Stimuli/Scene_Stimuli/Presented_Stimuli/ImageNet"
STIMULI_SI... |
str = "www.tutorialspoint.com"
print ("Min character: " + min(str))
str = "TUTORIALSPOINT"
print ("Min character: " + min(str))
|
import gym
import DQN_model
#from tensegrityEnvironment import *
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines.deepq.policies import LnMlpPolicy, MlpPolicy
from stable_baselines import DQN
# Instantiate and wrap the env
#env = DummyVecEnv([lambda: tensegrityEnvironment])
... |
"""
Core functions to perform clustering
"""
#######################################################################
## Imports
#######################################################################
import numpy as np
import numexpr as ne
import datetime
##############################################################... |
import requests,openpyxl
# 发送请求
def api_func(url_api,data_api):
header = {'X-Lemonban-Media-Type':'lemonban.v2','Content-Type':'application/json'}
response=requests.post(url=url_api,json=data_api,headers=header)
result=response.json()
return result
# 写入数据
def write_result(filename,sheetname,final_resul... |
# Example of python script to use on mongo-converter
def parser_field(field, row=None, configuration=None,
mongo_column=None,
oracleConnection=None,
mongoClient=None,
context=None,
operator=None):
print("Handle field", field, ' o... |
from django.contrib import admin
from .models import CarouselImage, Product
# Register your models here.
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'manufacturer', 'sku',
'tag_list', 'has_sizes', 'price', 'rating')
search_fields = ('name', 'manu... |
from django.test import TestCase
from django.apps import apps
from app.users.apps import UsersConfig
from django.contrib.auth.models import User
class TaskTest(TestCase):
# def setUp(self):
# admin = User.objects.create_user("admin")
# Task.objects.create(title="Task 1", description="Example task"... |
"""Utility functions.
:class EntryList: Various CLI tools relevant to displaying valid query entries.
"""
from data.dataset import valid_entries
class EntryList:
"""Command-line tools that assist with identifying valid entries.
These tools do things like:
- List all valid entries in sorted order, by... |
from collections import defaultdict
with open ('/Users/anthonynguyen/Desktop/Advent-Of-Code-2019/Day 6 - Universal Orbit Map/Orbits.txt') as file:
#with open ('/Users/anthonynguyen/Desktop/Advent-Of-Code-2019/Day 6 - Universal Orbit Map/Test2.txt') as file:
Orbits = file.read().splitlines()
def build_tuple_lis... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Thu May 16 11:41:49 CEST 2013
"""Measures for calibration"""
import math
import numpy
def cllr(negatives, positives):
"""Cost of log likelihood ratio as defined by the Bosaris toolkit
Computes the 'cost of log likelihood ratio' (:math:`C_{llr}`) meas... |
import sqlite3
import csv
def accountExists(username, password):
DB_FILE= "accounts.db"
db = sqlite3.connect(DB_FILE)
c = db.cursor()
command = "SELECT userID, username FROM USERNAMES WHERE username = \"{}\" AND password = \"{}\";".format(username, password)
c.execute(command)
q = c.fetchall()
... |
#PF-Assgn-36
def create_largest_number(number_list):
n = str(number_list[0]) + str(number_list[1]) + str(number_list[2])
n1 = str(number_list[1]) + str(number_list[2]) + str(number_list[0])
n2 = str(number_list[2]) + str(number_list[0]) + str(number_list[1])
n3 = str(number_list[0]) + str(numbe... |
#!/usr/bin/env python3
import requests
from bs4 import BeautifulSoup
import re
import os
"""Gets text of speeches from presidential elections"""
app_url = "http://www.presidency.ucsb.edu/"
def get_available_elections():
"""Gets dict like {election year: election url} for all available elections"""
docs_url... |
from json import loads, dumps
read = open('pelis.json', 'r')
# Forma 1
films = []
title = ''
actors = ''
rating = ''
boxOffice = ''
for i in range(1, 123):
line = read.readline().split(': ')
value = line[0][8:]
if value == '"Title"':
title = line[1][1:-3]
elif value == '"Actors"':
acto... |
import sqlite3
class SqliteRepository(object):
def __init__(self):
self.conn = sqlite3.connect(':memory:')
self._create()
def _create(self):
self.conn.execute('''CREATE TABLE IF NOT EXISTS Person (name text, surname text, phone_number text, email text) ''')
def put(self, name, sur... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-12 23:47
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('galerija', '0010_auto_20170113_0044'),
]
operations = [
migrations.AlterModelOption... |
import os
import signal
import sys
import socket, time
import cv
from PIL import Image
from numpy import array
# This makes sure the path which python uses to find things when using import
# can find all our code.
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname... |
"""
Scintillator
Abstract class for scintillators
"""
from abc import ABCMeta, abstractmethod
from Centella.physical_constants import *
import sys
from Util import *
from Xenon import *
nm = nanometer
mol = mole
micron = micrometer
LXeRefractionIndex =[
[6.4, 1.58587, 0.0964027],
[6.6, 1.61513, 0.508607],
[6.8, 1.6... |
from django import forms
from django.db.models import Count
from dcim.models import Site, Rack, Device, Interface
from extras.forms import CustomFieldForm, CustomFieldBulkEditForm, CustomFieldFilterForm
from tenancy.models import Tenant
from utilities.forms import (
APISelect, BootstrapMixin, BulkImportForm, CSVDa... |
# encoding: utf-8
"""
@project:data_structure_and_algorithm
@author: Jiang Hui
@language:Python 3.7.2 [GCC 7.3.0] :: Anaconda, Inc. on linux
@time: 2019/8/5 19:44
@desc:
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
... |
#!/usr/bin/env python
'''
Oct 10, 2017: Pasi Korhonen, The University of Melbourne
Simplifies running orthoMCL with a wrapper and pre-checks the known
formatting issues with FASTA headers to avoid failure in later stages of the run.
'''
import os, sys, optparse, getpass
from multiprocessing import Process, Pipe
fr... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
img = cv2.imread(r"D:\courses\Computer Vision with OpenCV and Deep Learning\Computer-Vision-with-Python\DATA\internal_external.png",0)
img.shape
plt.imshow(img,cmap="gray")
image,contour,hierarchy = cv2.findContours(img, cv2.RETR_CCOMP,... |
import base
from base import Base
import logging
import sys
sys.path.append('../core/')
from voice import Voice
class Controller:
# arrows
MOVE_FORWARD = 259
MOVE_BACKWARD = 258
TURN_LEFT = 260
TURN_RIGHT = 261
# 'pgup' and 'pgdown'
HEAD_LEFT = 339
HEAD_RIGHT = 338
# q, a, w, s
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 14 15:39:35 2018
@author: Administrator
"""
from urllib import request
import re
# 检验代理服务器,怎么知道当前和Internet连通的
def check_proxy(html):
pattern = re.compile("<title>百度一下,你就知道</title>")
title = re.findall(pattern, html)
if title is None:
ret... |
import numpy as np
A = np.arange(2, 14).reshape((3, 4))
print(A)
print(np.argmin(A))
print(np.argmax(A))
print(np.mean(A))
print(A.mean())
print(np.average(A))
print(np.median(A)) # 中位数
print(np.cumsum(A)) # 逐个累加
print(np.diff(A)) # 差
print(np.nonzero(A)) # 非零的数
A = np.arange(14, 2, -1).reshape((3, 4))
print(A)
prin... |
from spacy.matcher import PhraseMatcher
from spacy.tokens import Doc
from spacy.tokens import Span
from spacy.util import filter_spans
from spacy.language import Language
from text_complexity_analyzer_cm.constants import ACCEPTED_LANGUAGES
emphatics_getter = lambda doc: [doc[span['start']:span['end']]
... |
#try1.py
#함수를 정의
def divide(a,b):
return a/b
# 에러 처리
try:
#함수호출
#result = divide(5,"aa")
#result = divide(5,0)
result = divide(5,2)
except ZeroDivisionError:
print("0으로 나누면 안됩니다")
except TypeError:
print("숫자여야 연산이 됩니다.")
else:
print("결과:{0}".format(result))
finally:
print("무조건 실행")... |
from django.contrib.auth import get_user_model
from django.db import models
User = get_user_model()
class PostList(models.Model):
pass
class PostModify(models.Model):
pass
|
from django.db import models
from benchmark_django_rest_framework.benchmark_model import BenchmarkModel
# Create your models here.
class AppVersions(BenchmarkModel, models.Model):
version = models.IntegerField(primary_key=True)
app_id = models.IntegerField()
created_at = models.DateTimeField(bla... |
#####A program to calculate the one second moving averages and turbulence factors of the velocimetry graphs from testpiv2.py#####
#####If this program is to be used for other arrays, computers, or videos, things that need to change are marked by #*#. #####
import numpy as np
import glob
import pylab
#####make the dict... |
# Generated by Django 3.0.3 on 2020-05-06 00:40
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Accidente',
fields=[
('k_numaccidente', mod... |
from django.db import models
class User(models.Model):
name = models.CharField(max_length=50,
blank=False,
null=False)
role = models.ForeignKey('Role', on_delete=models.CASCADE)
password = models.CharField(max_length=55,
... |
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
import utils.Image_loader as il
import segmentation.threshold as t
import measure.find_countours as fc
img = il.get_sample()
countour = fc.get_contour(img)
polygon = measure.approximate_polygon(countour, 0.8)
print(polygon)
import numpy ... |
from textblob import TextBlob
from textblob import Word
import sys
from similar import get_cosine, text_to_vector
def parse(string):
global verbose
verbose = False
ques = []
sim = []
line = []
print("hi")
try:
txt = TextBlob(string)
for sentence in txt.sentences:
... |
import re
def name(utterance, slot_value, delex=False):
if delex:
if "__NAME__" in utterance:
return "__NAME__"
else:
return "N/A"
pattern = slot_value.replace("The ", "").lower()
if pattern in utterance:
return slot_value
else:
return "N/A... |
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *
import tkinter.font as font
import numpy as np
import serial as sr
import csv
skipfirst = True
root = Tk()
root.title("Welcome to Brage test")
verdi = Entry(root, width=50)
verdi.grid(row=0, co... |
import os
data_prefix_path = '../data/'
model_prefix_path = '../Model/model/'
eval_prefix_path = '../evaltool/'
save_prefix_path = '../save/'
TRAIN_FILE = data_prefix_path + 'nlpcc-iccpol-2016.dbqa.training-data'
TEST_FILE = data_prefix_path + 'nlpcc-iccpol-2016.dbqa.testing-data'
WIKI_EMBEDDING_MATRIX = dat... |
"""
function:以一定传染概率进行多次传播实验
@author: Ethan
"""
import xlrd
import numpy as np
import random
# 0传递节点数和感染概率,及设置初始值
nodeNum = 379
a = 0.09
step = 10
# 1读图
edges = xlrd.open_workbook("F:\lzw\EC\data\data2_netscience_379_914.xlsx")
table = edges.sheets()[0]
nrows = table.nrows
print(nrows)
# 2构建连接矩阵
p = np.zeros((node... |
from typing import Any
from unittest import TestCase
from unittest.mock import patch, MagicMock
import yaml
from github import GithubException
from reconcile.utils.openshift_resource import ResourceInventory
from reconcile.utils.saasherder import SaasHerder
from reconcile.utils.saasherder import TARGET_CONFIG_HASH
f... |
import numpy as np
import math
cpu_speed = 1.0
def leaky_relu(x):
return x if x >= 0 else 0.3*x
class App(object):
def __init__(self, name, candidate_models, alpha=0.05, beta=0.001, acc_min=0, lag_max=0, freeze_model=False):
self.name = name
self.can_models = candidate_models
self.... |
# Copyright 2012 Cloudbase Solutions Srl
#
# 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 ... |
#from django.test import TestCase
# coding=utf-8
# Create your tests here.
from django import forms
from models import Article
import datetime
import codecs
def myDate(date):
dt = datetime.datetime.today()
if date.year == dt.year and date.month == dt.month and date.day == dt.day:
res = "今天"
else:
res = str(d... |
import psutil
from config import logs, database
from domain import repository
log = logs.config_loggin()
def print_cpu_info():
log.info('===================================================================')
log.info('[ CPU Information summary ]')
log.info('========... |
import pandas as pd
data = pd.read_csv(
r'c:\Users\Professional\Documents\GitHub\openedu-answers\6\10input.csv', sep=';', encoding="windows-1251")
prices = []
for i in range(len(data)):
for j in range(1, data.shape[1]):
prices.append(data.iloc[i, j])
print(min(prices))
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('adm', '0008_auto_20150827_0858'),
]
operations = [
migrations.AlterField(
model_name='ofertatec',
na... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__a... |
from django.conf.urls import url
from . import views
app_name = 'order_app'
urlpatterns = [
url(r'^$', views.OrderListView.as_view(), name='list'),
url(r'^(?P<pk>\d+)/$', views.OrderDetailView.as_view(), name='detail'),
url(r'^create/$', views.OrderCreateView.as_view(), name='create'),
url(r'update/(?P... |
#!/usr/bin/env python
# enable debugging
import cgitb
cgitb.enable()
import cgi
from Db.Order import Order
from Db.OrderSearch import OrderSearch
#print "Content-Type: text/plain\r\n\r\n"
# Gather url paramters
form = cgi.FieldStorage()
sAction = form.getvalue('action')
if sAction == 'create' or sAction == 'edit' ... |
from PyQt5.QtWidgets import QFileDialog
from PyQt5 import QtCore
import os
from pathlib import Path
def LoadParamTemplate(self):
'''
ask user to select a template file to fill everything with presaved parameters
'''
directory=os.path.join(str(Path(os.path.abspath(__file__)).parent.parent... |
import pyttsx3
# initialize the engine
engine = pyttsx3.init()
def speak(words):
# set the voice and the rate to your wish
voices = engine.getProperty('voices')
female_voice_id = voices[1].id
voice_rate = 145
# set the properties that you like
engine.setProperty('voice', female_voice_id)
engine.setProperty(... |
'''OpenGL extension OES.primitive_bounding_box
This module customises the behaviour of the
OpenGL.raw.GLES2.OES.primitive_bounding_box to provide a more
Python-friendly API
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/OES/primitive_bounding_box.txt
'''
from OpenG... |
# coding: utf-8
# In[58]:
with open('mutants.in') as f:
data = f.read().split('\n')
N = int(data[0])
if N is 0:
mutants = []
else:
mutants = [int(x) for x in data[1].split(' ')]
t = int(data[2])
colors = [int(x) for x in data[3].split(' ')]
# In[59]:
def binsearch_first(arr... |
from django import forms
class login_client_form(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput, max_length=100)
|
import re
from collections import defaultdict
from typing import List, Dict
from app.application.models import User
EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
def validate_email_format(email: str) -> (bool, str):
if not EMAIL_REGEX.match(email):
return False, 'Invalid Email format.'
return True... |
name = str(input("Привет, как тебя зовут? "))
print ("Приятно познакомиться ", name)
question_1 = int(input(name + " сколько тебе лет?"))
|
from flask_testing import TestCase
from flask import url_for
from app import app
class TestBase(TestCase):
def create_app(self):
return app
class TestResponse(TestBase):
def test_service3(self):
response = self.client.get(url_for("pick"))
self.assertIn(response.json, range(1,224)) |
import os, datetime
from werkzeug.utils import secure_filename
from flask import Flask, request, jsonify, render_template, send_from_directory
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import J... |
### DO NOT REMOVE THIS
from typing import List
### DO NOT REMOVE THIS
class Solution:
def optimalDivision(self, nums: List[int]) -> str:
if len(nums)==1:
return "{}".format(nums[0])
elif len(nums)==2:
return "{0}/{1}".format(nums[0],nums[1])
res=""
res+=str(nu... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
import tensorflow as tf
def tf_expdec(t, t0, t1, v0, v1):
"""
Return `v0` until `e` reaches `e0`, then exponentially decay
to `v1` when `e` reaches `e1` and return `v1` thereafter.
Copyright (C) 2018 Lucas Beyer - http://lucasb.eyer.be =)
"""
return tf.train.piecewise_constant(
t, boun... |
from collections import defaultdict
from itertools import product
class Solution:
def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
blocks = defaultdict(list)
for x in allowed:
blocks[x[:2]].append(x[-1])
def explore(s):
if len(s) == 2: return s in... |
print('ABC'.encode('ascii'))
print('中文'.encode('utf-8'))
print(b'ABC'.decode('ascii'))
print(b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8',errors='ignore'))
len('jhfdsjkfkskk')#1111111111111111111111111111111
len('ghjhgjkhgjkbhjkl') |
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time
class BrowserInteraction():
def test(self):
binary = FirefoxBinary("C:\Program Files (x86)\Mozil... |
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
arr = [-1 for _ in range(71)]
res = [0] * len(temperatures)
for i in range(len(temperatures)-1,-1,-1):
t = temperatures[i]
... |
from typing import Iterable, List
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
class WaveNetLayer(nn.Module):
def __init__(
self,
num_channels: int,
kernel_size: int,
dilation: int,
drop: float = 0.25,
leaky: bool = Fa... |
def dfs(val):
if val not in elems:
return 0
else:
return
def find(x, parents):
while parents[x] != x:
x = parents[x]
return x
def union(x, y)
def main(nums):
distinctelems = set(nums)
g = {x: x+1 for x in nums if x+1 in distinctelems}
parents = {}
for el in n... |
from django.db import models
# Create your models here.
class Post(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
content = models.TextField()
author = models.CharField(max_length=255)
# views = models.IntegerField(default=0)
slug = models.Cha... |
"""change update to use timestamp
Revision ID: d0fd292e452
Revises: 1617b96530fc
Create Date: 2016-01-24 17:31:53.319131
"""
# revision identifiers, used by Alembic.
revision = 'd0fd292e452'
down_revision = '1617b96530fc'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def up... |
# Copyright 2020-2023 OpenDR European Project
#
# 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 agree... |
from django.db import models
from django.db.models.signals import pre_save
from django.urls import reverse
# Create your models here.
from ecommerce.utils import unique_slug_generator
class ProductManager(models.Manager):
def get_by_id(self,id):
qs=self.get_queryset().filter(id=id)
if qs.count () == 1:... |
import sys
def convert_color(l):
term_reset = '\x1b[0m'
html_end_balise = "</span>"
for col, int in color_dict.items():
l = l.replace(f'\x1b[1;{int}m', f'<span style="color:{col};font-weight:bold;">')
l = l.replace(term_reset, html_end_balise)
return l
if __name__ == '__main__':
col... |
from entities.account import Account
from daos.account_dao import AccountDAO
from unittest import TestCase
from daos.account_dao_local import AccountDaoLocal
from exceptions.resource_not_found import ResourceNotFound
from daos.account_dao_postgres import AccountDaoPostgres
from entities.customer import Customer
from d... |
import numpy as np
class UnionFind:
"""
Union-Find data structure.
"""
_size = 0
# Массив родителей элементов в лесу.
# Если родитель равен элементу, то элемент — корень дерева.
_parent = []
# Глубина узла в дереве.
# Используется для балансировки дерева.
_ra... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/9/21 上午10:32
# @Author : jlinka
# @File : complex_search.py
import pandas as pd
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import PCA
from sklear... |
# -*- coding: utf-8 -*-
# Sample script which demonstrates how to work with custom DEM in maperipy.
# The script downloads a DEM tile of a small part of Alps from http://www.viewfinderpanoramas.org/.
# It then generates a hillshading using this DEM tile.
# Author: Igor Brejc
# License: public domain
from ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.