text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
import torch
import os
import numpy as np
import re
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from PIL import Image
from imbalanced_sampler import Imb... |
# Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск).
# Атрибут реализовать как приватный.
# В рамках метода реализовать переключение светофора в режимы: красный, желтый, зеленый.
# Продолжительность первого состояния (красный) составляет 7 секунд, второго (ж... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.InsEmployee import InsEmployee
class AlipayInsSceneEmploymentGroupendorseAppendModel(object):
def __init__(self):
self._employee_list = None
self._endorse_ord... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 21 20:32:18 2018
@author: wdr78
"""
import numpy as np
import pandas as pd
date_col = ['计飞','计到','实飞','实到']
flights = pd.read_csv('C:/Users/wdr78/Desktop/ceair_simulation/simulation/2018-01-17.csv',low_memory=False,parse_dates=date_col,keep_default_na=False,encoding='gbk'... |
from twilio.rest import Client
import os
import pymongo
from twilio.twiml.messaging_response import MessagingResponse
from flask import Flask, request, redirect
from twilio.twiml.voice_response import Play, VoiceResponse
from flask_cors import CORS, cross_origin
import random
app = Flask(__name__)
cors = CORS(app)
ap... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'saveProject.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 impor... |
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from django.views.generic.base import RedirectView
from django.conf.urls.static import static
from esabha import settings
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.... |
# Standard library imports
from time import time
import sys
import argparse
import os
# Third party imports
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
# Local application imports
from mymodules.preprocessing import SignalGenerator
def make_mlp(units):
model = kera... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 10:37:33 2021
@author: HP
"""
import cv2 as cv
import scipy.fft as spfft
import numpy as np
def dct2D(a):
return spfft.dct(spfft.dct(a.T, norm='ortho').T, norm='ortho')
def idct2D(a):
return spfft.idct(spfft.idct(a.T, norm='ortho').T, norm='ortho')
img11... |
'''1.Write a program that reads a positive integer, n, from the user and then displays the sum of all of the integers from 1 to n.
The sum of the first n positive integers can be computed using the formula: sum = (n)(n + 1) / 2 '''
print('-'*20)
n = int(input("Enter a positive integer: ")) #Read the input from the... |
"""
1. Pretraining SimCLR & Proto-typing
2. Training OOD (one-class classification)
3. Evaluation (eval.py?)
python3 train_main_ssl.py --save_dir semi --known_normal 0 --load_path ./pretrained/model_cifar10_0.pth --lr .0001 --dataset cifar10 --optimizer adam --ratio_known_normal 0.05 --ratio_known_outlier 0.05
"""
imp... |
import test
from flask import Flask, Response
from flask import render_template
from flask import url_for
app = Flask(__name__)
x = test.myfunction()
g = x[1]
b = x[0]
@app.route("/")
def hello():
return render_template('index.html')
@app.route("/good")
def good():
print(type(g))
return render_template('goodNews... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from urllib import quote_plus
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.core.paginator import Paginator, EmptyPage, P... |
from IPython.core.magic import (register_line_magic, register_cell_magic,
register_line_cell_magic)
import cogniac
from tabulate import tabulate
from datetime import datetime
import os
import time_range
from sys import argv
__builtins__['cc'] = None
__builtins__['S'] = None
def print... |
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from send.models.Infomation import Information
from send.serializers.serializer import InformationSerializer
class InformationView(APIView):
def get(self, request, format=None):
inform... |
import numpy as np
import numpy.testing as npt
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import BaggingRegressor
from sklearn.svm import SVR
import forestci as fci
def test_random_forest_error():
X = np.array([[5, 2], [5, 5], [3, 3], [6, 4], [6, 6]])
y = np.array([70, 100, 60, ... |
voornaam= input("Wat is je voornaam?")
naam= input("Wat is je naam?")
leeftijd = input("Wat is j leeftijd?")
email = input("Wat is je email adres?")
print("Je heet {0} met je voornaam en {1} met je familienaam".format(voornaam, naam))
print("Je bent {0} jaar oud.".format(leeftijd))
print("Je email adress is " + email... |
# code from: https://github.com/tensorflow/models/blob/master/research/slim/slim_walkthrough.ipynb
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
# Main slim library
from tensorf... |
import fitsql as fs
from astropy.io import fits
import psycopg2 as p2
con=p2.connect("dbname='stars' user='postgres' host='localhost'")
cur=con.cursor()
fs.upfile('/home/groberts/astro/DeaconHamblydata/DeaconHambly2004.PrevMemb.fit','stars')
fs.upfile('/home/groberts/astro/DeaconHamblydata/DeaconHambly2004.HighProb.fit... |
from .ControlLimit import ControlLimit
class UpperControlLimit(ControlLimit):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def setup(self, **kwargs):
self.limit = kwargs["limit"]
def check_sample(self, sample):
return sample <= self.limit
|
def chk(no):
if no == 0:
print("Number is Zero");
elif no > 0:
print("Number is Positive");
else:
print("Number is Negative");
print("Enter a number to check");
no = int(input());
chk(no);
|
import os
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import torch
from agent import Agent
from train_eval import evaluate_agent, train_agent
from unityagents import UnityEnvironment
TRAIN = False
# env_path = "/data/Tennis_Linux_NoVis/Tennis.x86_64"
local_path = os.path.dirname... |
# Scrapes ESPN's 2012-2014 staff preseason rankings
# Wrties the rankings for each year to a csv file
from bs4 import BeautifulSoup
for year in ['2012', '2013', '2014']:
infile = open(year +'main.html', 'r').read()
soup = BeautifulSoup(infile, 'lxml')
rows = soup.find_all('tr', {'class' : 'last'})... |
#!/usr/bin/env python
"""
Copyright 2014 Wordnik, Inc.
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 applica... |
# Decimal dominants. Given an array with n keys, design an algorithm to find all values
# that occur more than n/10 times. The expected running time of your algorithm should be linear.
# Hint: determine the (n/10)th largest key using quickselect and check if it occurs more than n/10 times.
# https://massivealgorithms.... |
from metric import Metric
from util import Util
import numpy as np
import partition_comparison
class RIMeasure(Metric):
'''
This calculates rand index.
'''
@classmethod
def apply(cls, label_array):
'''
Apply the metric to a label_array with shape Y,X,Z.
'''
vi_sum = 0.
done = 0.
pr... |
#
# @lc app=leetcode id=199 lang=python3
#
# [199] Binary Tree Right Side View
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def right... |
import numpy as np
from matplotlib import pyplot as plt
from q5_1 import *
import ipdb
import math
def calc_prob(x, lambda_, func):
return np.exp(lambda_*func(x))
def MH_algo(lambda_, x, func, var):
X = []
x_ = x*1.0
for i in range(500):
while(1):
y = np.random.normal(x_, var**0.5, ... |
from django.contrib import admin
from . import models
from django.utils.safestring import mark_safe
# Register your models here.
@admin.register(models.Categorie)
class CategorieAdmin(admin.ModelAdmin):
list_display = ('nom', 'date_add', 'date_upd', 'status',)
list_filter = ('date_add', 'date_upd', 'status',)
... |
import random
from time import sleep
numint = random.randint(1, 5) #Computador emite um número aleatório
#print(numint)
print('-=-' * 20)
numUser = int(input('Digite um número entre 1 e 5: ')) #Usuário digita um número aleatório
print('-=-' * 20)
print('Processando os dados...')
#sleep()
if numUser == numint: #Faz a V... |
from flask_app.models.game_model import GameModel
import datetime
class GameCollection():
def __init__(self):
self.models = []
def populate(self, data):
for datum in data:
g = GameModel()
g.populate(datum)
# These come back as '/'-delimited strings, so split... |
from PyObjCTools.TestSupport import TestCase, min_os_level
import SafariServices
class TestSFSafariExtensionManager(TestCase):
@min_os_level("10.12")
def testMethods(self):
self.assertArgIsBlock(
SafariServices.SFSafariExtensionManager.getStateOfSafariExtensionWithIdentifier_completionHan... |
import numpy as np
from os import path
from proj1_helpers import load_csv_data, eval_model, predict_labels, create_csv_submission
from data_utils import feature_transform, standardise, standardise_to_fixed
from implementation_variants import logistic_regression_mean
cwd = path.dirname(__file__)
SEED = 42
DATA_PATH ... |
'''
Created on 23 okt. 2015
@author: danhe
'''
from game_tools import Sprite
class Map(Sprite):
def __init__(self, map_file):
super(Map,self).__init__(source=map_file)
self.id = 'map'
return
def update(self):
return
|
import sys
import os
import fileinput
from functools import partial
import numpy as np
from _global_stat_main import main
sys.path.insert(0, '../')
import seqmodel as sq # noqa
def load_data(opt):
dpath = partial(os.path.join, opt['data_dir'])
vocab = sq.Vocabulary.from_vocab_file(dpath('vocab.txt'))
... |
"""
Created on Jan 14, 2016
@author: stefanopetrangeli
"""
from sqlalchemy import Column, VARCHAR, Boolean, Integer
from sqlalchemy.ext.declarative import declarative_base
import logging
from orchestrator_core.exception import DomainNotFound
from orchestrator_core.sql.sql_server import get_session
from sqlalchemy.orm... |
#!/usr/bin/python
# http://flask.pocoo.org/docs/0.10/patterns/sqlite3/
# http://ryrobes.com/python/running-python-scripts-as-a-windows-service/
# http://stackoverflow.com/questions/23550067/deploy-flask-app-as-windows-service
# http://gouthamanbalaraman.com/blog/minimal-flask-login-example.html
from flask import Flas... |
# coding: utf-8
# In[1]:
#In this project I will try to detect the presence of heart disease based on 13 different features.
#If a high accuracy is achieved, this will show that we can predict heart disease in people with high certainty.
#This can be very valuable in practice: A lot of these features are already ca... |
from __future__ import unicode_literals
from django.db import models
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class EmailManager(models.Manager):
def validate(self, email):
if len(email) < 1:
return False
if EMAIL_REGEX.match(email):
... |
import robin_stocks as rs
from time import sleep
from getpass import getpass
ticker = 'NIO'
p = 0.94
c = 1
rs.login(username='liujch1998',
password=None,#getpass(),
expiresIn=86400 * 365,
by_sms=True)
try:
fund = rs.stocks.get_fundamentals(ticker, info=None)
last_high = float(fund[... |
N, K = map(int, input().split())
x = list(map(int, input().split()))
p = N
for i in range(N):
if x[i] > 0:
p = i
break
result = float('inf')
for i in range(K + 1):
if p - i < 0 or p + K - i > N:
continue
if i == 0:
result = min(result, x[p + K - 1])
elif i == K:
... |
import tensorflow as tf
from tensorflow.contrib import layers
def semi_supervised_encoder_convolutional(input_tensor, z_dim, y_dim, batch_size, network_scale=1.0, img_res=28, img_channels=1):
f_multiplier = network_scale
net = tf.reshape(input_tensor, [-1, img_res, img_res, img_channels])
net = layers.conv2d(net,... |
#-*- coding: utf-8 -*-
#@File : mockTest.py
#@Time : 2021/6/4 20:32
#@Author : xintian
#@Email : 1730588479@qq.com
#@Software: PyCharm
#Date:2021/6/4
import requests
HOST = 'http://127.0.0.1:9999'
# def test():
# #1- url
# url = f'{HOST}/sq'
# payload = { "key1":"abc"}
# #发请求
# resp = reque... |
# https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/
# 剑指 Offer 59 - I. 滑动窗口的最大值
from collections import deque
from typing import List
class Solution:
"""
将值依次存入堆中,一次获取最大值,
堆中存入 (值,值的索引)
解决的问题:
1. 最大值 a 从堆中 pop, 已经不再堆中, 但依然在窗口中,
下一个最大值依然为 a,因此,需要比较窗口左边界的索引与上次 pop... |
# Generated by Django 3.0.7 on 2021-05-30 05:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('carapp', '0004_remove_car_rcno'),
]
operations = [
migrations.RemoveField(
model_name='customers',
name='role',
),
... |
#!/usr/bin/env python
from setuptools import setup, find_packages
version = '1.5'
long_desc = """
nose-perfdump is a Nose plugin that collects per-test performance metrics into an
SQLite3 database and reports the slowest tests, test files, and total time
spent in tests. It is designed to make profiling tests to im... |
'''
Given an undirected graph, return true if and only if it is bipartite.
Recall that a graph is bipartite if we can split its set of nodes into two independent subsets A and B, such that every edge in the graph has one node in A and another node in B.
The graph is given in the following form: graph[i] is a list of ... |
# -*- coding: utf-8 -*-
import copy
import logging
import os
import re
import sys
import traceback
from logging.handlers import RotatingFileHandler
from Queue import Queue
from threading import Event, Thread
class Carrier(object):
''' スレッド間のデータ受け渡しとイベント通知を行う '''
def __init__(self, name):
self.name = na... |
"""
Given an integer k, we define the frequency array of a string Text as an array of length 4k, where the i-th element of
the array holds the number of times that the i-th k-mer (in the lexicographic order) appears in Text (see Figure 1.
Computing a Frequency Array
Generate the frequency array of a DNA string.
Give... |
t=(int)(input())
for abc in range(t):
c=(int)(input())
n=(int)(input())
l=[]
a=raw_input().split(' ')
for x in a:
l.append((int)(x))
for i in range(n):
if c-l[i] in l:
try:
p=l.index(c-l[i],i+1)
if p>i:
print i+1,p+1... |
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
import csv
from datetime import datetime
################ SUPPORT FUNCTIONS #############
def getHTMLforResource(resource):
"""
accepts a resource as a string input, and outputs an html table. The function makes a get request to inv... |
import datetime
from bin.leap import Leap
def test_leap_event():
leap = Leap("1", datetime.datetime(2021, 2, 2), "Test leap", 1)
e = leap.event()
assert len(leap.event().alarms) == 1
assert leap.event().alarms[0].trigger.days < 0
assert e.duration.days == 7
must_haves = [
"BEGIN:VE... |
import cv2,sys,numpy,random,os,math,select,time
from threading import Thread
import sqlite3,datetime,sys
camera_link = 0
camera_no = 0
def prompt() :
sys.stdout.write('\rWatchMen>> ')
sys.stdout.flush()
fn_dir='faces'
images = []
lables = []
names = {}
colours={}
id=0
for subdir in os.listdir(fn_dir):
if sub... |
from collections import defaultdict
def solution(words, queries):
word_map = Trie('')
reversed_word_map = Trie('')
for word in words:
word_map.insert(word)
reversed_word_map.insert(word[::-1])
result = list()
for query in queries:
if query.endswith('?'):
result.... |
#!/usr/bin/env python
"""
Examples:
%s
%s -i /Network/Data/250k/db/dataset/call_method_32.tsv -o /tmp/call_32.vcf
Description:
2013.03
"""
import sys, os, math
__doc__ = __doc__%(sys.argv[0], sys.argv[0])
sys.path.insert(0, os.path.expanduser('~/lib/python'))
sys.path.insert(0, os.path.join(os.path.expanduser... |
import numpy as np
from dataloader import get_data
from models import Net
import tensorflow as tf
from tensorflow.keras.utils import Progbar
import pickle
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
BATCH_SIZE = 16
EPOCHS = 10
MODEL_NAME = 'fcmodel'
X_train, X_val, y_train, y_val = get_data()
print(X_train.shap... |
import datetime
import uuid
from flask import session
from models.database import Database
def retblogs():
blog_data = []
coll=Database[blogs]
for i in coll:
blog_data.append(i)
return blog_data
|
from sklearn import linear_model
from sklearn import datasets
from sklearn.preprocessing import PolynomialFeatures
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
import numpy as np
impo... |
"""
Corrects unjustified track breakages from third party storm identification and tracking algorithms
Best Track: Real Time (BTRT) is a Python package designed to read in the output of a
third-party storm identification and tracking algorithm (i.e. WDSS-II segmotion; ProbSevere)
and improve upon that algorithm’s ... |
cnt=0
def quicksort(arr):
global cnt
if len(arr)<=1:
return arr
p=arr.pop(0)
menores,mayores=[],[]
for e in arr:
cnt+=1
if e<=p:
menores.append(e)
else:
mayores.append(e)
return quicksort(menores) + [p] + quicksort(mayores)
a=[1, 0, 15, 6, 7]
print(a)
quicksort(a)
print(cnt)
|
# coding=utf-8
from .test_default_mirror import TestDefaultMirror
from .test_httpbin import TestHttpbin
from .test_verification import TestVerification, TestVerificationSingleAnswer
from .test_cache_system import TestCacheSystem
from .test_cdn import TestCDN
from .test_redirection import TestRedirection
from .te... |
#pip install paho-mqtt
import paho.mqtt.publish as publish
import Adafruit_DHT
import time
import datetime
import busio
import digitalio
import board
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn
# colocamos el channelID de nuestro canal de thingspeak
channelID="1326958"
# colo... |
# Import bot token from environment variables
from os import environ
botToken = environ.get("MR_ROBOTO_TOKEN")
# Create updater and save reference to dispatcher
from telegram.ext import Updater
updater = Updater(token=botToken)
dispatcher = updater.dispatcher;
# Set up logging errors
import logging
logging.basicConfi... |
# -*- coding=UTF-8 -*-
# pyright: strict, reportTypeCommentUsage=none
from __future__ import absolute_import, division, print_function, unicode_literals
from wulifang.vendor.wlf import path as wlf_path
TYPE_CHECKING = False
if TYPE_CHECKING:
from typing import Text
def shot_from_filename(_filename):
# type... |
def min_manufacture(i, j, s):
global min_rate
if s >= min_rate:
return
if i == N-1:
min_rate = s
return
else:
for k in range(N):
visited[k][j] = 1
for l in range(N):
if visited[i+1][l] == 0:
min_manufacture(i+1, l, s+rate[i+... |
#coding=utf-8
import os
import shutil
import unittest
import tempfile
from DB import DB
from DBOptions import DBOptions
from WriteOptions import WriteOptions
from ReadOptions import ReadOptions
class TestDB(unittest.TestCase):
def setUp(self):
self.db_dir = tempfile.mkdtemp()
def tearDown(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 28 10:42:00 2017
@author: utente
Sbilanciamento 7 -- OUT OF SAMPLE ERROR CONTROL MODULE --
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
import os
##############################################################... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 Huawei Device Co., Ltd.
# 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
... |
import unittest
from datetime import datetime
import scraper as scr
import gearman
import bson
class TestScraping(unittest.TestCase):
def test_get_feed_data(self):
# The url is to a static RSS feed stolen from Hacker News
test_feed = scr.get_feed_data('http://u.m1cr0man.com/l/feed.xml')
... |
"""
controller.py
Python3 script to control two servos and a raspberry pi camera in a pan and tilt mechanism.
The first servo pans the second servo and tilt mechanism which holds the raspberry pi camera.
dependencies:
pip3 install gpiozero
pip3 install picamera
Things also work much more smoothly if you use the pig... |
import cv2
import numpy as np
img = cv2.imread('dorm.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
suft = cv2.SIFT(500)
kp,des = suft.detectAndCompute(img,None)
img = cv2.drawKeypoints(gray,kp,None,(255,0,0),10)
print len(kp)
cv2.imshow('test',img)
cv2.waitKey(0)
cv2.destroyAllWindows() |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import itertools
import logging
import os
import numpy as np
from collections import defaultdict
from rasa_nlu.config import RasaNLUConfig
from rasa_nlu.converters impo... |
from __future__ import print_function
import warnings
import os.path as op
import copy as cp
from nose.tools import assert_true, assert_raises, assert_equal
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
import mne
from mne.datasets import testing
from mne.beamformer import... |
import copy
def getValidMove(p, x, y, state):
m = []
left = 0
if p == "Star":
if x == 0:
return m
if x == 1 and y != 0 and state[x-1][y-1][0] != 'C':
m.append([x-1,y-1])
if x == 1 and state[x-1][y+1][0] != 'C':
m.append([x-1,y+1])
if x == 2 and state[x-1][y-1] == '0':
m.append([x-1,y-1])
left... |
import numpy as np
from .transforms import *
class Dataset(object):
def __init__(self, train, test, mode='Train'):
super(Dataset, self).__init__()
self.train = train
self.test = test
self.mode = mode
if self.mode == 'Train':
self.data = self.train
... |
# -*- coding:utf-8 -*-
import numpy as np
import transformers
import torch
from model import ResidualModel
import numpy as np
import json
import os
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
def model_init(model_path, device, length_num):
ckpt = torch.load(model_path, map_... |
"""
Given an array of non-negative integers, you are
initially positioned at the first index of the array.
Each element in the array represents your maximum jump
length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from ind... |
#encoding=utf-8
htmls=[]
#获取图片所在网页的html地址
class getHtml():
def __init__(self,target_url):
self.target_url=target_url
def html(self,start_page,page_num):
for i in xrange(start_page,page_num+1):
h=self.target_url % i
global htmls
htmls.append(h)
#获取图片地址
import r... |
# score_file = open("score.txt","w",encoding="utf8")
# print("수학 :0",file = score_file)
# print("영어 :50", file = score_file)
# score_file.close()
# score_file = open("score.txt","r",encoding="utf8")
# print(score_file.read())
# score_file.close()
# score_file = open("score.txt","r",encoding="utf8")
# print(score_file... |
#!/usr/bin/env python
# coding=utf-8
try:
import cupy as np
except ImportError:
import numpy as np
from nda.optimizers import Optimizer
from nda.optimizers import compressor
class CHOCO_SGD(Optimizer):
'''Decentralized Stochastic Optimization and Gossip Algorithms with Compressed Communication'''
de... |
import os
from robot.libraries.BuiltIn import BuiltIn
from robot.libraries.Collections import Collections
from robot.api import logger
import psutil
import shutil
import csv
from os import listdir, rmdir, remove
import json
import sys
import re
from sys import platform as _platform
import tempfile
DOWNLOADS_PATH = r'C... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Created on 2020/4/15 21:16
@author: phil
"""
import numpy as np
class BagOfWord:
def __init__(self, do_lower_case=False):
self.vocab = {}
self.do_lower_case = do_lower_case
def fit(self, sent_list):
# sent_list 类型为 L... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import smart_selects.db_fields
class Migration(migrations.Migration):
dependencies = [
('registro', '0003_auto_20151120_1520'),
]
operations = [
migrations.AddField(
mode... |
# Generated by Django 3.0.7 on 2020-07-25 13:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('sliderpic', '0012_projec... |
# Generated by Django 3.0.5 on 2020-04-17 22:06
import ckeditor_uploader.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('news', '0003_auto_20200417_2152'),
]
operations = [
migrations.AlterField(
model_name='comment',
... |
import email.message
import enum
import logging
import random
from collections import defaultdict
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from types import TracebackType
from typing import (
TYPE_CHECKING,
Any,
Callable,
... |
# A non-empty zero-indexed array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.
# Array A contains only 0s and/or 1s:
# 0 represents a car traveling east,
# 1 represents a car traveling west.
# The goal is to count passing cars. We say that a pair of cars ... |
import collections
import config
import cv2
import numpy as np
path = config.path
frame_num = 100 # config.frame_num
camera_num = config.camera_num
background_path = "/run/media/benjamin/HDD-3/Dataset/medialab_20210924/background"
# Full kernels
FULL_KERNEL_3 = np.ones((3, 3), np.uint8)
FULL_KERNEL_5 = np.ones((5, 5... |
import torch
from torch import nn
from torch_geometric.nn import dense_diff_pool
from torch_geometric.nn import global_sort_pool
from torch_geometric.nn.inits import glorot
from utils import adj_to_edge_index
from boxx import timeit
class SortPool(torch.nn.Module):
def __init__(self, k):
super(SortPool... |
"""
问题:
跟559类似,求树的深度。。。
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""... |
# Generated by Django 2.0.2 on 2018-02-23 09:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('talks', '0033_auto_20180217_1239'),
]
operations = [
]
|
# nums = [-2,1,-3,4,-1,2,1,-5,4]
# def maxSubArray(nums):
# if max(nums)<0:
# return max(nums)
# local_max, global_max = 0 , 0
# for num in nums:
# local_max = max(0,local_max+num)
# global_max= max(global_max,local_max)
# return global_max
# print(maxSubArray(nums))... |
import unittest
# Note: Python's sort algo is "Timsort" - a hybrid of merge sort and insertion sort
def solution(A):
A.sort() # I'd rather use sorted() and not modify the input but rules says I can't use additional memory
return max(A[-3] * A[-2] * A[-1], A[0] * A[1] * A[-1])
class TestMaxProductOfThree(u... |
try:
import cv2
import sys
import numpy as np
from os import listdir
from random import shuffle
from cod.extension import path_to_images, path_to_dataset_from_images
except ValueError:
print("Modules loading failed in " + sys.argv[0])
def save_data_to_file():
existing_folde... |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = '_X.xx_'
__date__ = '2018/7/18 18:11'
from django.urls import path
from . import views
app_name = 'payinfo'
urlpatterns = [
path('', views.payinfo, name='payinfo'),
path('auth/', views.auth_test)
] |
S = input()
T = input()
ls = len(S)
lt = len(T)
for i in range(ls-lt,-1,-1):
for j in range(lt):
if S[i+j] != T[j] and S[i+j] != '?':
break
else:
print((S[:i] + T + S[i+lt:]).replace('?','a'))
break
else:
print('UNRESTORABLE')
|
from flask import Flask
from flask_restplus import Api, Resource, fields
app = Flask(__name__)
api = Api(app)
# The first argument is to specify the model name.
a_language = api.model('Language_Model', {'language' : fields.String('Please type in a language you want.')})
languages = []
python = {'language' : 'Python... |
import argparse
import math
import time
import os
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.utils.data
from torch.optim.lr_scheduler import ReduceLROnPlateau
from model import DAN
import dataloader
import Constants
from build_vocab ... |
import copy
import unittest
import networkx
from qubo_nn.problems import MaxCut
from qubo_nn.problems.max_cut import MaxCutMemoryEfficient
class TestMaxCut(unittest.TestCase):
def test_gen_qubo_matrix(self):
"""Test whether a correct QUBO is generated.
Test case from: https://arxiv.org/pdf/1811.1... |
import resources.lib.nflcs
class Team(resources.lib.nflcs.NFLCS):
_short = "cowboys"
_cdaweb_url = "http://www.dallascowboys.com/cda-web/"
_categories = [
"Video - AskTheBoys",
"Videos - Cheerleaders",
"Video - Coaches-Executives",
"Videos - Draft",
"Videos - Exclus... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.