text stringlengths 38 1.54M |
|---|
# -*- coding: UTF-8 -*-
#!/usr/bin/env python
#--------------------------------
# Name: dicoshapes.py
# Purpose: make an Excel file about shapefiles present in a databse files
# structured, gathering basic informations. The output file could
# be used as a database dictionary.
... |
# Задание 3
def my_func(number1, number2, number3):
numbers = [number1, number2, number3]
max1 = max(numbers)
numbers.remove(max1)
max2 = max(numbers)
return max1 + max2
numbers = [1, 2, 10]
print(f"Из списка {numbers} сумма наибольших двух аргументов = " +
f"{my_func(numbers[0], numbers[1],... |
Administrador = u'Administrador'
Atendente = u'Atendente'
Gerente = u'Gerente'
Vendedor = u'Vendedor'
|
"""
SocksiPy + urllib.request handler
This module provides a Handler which you can use with urllib.request
to allow it to tunnel your connection through a socks.sockssocket socket,
with out monkey patching the original socket...
"""
import base64
import urllib.request
from . import socks
try:
from requests.pack... |
#!/usr/bin/env python
import operator
exit_code_output = {0: 'OK',
1: 'WARNING',
2: 'CRITICAL',
3: 'UNKNOWN',
}
exit_code = 0
# Get threshold
data = {}
outputs = []
output = ""
perf_data = ""
operator_name = 'ge'
thyallperfs = allperfs(se... |
import nltk
nltk.download('stopwords')
from sklearn.feature_extraction.text import CountVectorizer
from nltk import tokenize
from nltk.stem.snowball import SnowballStemmer
from collections import Counter
import numpy as np
class Featurizer(object):
def __init__(self):
self.stemmer = SnowballStemmer('en... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
from setuptools import setup
# Package meta-data.
NAME = 'get-pybrowser'
DESCRIPTION = 'Selenium based, user friendly Browser Automation API'
URL = 'https://git... |
class Node(object):
def __init__(self, data):
self.data = data ##
self.next = None
class LinkedList(object):
def __init__(self):
self.size = 0
self.head = None
def insertstart(self, data):
newNode = Node(data) ##
self.size += 1
if not se... |
# Generated by Django 3.0 on 2019-12-10 02:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plotapp', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='inputfile',
name='status',
fi... |
from blcscan import BLCScan1
from device.nct import NCT
from epics import caput, caget
import time
import threading
import math
import pandas as pd
class ScanRC(BLCScan1):
'''
Scan for rocking curve
DATE: 2018-5
m: motor, Motor object
d: detectors, BL09BNCT object
step > 0
'''
def __... |
#!/usr/bin/env python3
######################################################################
## Author: Carl Schaefer, Smithsonian Institution Archives
######################################################################
message_groups = {}
######################################################################
de... |
# -- coding: utf-8 --
from sys import argv
script,filename = argv
txt = open(filename)
txt.close()
print ("Here is your file %r:" % filename)
print (txt.read())
print ("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print (txt_again.read())
#remember to close the file when you a... |
import csv
import os
import random
import sys
import time
import pygame
screen_width, screen_height = 960, 640
pygame.init()
pygame.display.set_caption('Level Editor')
myfont = pygame.font.SysFont('Comic Sans MS', 30)
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
class ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-27 00:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
import csv
import time
from kafka import KafkaProducer
# 实例化一个KafkaProducer示例,用于向Kafka投递消息
producer = KafkaProducer(bootstrap_servers='localhost:9092')
# 打开数据文件
csvfile = open("../data/log_result.csv", "r",encoding='utf-8')
# 生成一个可用于读取csv文件的reader
reader = csv.reader(csvfile)
for line in reader:
sex = line[10] #... |
import gui as pychgui
import game as gm
import neuralNetwork as nn
import pickle as pck
def main():
fname = "trainedNetwork.pkl"
try:
networkfile = open(fname, 'rb')
network = pck.load( networkfile )
except Exception as exc:
print (str(exc))
neurons = [5*64,int(0.66*5*64),1... |
from flask import request, jsonify
from flask.views import MethodView
from src.DataTables.Tables import RegionalCapacities, GlobalCapacities, Offers
import json
import decimal
from itertools import groupby
from operator import itemgetter
from collections import defaultdict
# helper method to encode decimals as string... |
miastoA = input("Miasto startowe: ")
miastoB = input("Miasto końcowe: ")
dystans = int(input(f"Podaj odległość między {miastoA}-{miastoB}: "))
cena = float(input("Podaj cenę paliwa: "))
spalanie = float(input("Podaj średnie spalanie na 100km: "))
koszt = float(dystans/100 * spalanie * cena)
print()
koszt = round(koszt,... |
from selenium import webdriver
from time import sleep
try:
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.baidu.com')
# tree.xpath('//*[@id="kw"]/@maxlength')
# 获取指定属性的值
# maxlength = driver.find_element_by_xpath('//*[@id="kw"]').get_attribute('maxlength')
# p... |
#
# [224] Basic Calculator
#
# https://leetcode.com/problems/basic-calculator/description/
#
# algorithms
# Hard (28.53%)
# Total Accepted: 64K
# Total Submissions: 224.4K
# Testcase Example: '"1 + 1"'
#
# Implement a basic calculator to evaluate a simple expression string.
#
# The expression string may contain op... |
import os
import time
import atexit
import socket
import pathlib
import logging
import tempfile
import unittest
import subprocess
from contextlib import contextmanager
from typing import Optional
import docker
LOGGER = logging.getLogger(__package__)
logging.basicConfig(level=logging.DEBUG)
DOCKER_IMAGE = "mariadb:1... |
import datetime
from collections import defaultdict, namedtuple
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.db import transaction
from api.models.CompliancePeriod import CompliancePeriod
from api.models.CreditTradeHistory import CreditTradeHistory
from api.models.Cred... |
"""
*****************************************************************************
FILE: Game.py
AUTHOR: Cal Reynolds
PARTNER: n/a
ASSIGNMENT: Project 6
DATE: 4/7/2017
DESCRIPTION: Scrabble!
*****************************************************************************
"""
import random
from cs110graphics import *
clas... |
# Copyright 2015 Metaswitch Networks
#
# 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 w... |
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from datetime import date, timedelta
from app import app
import controllers
from views import SidebarView
import os
DEBUG=True if 'DEBUG' in os.environ and os.environ['DEBUG'] == 'true' else False
C... |
import os
import difflib
import math
from logwriter.TemplateBuilder import TemplateBuilder
class LogContext(object):
def __init__(self, outpath, templates_dir=None):
self.outpath = outpath
if not templates_dir:
self.templates = TemplateBuilder(os.path.join(os.path.dirname(__file__), "t... |
#!/usr/bin/python3
# by William Hofferbert
# Midi Shutdown Server
# creates a virtual midi device via amidithru,
# then listens for a control change message
# on that device, running a shutdown command
# via os.system when it gets that command.
import time
import mido
import os
import re
# midi device naming
name = "... |
import time
import numpy as np
import sys
import random
import os
from os import listdir
from os.path import isfile, join
import re
import json
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.cluster import DBSCAN
from sklearn.cluster import dbscan
from sklearn.feature_extraction.text import CountVe... |
import pandas as pd
import numpy as np
import sys
if len(sys.argv) < 2:
print("Run as: python/python3 <file_name.py> <absolute_path_of_test_file>")
sys.exit(0)
csv_path = 'AdmissionDataset/data.csv'#raw_input("Enter path to input CSV file: ")
dataset = pd.read_csv(csv_path)
dataset.drop(dataset.columns[[0]],... |
#!/usr/bin/env python
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from os import path
import multiprocessing
from bes.testing.unit_test import unit_test
from bes.git.git_repo_operation_options import git_repo_operation_options
from bes.git.git_temp_repo import git_temp_... |
# Generated by Django 3.2.7 on 2021-10-11 08:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0011_auto_20211011_1358'),
]
operations = [
migrations.AlterField(
model_name='student',
name='SeatCategory',... |
from flask import Blueprint, jsonify
from tabulation.controllers.user_controller import UserController
from tabulation.controllers.event_controller import EventController
from tabulation.controllers.criteria_controller import CriteriaController
from tabulation.controllers.judge_controller import JudgeController
from ta... |
# -*- coding: utf-8 -*-
from django.http import HttpResponse, Http404, HttpResponseForbidden
from django.shortcuts import render, redirect
from ..models import *
from .. import utils
from .. import exceptions
import json
def downloadFile(request, fileSequence = -1):
pass
def uploadFile(request):
if request... |
## medium
## tree, dfs
## 48ms, beats 100%
## 14.9mb beats 100%
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: 'TreeNode') -> 'bool':
def dfs(node,... |
try:
from collections.abc import Iterable
except ImportError:
Iterable = (tuple, list)
from gym.vector.async_vector_env import AsyncVectorEnv
from gym.vector.vector_env import VectorEnv
import gym
from gym import logger
from gym.vector.utils import concatenate, create_empty_array
import numpy as np
from copy ... |
import pdb
import torch
import torch.nn as nn
class SST(nn.Module):
"""
Container module with 1D convolutions to generate proposals
"""
def __init__(self, opt):
super(SST, self).__init__()
self.scores = torch.nn.Linear(opt.hidden_dim, opt.K)
# Saving arguments
... |
# coding=utf-8
##############################################################################################
# @file:acfuncomments.py
# @author:Merlin.W.OUYANG
# @date:2016/11/20
# @note:AcFun评论获取
# @modify
# @author:Jiangsiwei
# @date:2017/01/12
# @note:网站域名更新升级,原地址:http://www.acfun.tv/ 升级后地址:http://www.acfun.cn/
# ... |
#! /usr/bin/env python
import pygame
from random import uniform
black = 0, 0, 0
white = 255, 255, 255
green = 0, 80, 0
game_end = False
screen_size = 800, 600
game_screen = pygame.display.set_mode(screen_size)
game_rect_screen = game_screen.get_rect()
game_time = pygame.time.Clock()
pygame.display.set_ca... |
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from . import views
app_name='home'
urlpatterns = [
path('', views.index, name='index'),
url(r'^timeline/(?P<id>[\w-]+)/$', views.timetable, name="schedule"),
]
# (?P<file_name>[\w.]{0,256})/$ |
'''
Please create an empty file (manually as you normally create
Python files) and name it requests.py . Make sure the file has that name exactly.
Then just paste the following code in the file (manually):
Executing the script will throw an error. Please fix that error
so that you get the expected output and expla... |
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class GlobusAuthorizer(object):
"""
A ``GlobusAuthorizer`` is a very simple object which generates valid
Authorization headers.
It may also have handling for responses that indicate that it has provided
an invalid Authorization header.
"""... |
import pygame
import random as r
UNIT = 70 # size of individual square in pixels
COUNT_W = 10 # width in units
COUNT_H = 10 # height in units
FONT_SIZE = 20
FRAMERATE = 60 # frames per second
SPEED = 20 # number of frames between movement (greater than 0)
TAIL_GROWTH = 5 # increase in tail length for each food eaten
... |
import sys
_module = sys.modules[__name__]
del sys
cifar = _module
datasets = _module
cifar = _module
folder = _module
LinearAverage = _module
NCA = _module
lib = _module
normalize = _module
utils = _module
main = _module
models = _module
resnet = _module
resnet_cifar = _module
test = _module
from _paritybench_helpers... |
import unittest
from datacategoryvisitors.processeddatabuilders.ProcessedDataBuilderBase import ProcessedDataBuilderBase
class ProcessedDataBuilderBaseTest (unittest.TestCase):
def setUp(self) -> None:
self._dummyProcessedDataBuilder = DummyProcessedDataBuilder()
def testGetProcessedData(sel... |
from .main import *
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bivver_local',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '3306'
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.bac... |
from typer.testing import CliRunner
from rasalit.__main__ import app
from rasalit import __version__
runner = CliRunner()
def test_app():
result = runner.invoke(app, ["--help"])
assert result.exit_code == 0
def test_version():
result = runner.invoke(app, ["version"])
assert __version__ in result.s... |
import tstables as tstab
import pandas as pd
import tables as tb
import datetime as dt
class TsDesc(tb.IsDescription):
timestamp = tb.Int64Col(pos=0)
Last = tb.Float64Col(pos=1)
path = 'C:/Users/ivanm/Documents/Currency/AUDNZD/'
# data = pd.read_csv('C:/ticks.csv', index_col=0, parse_dates=True, decimal=','... |
import csv
def csv_parse(file_name):
data = []
rows = []
with open("./"+file_name) as csvDataFile:
csv_reader = csv.reader(csvDataFile)
for row in csv_reader:
data.append(row)
fields = data[0]
for row in data[1:]:
new_row = [0] * 25
for i in range(25):
... |
from sklearn import ensemble
from sklearn.feature_extraction import DictVectorizer
from sklearn import metrics
from import_data import get_data, get_oversampled_data
from timeit import default_timer as timer
import tensorflow as tf
import numpy as np
from scipy import stats
def load_data():
vec = DictVec... |
import serial
import subprocess as sp
import time
gps = serial.Serial("/dev/ttyUSB0", baudrate=4800, timeout=5)
satellites = {}
def sat_data(gps):
global satellites
try:
line = str(gps.readline(), 'ASCII')
data = line.split(',')
if data[0] == '$GPGSV':
checksum_data = data... |
# encoding: utf-8
# module PyQt4.QtGui
# from C:\Python27\lib\site-packages\PyQt4\QtGui.pyd
# by generator 1.145
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
from QAbstractScrollArea import QAbstractScrollArea
class QTextEdit(QAbstractScrollArea):
"""
QTextEdit(QWidget parent=None)... |
#jug problem
#euclid's theorem
x=int(input("enter the size of first jug "))
y=int(input("enter the size of second jug "))
a=0
b=0
needed=int(input("enter the remaining size needed"))
if needed==x:
print("the solution is 1 gallon of jug 1 and 0 gallons of jug 2" )
elif needed==y:
print("the solution ... |
from flask import Flask
from flask_restful import Api
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from hashlib import sha256
from controllers import userController, mainControllers
from database import db
from models import Organization, User
app = Flask(__name__)
app.config['SQLALCHEMY_DATABAS... |
from django.conf.urls import url
from api.views_set.classroom import *
urlpatterns = [
url(r'^create/', create),
url(r'^update/', update),
url(r'^close/', close),
url(r'^get_list/', get_list),
url(r'^search/', search),
url(r'^send_request/', send_request_to_join),
url(r'^approve_request/', ... |
"""
======================COPYRIGHT/LICENSE START==========================
write.py: code for CCPN data model and code generation framework
Copyright (C) 2012 (CCPN Project)
=======================================================================
This library is free software; you can redistribute it and/or
modif... |
from HTMLTestRunner import HTMLTestRunner
import unittest
import os
import time
# os.path.abspath(__file__) #返回当前文件的绝对路径
# os.path.dirname(os.path.abspath(__file__)) #返回当前文件的目录
# print(os.path.dirname(os.path.abspath(__file__)))
#######################################################################################... |
# Copyright 2015, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
import fire
import json
from sultan.api import Sultan
import os.path
TEMP_PATH = "temp/"
class EnvDeploy:
def down(self, name, skip_db=False):
self.app(name, True)
self.ups_service(name, True)
if skip_db is False:
self.execute_db_task(name=name, delete=True)
self.... |
import pandas as pd
import numpy as np
from sklearn import model_selection
from sklearn.model_selection import KFold
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from utilities import train_model
from sklearn.ensemble import RandomForestClassifier
#Read LIWC output file
df = pd.read_csv("./R... |
from collections import OrderedDict
from functools import wraps
from itertools import chain
from graphql.core.type import GraphQLArgument
from ...utils import ProxySnakeDict, to_camel_case
from .base import ArgumentType, BaseType, OrderedType
class Argument(OrderedType):
def __init__(self, type, description=No... |
import media
import fresh_tomatoes
# first instance of class Movie
justice_league = media.Movie("Justice League",
"A group of superheroes unite",
"https://upload.wikimedia.org/wikipedia/en/3/31/Justice_League_film_poster.jpg", # NOQA
... |
import jinja2
from xhtml2pdf import pisa
fileSystem = jinja2.FileSystemLoader(searchpath="./PrintFunction/templates")
env = jinja2.Environment(loader=fileSystem)
template = env.get_template("familleProduitTemplate.html")
def render(data, name=None):
resultat = template.render(codefamilleproduit=data[0], nomfamillep... |
import numpy as np
import astropy.units as au
from astropy.units import Quantity
import pylab as plt
from born_rime.fourier import fourier, inv_fourier, fft_freqs
from born_rime.greens import two_dim_g, two_dim_G
from born_rime.potentials import partial_blockage, pad_with_absorbing_boundary_conditions
def main():
... |
# -*- coding: utf-8 -*-
bytecode_map = {
"move": "M", # M指令集
"move/from16": "M",
"move/16": "M",
"move-wide": "M",
"move-wide/from16": "M",
"move-wide/16": "M",
"move-object": "M",
"move-object/from16": "M",
"move-object/16": "M",
"move-result": "M",
"move-result-wide": "M",
"move-result-object": "M",
"move-exceptio... |
import socket, json, config, sys, os, time
class Api:
def __init__(self, db, sync):
self.db = db
self.sync = sync
while True:
try:
self.s = socket.socket()
self.s.bind((config.ip, config.port))
self.s.listen(5)
break
except:
print "Could not start socke... |
from keras.models import Model, Sequential
from keras.layers import Input, Flatten, Dense, Dropout
from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D
from keras import backend as K
def VGG16(input_dim=224, input_depth=3, output_dim=1000, include_top=True):
# Determine proper input shape
if K.image_di... |
from pathlib import Path
import inspect
from datetime import datetime
import re
import xmltodict
import json
import shutil
from utils import loadurlmap, add_syndication, get_content, add_to_listmap, urlmap_to_mdfile, clean_string
from utils import MDSearcher, URLResolver, PostBuilder, CommentBuilder
urlmap = loadurlma... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/", methods=["GET"])
def index():
names = {'name' : 'Anthony'}
return render_template("layout.html", names=names, language='Python', lang=False, framework='Flask')
if __name__ == "__main__":
app.run(debug=True) |
from flask import Blueprint, render_template, request, jsonify
pie_blueprint = Blueprint('pie', __name__, url_prefix='/pie')
@pie_blueprint.route('/', methods=("GET", "POST"))
def index():
ingredient = ['apples', 'strawberries', 'hampster']
if request.method =='GET':
return jsonify({'pie ingredient'... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 31 18:10:37 2016
@author: saisugeethkamineni
"""
# Leave Automation Project #
'''
start
'''
import time
import math
from sys import exit as close
import numpy as np
import matplotlib.pyplot as plt
database = open('leave automation.csv', 'r')
readDatabase = database.read(... |
import tensorflow as tf
import numpy as np
from utils import utils
class Model(object):
def __init__(self, token_emb_mat, glove_emb_mat, token_dict_size, char_dict_size, token_max_length, model_params, scope):
self.scope = scope
self.global_step = tf.get_variable('global_step', shape=[], d... |
__author__ = 'trunghieu11'
def dfs(html, begin, end, type):
if html == "":
return ""
for i in range(3):
if html.find2(begin[i]) == 0:
html = html[len(begin[i]):]
return type[i] + "([" + dfs(html, begin, end, type)
if html.find2("<img />") == 0:
html = html[l... |
from threading import Thread, Lock
n = 10
def func(lock):
global n
lock.acquire()
n -= 1
lock.release()
lock = Lock()
for i in range(10):
Thread(target=func, args=(lock, )).start()
print(n) |
import pygame
import time
import random
pygame.init()
# 颜色设置
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 显示吃准
dis_width = 600
dis_height = 400
# 显示模式
dis = pygame.display.set_mode((dis_width, dis_height))
# 设置标题
pygame.display.se... |
from itertools import product
from random import randint, seed
from sse_validate_utf16le_proof import bitmask
# This is a copy from sse_validate_utf16le_proof.py with
# adjusted the mask for the 16-bit base
def mask(words):
L = bitmask(words, 'L')
H = bitmask(words, 'H')
V = (~(L | H)) & 0xffff
a = L... |
#?description=Use the specialized IDexUnit interface to replace all dex strings 'text/html' by 'foobar'.
#?shortcut=
from com.pnfsoftware.jeb.client.api import IScript
from com.pnfsoftware.jeb.core.units.code import ICodeUnit, ICodeItem
from com.pnfsoftware.jeb.core.units.code.android import IDexUnit
from com.pnfsoftwa... |
# David Powis-Dow CS 101:Python
# 2016-10-02 v0.1
# Chapter 2 Exercise 5: Compound Interest Calculation with Years Input
# user_response = int(input("Please enter the number of years the money be compounded for?: "))
# population = int(input("Population of Toronto? "))
# var_t = (user_response) # Number ... |
import unittest
from puzzles.day2.intcode import process_intcode, find_initial_inputs
class TestIntcode(unittest.TestCase):
def test_process_gravity_assist(self):
self.assertEqual(process_intcode([1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]), [3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50])
self.ass... |
""" Views for the base application """
from django.shortcuts import render_to_response
from django.template import RequestContext
def home(request):
""" Default view for the root """
return render_to_response('base/home.html',
context_instance=RequestContext(request))
def documentation(request):
... |
import math
datea = input("Enter first date using format (dd/mm/yyyy):")
s1=datea.split('/')
print(s1[:])
d1 = eval(s1[0])
m1 = eval(s1[1])
y1 = eval(s1[2])
c1 = 365*y1+ math.floor(y1/4)- math.floor(y1/100)+ math.floor(y1/400)+ math.floor((306*m1+5)/10)+(d1-1)
dateb = input("Enter second date using format (dd/mm/yyyy... |
import time
def time_this(num_runs=10):
def wrapp(func):
def time_test():
print("Старт теста")
time_compare = 0
for i in range(num_runs):
t0 = time.time()
func()
t1 = time.time()
time_compare += (... |
# Generated by Django 3.1.5 on 2021-02-11 03:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shop', '0009_slidercontent'),
]
operations = [
migrations.CreateModel(
name='CartProduct',
... |
from django.test import TestCase
from users.models import User
from .fake_transactions import transactions_data
from ..exceptions import InvalidReport
from ..reports.summary_by_account import SummaryByAccount
from ..use_cases import CreateTransactions
class SummaryByAccountTestCase(TestCase):
def setUp(self):
... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class ProductManager(models.Manager):
def for_user(self, user):
return self.filter(created_by=user)
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.IntegerField... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'calendar.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObject... |
from itertools import permutations
N,M,R=map(int,input().split())
*r,=map(int,input().split())
inf=float("inf")
d=[[inf]*N for _ in range(N)]
for _ in range(M):
A,B,C=map(int,input().split())
d[A-1][B-1]=C
d[B-1][A-1]=C
for k in range(N):
for i in range(N):
for j in range(N):
d[i]... |
from django.shortcuts import render
from django.http import HttpResponse
from .models import Score
def index(request):
return render(request, 'bwvsearchweb/index.html')
def search(request):
chords = request.POST['chords']
hits = Score.objects.with_pitched_chords(chords)
return render(request, 'bwvsea... |
# def form_new_list(new_list):
# return [str(element) for element in new_list if type(element) == int or type(element) == float]
#
# new_list = [1,2,3,4,5,6,9.8,8.2,9.9,1.3,'sumit','saurav',[1,2,'sumit']]
#
# print(form_new_list(new_list))
print({i:('odd' if(i%2!=0) else 'even') for i in range(1,11)})
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-;
# TODO: 缓存,选择性输出
import os
os.chdir(os.path.split(os.path.realpath(__file__))[0])
def match(text, name):
for x in text.splitlines():
x = x.split(':')
if name == x[0]:
return x[1]
if os.path.exists("main.ini"):
with open("main.ini", ... |
# -*- coding: utf-8 -*-
import pandas as pd
nodes = pd.read_csv("data/iterim/nodes.csv")
nodes_with_communities = pd.read_csv("data/iterim/nodes_with_communities.csv")
test = pd.read_csv("data/iterim/test.csv")
# creating test feature hash
test["hash"] = pd.Series(test.loc[:, ["X1", "X2", "X3", "X4", "X5", "X6"]].v... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("DQM")
# DQM service
process.load("DQMServices.Core.DQMStore_cfi")
# MessageLogger
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 1000
#process.MessageLogger.cerr.INFO.limit = 1000
import FWCore.... |
class Solution:
def areSentencesSimilar(self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool:
"""
sentence1 = ["great","acting","skills", "fine", "fine", "great"]
sentence2 = ["fine","drama","talent", "great", "good"]
... |
from newio.sync import Event
class Future:
def __init__(self):
self._event = Event()
self._result = None
self._exception = None
async def set_result(self, result):
self._result = result
await self._event.set()
async def set_exception(self, exception):
sel... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
import heapq
import operator
import numpy
import datetime
import time
def factorization(train, r, g, au, ts, bias=False, svd=True, svd_pp=False, steps=25, gamma=0.04, gamma1=0.04 , gamma2=0.04,
slow_rate=0.93, Lambda... |
# to determine the "determinant" of matrix
from numpy import linalg as LA
import numpy as np
a = np.array([[1, 0], [0, 1]])
print(a)
print(LA.det(a)) # similar ar np.linalg.det(a)
|
"""
墙壁上挂着一个圆形的飞镖靶。现在请你蒙着眼睛向靶上投掷飞镖。
投掷到墙上的飞镖用二维平面上的点坐标数组表示。飞镖靶的半径为 r 。
请返回能够落在 任意 半径为 r 的圆形靶内或靶上的最大飞镖数。
示例 1:
输入:points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2
输出:4
解释:如果圆形的飞镖靶的圆心为 (0,0) ,半径为 2 ,所有的飞镖都落在靶上,此时落在靶上的飞镖数最大,值为 4 。
示例 2:
输入:points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5
输出:5
解释:如果圆形的飞镖靶的圆心为 (0,4) ,半径... |
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import pyspark
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from pyspark.sql.functions import *
from pyspark.sql import *
from pyspark.sql.types import *
from pyspark.... |
########## ELASTICSEARCH CONFIGURATION
from elasticsearch import Elasticsearch, RequestsHttpConnection
from urlparse import urlparse
import os
ES_URL = os.environ.get('SEARCHBOX_URL') or 'http://127.0.0.1:9200/'
if not urlparse(ES_URL).port:
ES_URL += ':80'
ES_CLIENT = Elasticsearch([ES_URL], connection_class=Req... |
/*
Nome: El Dorado
ID: 1645
Resposta: Accepted
Linguagem: Python 3 (Python 3.4.3) [+1s]
Tempo: 0.688s
Tamanho: 735 Bytes
Submissao: 05/06/16 20:03:38
*/
# -*- coding: utf-8 -*-
import functools
def cache(func):
cache.cache = dict()
def cached(*args):
if args not in cache.cache:
result ... |
import os
import json
from datetime import datetime
from flask import Flask
from flask import render_template, url_for, request, jsonify
from flask import send_from_directory
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = ['JPEG', 'JPG', 'PNG', 'GIF']
a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.