text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
"""
@version: v1.0
@author = pdu
@license: pdu Licence
@contact: 1090416@qq.com
@project = jobplus
@file: app.py
@create_time = 2020/8/44:28 下午
"""
from flask import Flask
from jobplus.config import configs
from flask_migrate import Migrate
from flask_login import LoginMan... |
class KMP:
#def __init__(self):
def patternFunc(self, p):
i = 0
j = 1
arr = [0]*(len(p))
while j < len(p):
if p[i] == p[j]:
i = i+1
arr[j] = i
j = j+1
else:
if i != 0:
i = arr[i-1]
else:
arr[j]=0
j = j+1
return arr
#while j != len(p):
# while j < len(p) an... |
"""Interfact Segregation Principle
Favor many client-specific interfaces over a single general-purpose one.
"""
from abc import ABC, abstractmethod
class Printer(ABC):
@abstractmethod
def print(self):
pass
class Scanner(ABC):
@abstractmethod
def scan(self):
pass
class Fax(ABC):
... |
# Algorithms in Python: Recursion -- Find Uppercase Letter in String
input1 = 'LucidDream'
input2 = 'lucidDream'
input3 = 'lUCidDream'
def find_upper(str):
for i in range(len(str)):
if str[i].isupper():
return str[i]
return None
def find_upper_recur(str, i=0):
if str[i].isupper():
... |
#!python
import sys
from optparse import OptionParser
from collections import deque
import math
import operator
import itertools
import re
usage = 'usage: %prog input'
parser = OptionParser(usage=usage)
(options, args) = parser.parse_args()
if args:
if args[0] == '-':
f = sys.stdin
else:
f = ope... |
import sys
sys.path.append("/usr/local/anaconda3/lib/python3.6/site-packages")
import numpy
from numpy import sin, linspace
def f(x):
return sin(x)
x = linspace(0, 7, 71)
y = sin(x)
delta_x = x[1] - x[0]
from matplotlib import pyplot as plt
plt.grid()
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Funkcija $sin... |
import os
apk_filename = 'launcher-future-skin-blue'
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path ... |
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django.dispatch import receiver
from django.template import loader
from django.db.models.signals import post_save
from django.core.mail import send_mail
from django.utils.encoding import smart_str, smart_unicode
# Create your mo... |
# This Python file uses the following encoding: utf-8
import os
from pathlib import Path
import sys
import re
from PySide2.QtGui import QGuiApplication, QIcon
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QThread, Slot, Signal
class Standart(QThread):
def __init__(self):
... |
class Solution:
def thirdMax(self, nums):
"""
给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
---
输入: [3, 2, 1]
输出: 1
解释: 第三大的数是 1.
:type nums: List[int]
:rtype: int
"""
if len(set(nums)) < 3:
return max(nums)
return sorted(list(set(nums)), reverse=True)[2]
a = Solution()
# [2, 2, 3, ... |
from pymongo import MongoClient
from bson import ObjectId
import pymongo
client = MongoClient("mongodb+srv://bdiaz071:0312651pw@bookstore-2edyi.mongodb.net/test")
database = client["test"]
db_c = database["clients"]
print("Database connected...")
# Inserts data into the collection that you want
def insert_data(data):... |
"""Surrogate (simulated) tasks created using the Profet algorithm.
For a detailed description of Profet, see original paper at https://arxiv.org/abs/1905.12982 or
source code at https://github.com/EmuKit/emukit/tree/main/emukit/examples/profet
Klein, Aaron, Zhenwen Dai, Frank Hutter, Neil Lawrence, and Javier Gonzale... |
# -*- coding:utf-8 -*-
from flask import Blueprint, request, jsonify, render_template
from flask.views import MethodView
from bson import ObjectId
from ..helpers import html, cn_time_now
from .. import app, db, cache
from . import render_json, register_api, ck_auth, get_user
bp = Blueprint('user', __name__)
@bp.rou... |
import requests
from bs4 import BeautifulSoup
# 타겟 URL을 읽어서 HTML를 받아오고,
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://www.genie.co.kr/chart/top200?ditc=D&ymd=20200403&hh=23&rtm=N&pg=1',headers=... |
t = input()
while(t > 0):
t -= 1
n = input()
k=2;h=0;i=2
while(1):
h += 1
if(n <= i):
print h
break;
k += 1
i += k |
#!/home/xavi/Udacity/fyyur/fyyur-env/bin/python3
# EASY-INSTALL-ENTRY-SCRIPT: 'ipdb==0.13.8','console_scripts','ipdb3'
__requires__ = 'ipdb==0.13.8'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.e... |
from pyspark import SparkConf, SparkContext
classScore = sc.parallelize({('class1', 70),('class2', 75),('class2', 40),('class3', 10),('class1', 90),('class2', 100)})
classScoreGroup = classScore.groupByKey().map(lambda classObject:(classObject[0], list(classObject[1])))
classScoreGroup.collect()
|
from selenium import webdriver
class TestHogwards():
def setup(self):
pass
def teardown(self):
pass
def test_hogwarts(self):
pass
|
#pytorch批处理裁剪图像
# coding: utf-8
from PIL import Image
import os
import os.path
import numpy as np
import cv2
# 指明被遍历的文件夹
# rootdir = "D:\\zl\\GraduationThesis\\data\\new_data\\label"
# 裁剪单偏光、融合、标签图
# for parent, dirnames, filenames in os.walk(rootdir): # 遍历每一张图片
# for filename in filenames:
# (name, ext... |
class Solution(object):
def dfs(self, k, n, rg, path, paths):
if n == 0 and k == 0:
paths.append(path)
if len(rg) == 0 or rg[0] > n or k == 0 or n == 0:
return
self.dfs(k-1,n-rg[0],rg[1:],path+[rg[0]],paths)
self.dfs(k,n,rg[1:],path,paths)
def combinationS... |
"""
Copyright (c) 2017, Sandia National Labs and SunSpec Alliance
All rights reserved.
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 cond... |
# coding: utf-8
from django.shortcuts import render, redirect, get_object_or_404
from usuarios.models import Usuario
from usuarios.forms import UsuarioForm
def listarU(request):
users = Usuario.objects.all()
return render(request, 'usuarios/lista.html', {'usuarios':users})
def nuevoU(request):
if request.method ==... |
import cv2
from config import cascadePath
import math
class Detector:
def __init__(self):
self.face_cascade = cv2.CascadeClassifier(cascadePath+'haarcascade_frontalface_default.xml')
self.eye_cascade = cv2.CascadeClassifier(cascadePath+'haarcascade_eye.xml')
self.faceBB = None
self.eyesBB = {'left':None, 'ri... |
from fcis.functions.psroi_pooling_2d import psroi_pooling_2d # NOQA
from fcis.functions.psroi_pooling_2d import PSROIPooling2D # NOQA
|
from . import common as cmn
import numpy as np
import fast_matched_filter as fmf
from obspy.core import UTCDateTime as udt
from .config import cfg
from IPython.core.debugger import Tracer
debug_here = Tracer()
def find_multiplets(templates_mat, moveouts_mat, data, template_ids, net,
threshold_typ... |
# Machine Learning Online Class - Exercise 2: Logistic Regression
#
# Instructions
# ------------
#
# This file contains code that helps you get started on the logistic
# regression exercise. You will need to complete the following functions
# in this exericse:
#
# sigmoid.m
# costFunction.m
# predict.... |
import numpy as np
import pandas as pd
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
train.drop('Username',axis=1,inplace=True)
test.drop('Username',axis=1,inplace=True)
test_labels = test.iloc[:,0].values
test.drop('ID',axis=1,inplace=True)
train.drop('ID',axis=1,inplace=True)
from s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 4 15:33:22 2020
eager模式介绍
@author: tinghai
"""
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
#%matplotlib inline
# !pip install tensorflow==2.0.0-beta1
# !pip install tensorflow-gpu==2.0.0-beta0
... |
from django.db import models
# Create your models here.
class Comment(models.Model):
video_id = models.CharField(max_length=100, blank=True, null=True)
like = models.IntegerField(default=0)
dislike = models.IntegerField(default=0)
comment = models.CharField(max_length=100) |
from geowatchutil.buffer.base import GeoWatchBuffer
from geowatchutil.codec.factory import build_codec
class GeoWatchStore(object):
# Public
backend = None
key = None # or path
which = None
which_index = None
# Private
_buffer = None # Used for temporarily caching messages locally befo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from inputReader import *
from processo import Processo
from collections import deque
class RoundRobin(object):
"""Classe que representa um algoritmo de escalonamento Round Robin. Esse algoritmo
define uma fatia de tempo para a execução de cada processo. Caso um process... |
import math
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import pandas as pd
# Data location relative to execution location (modify if needed)
folder = "data"
rawSamples = np.load(folder + "/Chain A - th... |
from hugh.simulat_probe.report_data.data_temp.origin_data_base import OriginDataBase
class _OriginTypeOne(OriginDataBase):
@property
def connect_delay(self):
"""
连接时延, 单位毫秒
:return:
"""
return None
@property
def byte_delay(self):
"""
首字节时延, 单位毫... |
"""
This code is the entry-point
"""
import json
from typing import TextIO
import click
from .http import assault
from .stats import Results
@click.command()
@click.option("--requests", "-r", default=500, help="Number of requests")
@click.option("--concurrency", "-c", default=1, help="Number of concurrent requests")
... |
def selectLast(set_number, activities):
#set of completed activities
completed = []
#Sorting
#print("sorting:")
#Sorting by start time, since we're looking for last to start
activities.sort(reverse = True, key = lambda x: x[1])
last_start = activities[0]
current_activity = last... |
import sys
N, S = map(int, sys.stdin.readline().split())
num = list(map(int, sys.stdin.readline().split()))
cnt = 0
def backtracking(i, result, num, N, S):
if i == N:
if result == S:
global cnt
cnt += 1
return
# not selected
backtracking(i+1, result, num, N, S)... |
from io import open
archivoTexto = open('archivo.txt', 'r+') # Lectura y escritura r+
# print(archivoTexto.readlines())
listaTexto = archivoTexto.readlines()
listaTexto[1] = "Esta linea ha sido incluida desde el exterior \n"
archivoTexto.seek(0)
archivoTexto.writelines(listaTexto)
archivoTexto.close()
# print(... |
class Tree:
def __init__(self, key, parent_key):
self.key = key
self.parent_key = parent_key
self.parent = False
if parent_key == -1:
self.parent = True
def preorder_traversal(tree):
if tree.leaf:
return
print(tree.key)
preorder_traversal(tree)
|
from src.Character_Detection.train_characters import save_character_recognition_model
from src.Plate_Detection.get_plate import get_plate
from src.Character_Detection.image_processing import get_characters
import glob
from src.Character_Detection.predict_character import predict_character
# TODO: IMPORTANT uncomment... |
#list 10 nama teman
list_teman = ['nando','arfan','irfan','hidan','jefri','narista','issa','harry','ivan','vika']
print("list teman:" ,list_teman)
print("list teman index ke 4,6,7 :",list_teman[4],list_teman[6],list_teman[7])
print('===========================================================================')
list_te... |
#!/usr/bin/env python2
import re
import os
import base64
from dumptruck import DumpTruck
import requests
import tempfile
from unidecode import unidecode
import lxml.html
#import lxml.etree
from time import sleep
from bucketwheel import * # Sorry
RETRIES = 4
WAIT = 2 # seconds, raised to the retry
class Get(BucketMol... |
n = int(input("Please enter your number n = "))
c=1
for i in range(1, n+1):
c *= i
print(n, c, sep="! = ") |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et
#
# Usage: python retriever-multi.py <file with URLs to fetch> [<# of
# concurrent connections>]
#
import sys
import pycurl
# We should ignore SIGPIPE when using pycurl.NOSIGNAL - see
# the libcurl tutorial for more info.
try:
import signal
... |
"""empty message
Revision ID: 4271ff647a5d
Revises: 1e4dbd908e8d
Create Date: 2014-07-04 17:06:01.981123
"""
# revision identifiers, used by Alembic.
revision = '4271ff647a5d'
down_revision = '1e4dbd908e8d'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.execute(
"insert into facebook... |
import json
import datetime
from django.http import Http404, HttpResponse
from django.shortcuts import render
from business_logic import api
from django.core.context_processors import csrf
def login(request,jsonObj):
#if request.method == 'POST':
json_data = json.loads(jsonObj)
username =json_data['username']
pa... |
from djongo import models
# Create your models here.
class ReportForm(models.Model):
subject = models.CharField(max_length=30)
reported_user = models.CharField(max_length=30)
description = models.CharField(max_length=200)
image = models.ImageField(upload_to='', null=True, blank=True) |
import sys
import timeit
def Stack():
items = []
def push(item):
items.append(item)
def pop():
return items.pop()
return ClosureInstance()
class ClosureInstance:
def __init__(self,locals=None):
if locals is None:
locals = sys._getframe(1).f_locals
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import re
import subprocess
import time
from ansible.module_utils.basic import AnsibleModule
DOCUMENTATION = '''
---
module: oracle_db
short_description: Manage an Oracle database
description:
- Create/delete a database using dbca
- If a responsefile is ava... |
"""
Login and logout views for the browsable API.
Add these to your root URLconf if you're using the browsable API and
your API requires authentication:
urlpatterns = [
...
url(r'^auth/', include('rest_framework.urls', namespace='rest_framework'))
]
In Django versions older than 1.9, the urls... |
from django import forms
from django.core import validators
class LetterForm( forms.Form ):
to = forms.CharField( max_length = 100 )
subject = forms.CharField( max_length = 100 )
msg = forms.CharField( )
def clean(self):
user_cleaned_data = super().clean() |
import sys
from PyQt4 import QtGui, QtCore
import facility
import food
import local
import traffic
from mainUI import *
from facility_eidt_UI import *
from facility_serch_UI import *
from facility_view_UI import *
from food_edit_UI import *
from food_serch_UI import *
from food_view_UI import *
from Traffic_view_UI i... |
# Generated by Django 3.0.1 on 2020-03-24 21:54
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='... |
from flask import render_template, flash, url_for, redirect, request, abort
from app import app, db
from app.forms.forms import RegisterForm, LoginForm, BusinessesForm, ReviewForm, SearchForm
from flask_login import login_user, logout_user, current_user, login_required
from app.models.models import User, Businesses, Re... |
from flask import Flask
app=Flask(__name__)
@app.route("/",methods=["get"])
def helloword():
return "helloword,thinkyou!",666,{"Content-Type":"application/json"}
if __name__ == '__main__':
print(app.url_map)
app.run(debug=True) |
#DFS
#Time comp --> o(mn)
#space comp --> o(mn)
class Solution:
def __init__(self):
self.dirs=[[0,1],[1,0],[0,-1],[-1,0]]
def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if len(matrix)==0:
return []
# Maintain two separate arrays to ch... |
import bpy
from pathlib import Path
import json
"""Optionen"""
skalierung = 10 ** 13
frame_schritt = 5
dateipfad = 'C:/Users/...'
# Array aller Objekte im System
objects_arr = []
# definiert Objekt
class Object:
def __init__(self, xs=[], ys=[], zs=[]):
# die Koordinaten
self.xs = xs
self... |
def remove (x):
return list(dict.fromkeys(x) )
names = remove(["John", "William", "John", "Mary", "Steve", "Mary"])
print(names)
|
import rasterio
from rasterio import plot
import numpy
img_b3='LE07_L1TP_199026_20020830_20170214_01_T1_B3.tif'
img_b4='LE07_L1TP_199026_20020830_20170214_01_T1_B4.tif'
if __name__ == '__main__':
band_red = rasterio.open(img_b3)
band_nir = rasterio.open(img_b4)
red = band_red.read(1).astype('flo... |
from django.conf.urls import url, include
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^pic_code/(.+)', views.ImgCodeView.as_view()),
url(r'^msg_code/(?P<phone>.+)/', views.MsgCodeView.as_view()),
# url(r'^msg_code/(?P<phone>.+)/', views.MsgCodeView.as_view()),
# url(r'^msg... |
# Generated by Django 2.2.16 on 2021-01-06 11:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0008_auto_20210104_1028'),
]
operations = [
migrations.AlterField(
model_name='order',
name='emailAddress'... |
# file: address/views.py
from django.shortcuts import get_object_or_404, render, redirect
from address.models import ipv6_address, ipv4_address
from netdevice.models import router, interface, logical_interface
from address.forms import IPv6AddressForm, IPv4AddressForm
def ipv6_address_create(request, logical_inter... |
from intra.system import system_manager
from intra.cgroup import cgroup_manager
import subprocess
class identify_policy:
def get_score_by_uuid(uuid):
return 1.0
class etime_rev_policy(identify_policy):
def get_score_by_uuid(uuid):
pid = cgroup_manager.get_container_pid(uuid)
etime = system_manager.get_pro... |
#!/usr/bin/python
import sys
for line in sys.stdin:
data = line.strip().split("\t")
if len(data) == 26:
idref, ident, gsm19023, gsd19024, gsd19025, gsd19026, genetitle, genesymbol, geneID, uniGenetitle, uniGenesymbol, uniGeneID, NucleotideTitle, GI, GenBankAccession, PlatformCLONEID, PlatformORF, Plat... |
from viterbi import viterbi
from generate_pos_model import get_pos_model
training_data = 'pos_train.txt'
test_data = 'pos_test.txt'
text = open(test_data).read()
trans_p, emit_p = get_pos_model(training_data)
states = list(trans_p.keys())
start_p = trans_p['.']
sentence = 'I like dogs .'
obs = sentence.split()
assi... |
#!/usr/bin/env python
import sys
import math
# The PYTHONPATH should contain the location of moose.py and _moose.so
# files. Putting ".." with the assumption that moose.py and _moose.so
# has been generated in ${MOOSE_SOURCE_DIRECTORY}/pymoose/ (as default
# pymoose build does) and this file is located in
# ${MOOSE_S... |
import numpy as np
from random import randint, uniform
import sys
def move_players(players, apple, colisao):
for player in players:
# pega posicao mais indicada a seguir pela rede neural
direcao, en1, en2 = rede_neural(player, apple)
# pontuacao
distanceX = apple[0] - player[0]
... |
import access_database.sqlite_wrapper as sqlite_wrapper
import classes.struct as s
import classes.process as process
import classes.process_type as process_type
import classes.model as model
import classes.parameter as parameter
import classes.result as result
import classes.output_flow as output_flow
database_file = ... |
from torch.nn import functional as F
from torch import nn
class DeepNet(nn.Module):
def __init__(self, n_joints):
super(DeepNet, self).__init__()
self.c1 = nn.Sequential(nn.Conv2d(3, 96, 11, stride=4, padding=4),
nn.ReLU(inplace=True))
self.c2 = nn.... |
from manysim import Configuration, Cluster, JobMaster
job_config = {
'job_id' : 'test',
'value' : 100,
}
config_params = {
'instance_type' : "t1.micro",
'instance_image' : "ami-xxx",
'access_key' : "ABC",
'secret_key' : "123",
'key_name' : "foo",
'instance_count' : 1,
'pool_size' ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 12 13:47:32 2017
@author: Sandbox999
"""
print("welcome to optimized guessing game")
print("pick a number between 1 and 16")
print("type 0, 1 or 2, depending on whether my guess is less, equal or more than your secret number")
lowerLimit = 1
upperLimit = 16
... |
import sys
from ruamel.yaml import YAML
from ruamel.yaml.compat import StringIO
class Yaml(YAML):
def dump_all(self, data, stream=None, *args, **kwargs):
inefficient = False
if stream is None:
inefficient = True
stream = StringIO()
YAML.dump_all(self, data, stream, ... |
class Point:
default_color = "green"
def __init__(self, x, y):
self.x = x
self.y = y
def draw (self):
print(f"Point ({self.x}, {self.y})")
point = Point(1,2)
point = Point.zero()
print(point)
print(point.default_color)
point.default_color ="red"
print(point.default_color)
print(Poi... |
# Generated by Django 2.0.2 on 2021-01-28 08:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cmms', '0003_auto_20210125_1121'),
]
operations = [
migrations.AddField(
model_name='message',
... |
import pandas as pd
import os
from sqlalchemy import create_engine
# A quick script that loads csv data to the Main DataBase
FILE_PATH = os.path.abspath(os.path.dirname(__file__))
engine = create_engine("mysql://root:E6#hK-rA5!tn@localhost/prescientmaindb")
sector_file = os.path.join(FILE_PATH, "csv_files", "FTSE_Sec... |
# 参考:https://note.com/mokuichi/n/n70d61237e6c7
# coding: utf-8
import pyaudio
import numpy as np
CHUNK = 512
RATE = 48000
P = pyaudio.PyAudio()
stream = P.open(format=pyaudio.paInt16, channels=1, rate=RATE, frames_per_buffer=CHUNK, input=True, output=False)
while stream.is_active():
try:
input = stream... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@File: DataWrangler.py
@Description: PySpark application for cleaning and preprocessing customer
and product purchase data.
@Author: Chetan Borse
@EMail: cborse@uncc.edu
@Created on: 12/04/2016
@Usage: python src/... |
from Commands import Commands
class Run:
def __init__(self, boat: [], start_coast: [], finish_coast: [], move_yn: str):
self.boat: [] = boat
self.start_coast: [] = start_coast
self.finish_coast: [] = finish_coast
self.move_yn: str = move_yn
def run(self, action, beast):
... |
from nltk.tag.stanford import NERTagger
# locations of Stanford parser/models, Java, and English PCFG model
USER_STANFORD_PARAMS = {}
JEMMIN_HOME_ROOT = '/usr/lib/stanford-ner-2014-08-27'
USER_STANFORD_PARAMS['Jemmin_home'] = [JEMMIN_HOME_ROOT + '/classifiers/english.muc.7class.distsim.crf.ser.gz', JEMMIN_HOME_ROOT + ... |
from datetime import date
from django.test import TestCase
from wagtail.tests.utils import WagtailTestUtils
from model_mommy import mommy
from wagtailregulations.models.django import (
EffectiveVersion,
Part,
Section,
Subpart,
)
class TestRegs3kHooks(TestCase, WagtailTestUtils):
def setUp(self)... |
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time
sys.setrecursionlimit(10**7)
inf = 10**10
def f():
h,w,n = list(map(int, input().split()))
t = collections.defaultdict(int)
for _ in range(n):
a,b = list(map(int, input().split()))
for i in range(3):
... |
import argparse
import datetime
import time
import boto3
def count_jobs(batch, job_queue):
total = 0
message = ''
for status in ('SUBMITTED', 'PENDING', 'RUNNABLE', 'STARTING',
'RUNNING'):
response = batch.list_jobs(
jobQueue=job_queue,
jobStatus=status... |
from abc import ABC, abstractmethod
from numpy.linalg import inv
import numpy as np
class MAB(ABC):
@abstractmethod
def play(self, tround, context):
# Current round of t (for my implementations average mean reward array
# at round t is passed to this function instead of tround itself)
... |
from types import SimpleNamespace
from typing import Optional
import neptune.new as neptune
import torch
from sb3_contrib import QRDQN, TQC
from stable_baselines3 import A2C, DDPG, DQN, HER, PPO, SAC, TD3
ALGOS = {
"a2c": A2C,
"ddpg": DDPG,
"dqn": DQN,
"ppo": PPO,
"her": HER,
"sac": SAC,
"... |
# -*- coding: utf-8 -*-
def g1(x):
return int(''.join(list(map(int, sorted(str(x)))))
def g2(x):
return int(''.join(list(map(int, sorted(str(x), reverse=True)))))
def f(x):
return g1(x) + g2(x)
def main():
n, k = map(int, input().split())
for i in range(10):
if __name__ == '__main__':
ma... |
PAssword = input("Enter a new password (at least 10 characters):")
LEN = len(PAssword)
while LEN < 10:
print("Too short! At least 10 characters.")
PAssword = input("Enter a new password:")
LEN = len(PAssword)
print(PAssword)
|
"""This module contains tests for modifying performance resources."""
from pytest import mark
from datetime import datetime
from flask_app.utils import get_headers
from app.models import Performance
def test_create_new_performance_with_valid_data(
flask_test_client, auth, user, artist, venue, json, db
):
""... |
import os
import cgi
import wsgiref.handlers
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
def reg(request):
user = users.get_current_user(... |
#抛出异常:raise语句
def division(x,y):
if y==0:
raise ZeroDivisionError('The zero is not allow')
return x/y
try:
division(1,0)
except ZeroDivisionError as e:
print(e)
|
import asyncio
from data import config
from utils.db_api import quick_commands
from utils.db_api.db_gino import db
async def test():
await db.set_bind(config.POSTGRES_URI)
# await db.gino.drop_all()
await db.gino.create_all()
print('Добавляем новость')
# await quick_commands.add_news(
# ... |
"""CIS 189
Alex Rickels
Topic 1 Assignment 1"""
def make_list():
"""
:return: list of 3 user inputs
"""
the_list = []
for x in range(0, 3):
try:
user_input = (int(get_input()))
except ValueError:
print("try again!")
else:
the_list.append(... |
# Generated by Django 2.1.4 on 2019-01-11 00:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0007_match_date'),
]
operations = [
migrations.AddField(
model_name='redcard',
name='double_yellow',
... |
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
'''
backtracking traverses a path until it isn't suitable, then
abandons the path for a new more suitable path
'''
self.ans = []
self.backtrack(graph, 0, [0], len(graph)-1)
... |
import pickle, glob, os
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
folder = "C:/Users/dpedr/Desktop/test_EMGchannels"
file = "stnL_c1_5.0mA_dd_20200109-165832.pkl"
fig = plt.figure()
for k in range(1,9):
fig, axs = plt.subplots(8, sharex=True)
for name in glob.glob(folder+'/... |
import pickle
import numpy
from comsyl.waveoptics.ComsylWofryBeamline import ComsylWofryBeamline
from comsyl.waveoptics.SRWAdapter import ComsylSRWBeamline
from comsyl.autocorrelation.AutocorrelationFunction import AutocorrelationFunction
def create_beamline_srw_new(load_from_file=None,slit_width=5e-6,slit_height=... |
import os
import logging
import time
def create_logger(root_output_path, config):
"""
create the logger path and the data output path.
"""
# set up logger
if not os.path.exists(root_output_path):
os.makedirs(root_output_path)
assert os.path.exists(root_output_path), '{} does not exist'... |
X=[0]*10001
for i in range(2,10001):
now_sum=0
for j in range(1,i-1):
if i%j==0:
now_sum+=j
X[i]=now_sum
now_sum=0
for i in range(10001):
if X[i]<=10000 and i == X[X[i]] and X[i] != i:
now_sum += i
print(X[i],X[X[i]],i)
print(now_sum) |
from RedBlackTree import *
import math
import random
from tkinter import *
import matplotlib.pyplot as plt
YSIZE = 750
PSIZE = 4
isFirstClick = False
# -----------------------------------------------------------------
# Event class for endpts and intersection pts in our event queue
# --------------------------------... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-29 12:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bowling_app', '0013_auto_20180329_0700'),
]
operations = [
migrations.AddFiel... |
# Copyright (c) 2017, John Skinner
import abc
import database.identifiable as identifiable
import database.entity_registry as reg
class EntityMetaclass(type):
"""
Entity metaclass.
When an entity class is declared, it will register the class name in the entity register.
This is so that type names stor... |
from flask import render_template, url_for, escape, redirect, abort
from app import core
from database import db
@core.route('/post')
@core.route('/categorie')
@core.route('/tag')
def returnToHome():
return redirect(url_for('home')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.