text stringlengths 8 6.05M |
|---|
x = [1, 2, 3]
def oops(num_list, n):
for i in num_list:
try:
print(num_list[n] + 2)
break
except IndexError:
print('oops')
break
def main():
try:
oops(x, 3)
except KeyError:
print('oops')
main()
|
def triangle(a,b,c):
if (((a+b)>c)and((b+c)>a)and((c+a)>b)):
return True;
else:
return False;
a=input();
b=input();
c=input();
print triangle(a,b,c);
|
import logging
import redis
from django.conf import settings
# from .api_connection import ApiConnection
from .db_connection import DbConnection
# from .util import Util
class HistoricalManager:
def __init__(self):
self.logger = logging.getLogger(__name__)
# self.util = Util()
self.db_con... |
#-- GAUDI jobOptions generated on Tue Jul 14 16:29:02 2015
#-- Contains event types :
#-- 11104401 - 145 files - 3002924 events - 876.12 GBytes
#-- Extra information about the data processing phases:
from Gaudi.Configuration import *
from GaudiConf import IOHelper
IOHelper('ROOT').inputFiles(['LFN:/lhcb/MC/2012... |
import os
import numpy as np
import glob
import cv2
import random
import torch
import logging
from datetime import datetime
def mkdir(path):
if not os.path.exists(path):
os.mkdir(path)
def mkdir_experiments(path):
mkdir(path)
mkdir(os.path.join(path, 'models'))
mkdir(os.path.join(path, 'train... |
from __future__ import annotations
from wiki.inheritance.Lamborghini import Lamborghini, Aventador
class IsaacEdition(Lamborghini):
__onlyInstance: IsaacEdition = None
def __init__(self):
super(IsaacEdition, self).__init__()
if IsaacEdition.__onlyInstance is not None:
raise Runti... |
from django.db import models
# Create your models here.
class Autor(models.Model):
nome = models.CharField(max_length=150, blank=False, null=False)
class Meta:
verbose_name_plural = 'Autores'
def __str__(self):
return self.nome
class Livro(models.Model):
CATEGORIA_CHOICES = {
... |
a=list(input('Enter the list'))
x=int(input('Enter the value to be searched'))
count=0
for i in range(0,len(a)):
if x == int(a[i]) :
count+=1
print(count)
if count>0:
print('Element is present',count,'times')
else:
print('Element is not present') |
try:
from django.conf import settings
except ImportError:
pass
def overridable(name, default=None):
try:
return getattr(settings, name, default)
except NameError:
return default
# Enables Suds request/response logging
DEBUG = overridable('DEBUG', False)
# Remove the Suds file cache of... |
import cv2
cam0 = cv2.VideoCapture(0)
cam1 = cv2.VideoCapture(1)
# windows7 + python3.7+ opencv 3.4
# fourcc = cv2.VideoWriter_fourcc(*'XVID')
# Raspberry pi+ python2.7+opencv 2.4.9
fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
out0 = cv2.VideoWriter('out0.avi', fourcc, 20.0, (640, 480))
out1 = cv2.VideoWriter('out1.... |
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from sklearn.datasets import make_circles
X, y = make_circles(n_samples=10000, factor=.3, noise=.07)
y_fit = KMeans(n_clusters=2).fit(X)
plt.figure(1)
plt.subplot(221)
reds = y == 0
blues = y == 1
plt.plot(X[re... |
import numpy as np
from numpy import pi
from . import qg_diagnostics
try:
import mkl
np.use_fastnumpy = True
except ImportError:
pass
try:
import pyfftw
pyfftw.interfaces.cache.enable()
except ImportError:
pass
class QGModel(qg_diagnostics.QGDiagnostics):
r"""Two layer quasigeostrophic mo... |
__author__ = 'Галлям'
import logging
import asyncore
from PyQt5 import QtCore
from .import asynchat_patched
logger = logging.getLogger(__name__)
class ProtocolInterpreter(QtCore.QThread, asynchat_patched.AsyncChat):
wait_until_next_command = QtCore.pyqtSignal() # 100
data_canal_ope... |
#Dobro, o triplo e raiz quadrada
n1 = float(input('Digite um numero: '))
dob = n1 * 2
trip = n1 * 3
raiz = n1 ** (1/2)
print('O dobro é {}, o triplo é {} e raiz quadrada é {:.3f}'.format(dob, trip, raiz))
|
# Hough Line Transform : 직선을 찾기 위해 사용되는 알고리즘
import math
import cv2 as cv
import numpy as np
# img_gray = cv.imread("../sample/circle.jpg", cv.IMREAD_GRAYSCALE)
img_gray = cv.imread("../sample/orange.png", cv.IMREAD_GRAYSCALE)
img_gray = cv.medianBlur(img_gray, 5)
img_color = cv.cvtColor(img_gray, cv.COLOR_GRAY2BGR)... |
#Para inicializar um dicionário usamos:
carro = {
'Fabricante':'Honda',
'Modelo':'NSX',
'Ano':'1992',
'Cor':'Vermelho'
}#Chave:Valor
#Para exibir todos os elementos do dicionario usamos
print(carro)
print('---------------------------')
#Para exibir cada elemento do dicionario usamos
print('Fabricante... |
from rest_framework.serializers import ValidationError
def get_query_switches(
query_params,
switches,
raise_on_none=False,
all_true_on_none=False,
):
active_switches = set()
if query_params:
for switch in switches:
if switch in query_params:
value = query_... |
x = int(raw_input("Dime un numero: "))
y = int(raw_input("Dime otro numero: "))
while x<=y:
if x%2==0:
print x
x += 1 |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Admin
#
# Created: 30/10/2017
# Copyright: (c) Admin 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
... |
from keras.models import Sequential
from keras.layers import Dense
import random
import numpy as np
import matplotlib.pyplot as plt
#目標の関数
f = lambda x: np.sin(x) + 0.3*x**2
#nの数だけランダムにy=sinxを生成
def get_data(n):
x = np.random.uniform(-10, 10, n)
x = np.reshape(x, [n,1])
y = f(x)
return x, y
#
batc... |
# -*- coding:utf-8 -*-
"""
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,
他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向
量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某
个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子
向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续
子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
"""
class Solution:
def FindGreatestSumOfSubArray(self, array... |
import urllib.parse
from pymongo import HASHED
from .ssrn_base import BaseSsrnSpider
class SsrnSpider_3526433(BaseSsrnSpider):
name = 'ssrn_3526433'
# DB specs
collections_config = {
'Scraper_papers_ssrn_com_3526433': [
[('Doi', HASHED)],
[('Title', HASHED)],
'... |
# 8 11
# a b
# a c
# b c
# b g
# a e
# a d
# e d
# h d
# f h
# f e
# f g
# a
# 6 6
# a c
# a b
# c d
# b d
# d e
# e f
# a
n,e=map(int,input().split())
adj_dict={}
#for bfs we need visited array
visited={}
for i in range(e):
x,y=input().split()
if x not in adj_dict:
adj_dict[x]=[y]
else:
a... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import imageio
import os
import sys
import numpy as np
import SimpleITK as sitk
import tensorflow as tf
from tensorflow.contrib.slim.python.slim.nets import inception
from geomstats.special_or... |
"""Classes for melon orders."""
class AbstractMelonOrder:
def __init__(self, species, qty, order_type, tax):
self.species = species
self.qty = qty
self.shipped = False
self.order_type = order_type
self.tax = tax
def get_total(self):
"""Calculate price, including... |
from common import *
def dice_accuracy(prob, truth, threshold=0.5, is_average=True):
batch_size = prob.size(0)
p = prob.detach().view(batch_size,-1)
t = truth.detach().view(batch_size,-1)
p = p>threshold
t = t>0.5
intersection = p & t
union = p | t
dice = (intersection.float().... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 21:09:05 2019
@author: gustavo.fonseca
"""
import numpy as np
import matplotlib.pyplot as plt
#Tarefa 20:
α=0.01
β=0.001
δ=0.007
γ=0.000009
'''Os valores dos parâmetros foram modificados para funcionar com o período de
tempo (0.01 dias por instante)'... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
class Attention_Encoder(keras.layers.Layer):
def __init__(self, time_steps, nb_rnn_units, **kwargs):
super(Attention_Encoder, self).__init__(**kwargs)
self.en_dense_We = keras.layers.Dense(time_steps, u... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
for n in range(100,1000):# 遍历所有三位数
a = n% 10 # 取余找出个位数
b = int(n/100) # 求商找出百位数
c = int(n/100) % 10 # 通过求商取整找出百位和十位,然后求商找出十位
if n == a**3 + b**3 + c**3:
print("%d"%n)
def isIpV4AddrLegal(ipStr):
'''切割IP地址为一个列表'''
ip_split_list = ipStr.strip().split('.')
#... |
# -*- coding: utf-8 -*-
from django.template.response import TemplateResponse
from snippets.views import BaseTemplateView
class TemplateResponse400(TemplateResponse):
status_code = 400
class TemplateResponse403(TemplateResponse):
status_code = 403
class TemplateResponse404(TemplateResponse):
status_c... |
# coding: utf-8
"""
NiFi Rest API
The Rest API provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ... |
from user_group import *
from skill import *
from skill_rate_log import *
from company_manag import *
from job import *
from job_requests import *
|
while True:
x = input("Enter the list (separated by commas) you wish to have reversed; or type 'exit': ")
if x == 'exit': break
try:
print(x.replace(' ','').split(',')[::-1])
except:
print("Please check your formatting and try again!")
|
import scipy.io
import numpy as np
import sys
import numpy as np
import random
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemb... |
__version__ = "1.1.5"
|
def qsort(nums, l, r):
if l > r: return
p = partition(nums, l, r)
qsort(nums, l, p-1)
qsort(nums, p+1, r)
pass
def partition(nums, l, r):
key = r
keyval = nums[r]
while l < r:
while l < r and nums[l] <= keyval:
l += 1
while l < r and nums[r] >= keyval:
... |
列表生成式
#列表 a = [0,1,2,3,4,5,6,7,8,9], 把列表里的每个值加1,怎么实现?
#方法一:
b = []
for i in a:
b.append(i+1)
a = b
print(a)
#方法二:原值修改
for index,i in enumerate(a):
a[index] += 1
print(a)
#方法三
list = map(lambda n:n+1,a)
for i in list:
print(i)
#方法四
a = [i+1 for i in range(10)]
print(a)
#以上就是列表生成
生成器:
1.python中一边... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 13:03:27 2021
@author: ali_k
"""
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time, requests
graph_limit = 10
# Create figure for plotting
fig, axs = plt.subplots(2, 2)
arrx = []
arrbtc = ... |
import os
import asyncio
import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from cogs.utils import checks
from discord.utils import find
class StreamAnnouncer:
"""Configureable stream announcements"""
__author__ = "mikeshardmind"
__version__ = "0.2"
def __init__(sel... |
import pytest
from k8s_utils import *
from s2i_utils import *
from java_utils import *
@pytest.fixture(scope="module")
def single_namespace_seldon_helm(request):
version = get_seldon_version()
create_seldon_single_namespace_helm(request,version)
port_forward(request)
@pytest.fixture(scope="module")
def cl... |
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.Qt import *
class ContentWidget(QWidget):
def __init__(self, parent=None):
super(ContentWidget, self).__init__(parent)
self.palette = QPalette()
self.top_widget = QWidget()
self.down_widget = QWidget()
self.top_w... |
#!/usr/bin/env python3
import db
from flask import Flask, abort
from misaka import html
app = Flask(__name__)
app.config.update(
SECRET_KEY = 'keyval',
DEBUG = True
)
@app.route('/')
def index():
with open('README.md') as readme: return html(readme.read())
@app.route('/<key>/')
@app.route('/<key>/<value>... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import beta
NUM_TRIALS = 2000
BANDIT_PROBABILITIES = [0.2, 0.5, 0.6]
class Bandit:
def __init__(self, p):
self.p = p
self.a = 1
self.b = 1
def pull(self):
return np.random.random() < self.p
def sample(self):
beta_sample = np.random.be... |
import gl, conc
class Rule:
def __init__(self,actualconcept): # an instance represents a single rule to apply for the actual concept
self.actual = actualconcept # index of concept in WM for which we found a rule
self.rule = -1 # index of rule in KB, an IM(g,k) con... |
import json
import pytest
from freezegun import freeze_time
from datetime import datetime, timedelta
from models.users import PasswordRecoveryToken
@freeze_time("2019-09-28 13:48:00")
def test_multiple_user(multiple_users, testing_app):
r = testing_app.get('/api/admin/users')
assert r.status_code == 200
a... |
'''
File which handles the parsing of strings into syntax trees
'''
from syntax import *
from state import *
import re
from robot import Robot
def matchParen(s,i):
l=s[i]
if l=='(':
r=")"
elif l=="{":
r="}"
elif l=="[":
r="]"
elif l=="<":
r=">"
else:
rai... |
from scrapy.spider import BaseSpider
from apple.items import AppleItem
from scrapy.selector import HtmlXPathSelector
import re
class DmozSpider(BaseSpider):
name = "dmoz"
allowed_domains = ["apple.com"]
start_urls = [
"http://store.apple.com/sg/browse/home/specialdeals/mac"#,
#"http://store... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ˅
from behavioral_patterns.template_method.abstract_display import AbstractDisplay
# ˄
class StringDisplay(AbstractDisplay):
# ˅
# ˄
def __init__(self, string):
self.__string = string
# String width
self.__width = len(string)
... |
N = int(input())
*S, = list(input())
A = [chr(i) for i in range(97, 97+26)]
K = 0
for L in range(1,N):
cnt = 0
for alpha in A:
if alpha in S[:L] and alpha in S[L:]:
cnt += 1
K = max(K,cnt)
print(K)
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
t=int(input())
for i in range(t):
n=int(input())
s=input()
x="2020"
ans=[0]*4
a=0
b=n-1
for p in range(4):
if s[p]==x[p]:
ans[p]=1
else:
break
for p in range(4):
if s[b]==x[3-p]:
a... |
#import sys
#input = sys.stdin.readline
# from bisect import bisect_left
def main():
K = int(input())
ans = 0
A = [i**2 for i in range(10**3)]
for i in range(1, K+1):
L = K//i
for j in range(1,L+1):
ans += L//j
print(ans)
if __name__ == '__main__':
main()
|
from flask import Flask, render_template, request
import os.path
import json
import requests
from pyGTrends import pyGTrends
app = Flask(__name__)
global connection
global counter
global popList
connection = None
counter = 0
popList = None
@app.route("/", methods=['GET', 'POST'])
def index():
global connection
... |
from interface import admin_interface
def frozen():
while True:
frozen_user = input('请输入要冻结的用户名:')
flag,msg = admin_interface.frozen_interface(
frozen_user
)
if flag:
print(msg)
break
else:
print(msg)
continue
def ... |
"""
Module for holding constants (and some variables with "fixed" values) used
all over the program.
"""
import os.path
import glib
from constant_constants import *
# Path of the program (bad assumption)
TV_PATH = "/usr/bin/tunesviewer"
TV_VERSION = "1.5" #also needs changing in debian conf file somewhere
# Directo... |
from app.database.cache import get_from_cache, add_to_cache
from app.database.database import execute_query
def get_teen_pregnancy_by_state(year):
query = get_query(year)
data = get_from_cache(query)
print("DB Query: " + query)
if data is None:
data = execute_query(query)
add_to_cache... |
#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
from os import listdir
from os.p... |
from Login.NewContract import *
from selenium import webdriver
driver = webdriver.Chrome()
# driver.maximize_window()
driver.implicitly_wait(10)
test_user_login(driver)
# test_contract2(driver)
|
import sys
input = sys.stdin.readline
def find(A,x):
p = A[x]
if p == x:
return x
a = find(A,p)
A[x] = a
return a
def union(A, x, y):
if find(A,x) > find(A,y):
bx, by = find(A,y), find(A,x)
else:
bx, by = find(A,x), find(A,y)
A[y] = bx
A[by] = bx
def main(... |
Name:Siddhant Pawar
State:Maharashtra
|
# Generated by Django 2.2.1 on 2019-05-25 23:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web_api', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='eventplaceseattype',
name='seat_type... |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import gc
import os
import math
import time
from tqdm import tqdm
from vdgnn.utils.eval_utils import process_ranks, scores_to_ranks, get_gt_ranks
from vdgnn.utils.metrics import NDCG
class Trainer(object):
def __ini... |
# Generated by Django 3.2.7 on 2021-10-03 19:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apis', '0002_auto_20211004_0110'),
]
operations = [
migrations.AlterModelOptions(
name='jobs',
options={'verbose_nam... |
from django import forms
from finalCristianGarcia.models import Reserva
class DateForm(forms.DateInput):
input_type = 'date'
class ReservaForm(forms.ModelForm):
class Meta:
model = Reserva
fields = "__all__"
widgets= { 'fecha_de_ingreso': DateForm() , 'fech... |
from django.shortcuts import render, HttpResponseRedirect, get_object_or_404, HttpResponse, reverse, Http404
from player.models import Player
from question.models import Question, Answer
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from allauth.socialacc... |
from django.shortcuts import render, render_to_response, redirect
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib import auth
from django.con... |
import logging
import os
import bottle
import json
import urllib2
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
import zipfile
import uuid
import json
# Azure libraries
from azure.storage import *
# Bottle libraries
from bottle import route, template, request, redirect, static_file
c... |
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2017. Authors: see NOTICE file.
# *
# * 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 sys
from rosalind_utility import parse_fasta
TI_DICT = {"A": "G", "G": "A", "C": "T", "T": "C"}
def ti_tv_ratio(string1, string2):
''' Calculate Ti/Tv ratio
:param string1: string 1
:param string2: query string
:return: Ti/Tv ratio (float)
'''
num_ti = 0
num_tv = 0
for sym1, sy... |
"""Example of using hangups to retrieve suggested contacts."""
import hangups
from common import run_example
async def retrieve_suggested_contacts(client, _):
request = hangups.hangouts_pb2.GetSuggestedEntitiesRequest(
request_header=client.get_request_header(),
max_count=100,
)
res = aw... |
def do():
new_list = []
new_list.append('строка')
new_list.append(2134)
new_list.append(('кортеж', 'строк'))
for i in range(len(new_list)):
print(f'{i} элемент списка содержит: {new_list[i]}. Данные относятся к типу {type(new_list[i])}')
if __name__ == '__main__':
do()
|
"""private_message
Revision ID: e72ff320d68f
Revises:
Create Date: 2018-07-27 13:22:34.036683
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e72ff320d68f'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto ge... |
from appium_advance.unittest.myunit import StartEnd
from appium_advance.page_object.loginView import LoginView
import unittest
class TestLogin(StartEnd):
def test_login_zxwcs(self):
l = LoginView(self.driver)
l.login_actiopn("自学网测试", "wyc1063983073")
def test_login_zxw2017(self):
l =... |
FILES_DIR = '/files/'
DEFAULTCERTS_DIR = FILES_DIR + 'certs/default/'
TMP_FILES_DIR = '/files/tmp/'
INPUT_APK_DIR = TMP_FILES_DIR + 'input_apks/'
COMMON_TEMPLATES_DIR = '/common/templates'
|
from rest_framework import serializers
from django.contrib.admin.models import LogEntry
from .models import Item, Variant
class LogsSerializer(serializers.ModelSerializer):
variants = serializers.SerializerMethodField()
def get_variants(self, obj):
variant = obj.variant_set.all()
variant_seri... |
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
results = [[]]
nums = sorted(nums)
k = 0
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
k += 1
else:
k = 0
nres = results[:... |
# https://leetcode.com/problems/rotate-image/discuss/146406/5-Line-Python-Solution
#
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
assert len(matrix) == len(matrix[... |
#!/usr/bin/python3
"""unit tests for max_integer"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""unit tests for max integer"""
def test_ordered_list(self):
"""Test an ordered list of integers"""
ord_list = [1, 2, 3, 4]
... |
# Generated by Django 3.1.4 on 2020-12-17 00:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='doctor',
name='Nusuarios',
),
]
|
import logging
import torch
from typing import Tuple
LOGGER = logging.getLogger(__name__)
# TODO: restructure the code to not use the decoder
def word_error_rate(model_out: torch.Tensor, batch: Tuple, decoder=None) -> float:
"""
Calculate word error rate based on the model output and groundtruth.
Args:... |
import re
n = input()
m = int(input())
a = []
for i in range(m):
room_number = input()
if re.search(n, room_number) is None:
a.append(room_number)
if not a:
print("None")
else:
for i in range(len(a)):
print(a[i])
|
from pyramid.scaffolds import PyramidTemplate
class PyramidFoundationTemplate(PyramidTemplate):
_template_dir = 'pyramid_foundation_scaffold'
summary = 'Pyramid scaffold to extend project with Foundation support'
|
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix or len(matrix[0]) == 0:
return []
row = 0
col = 0
arr = []
m = len(matrix)
n = len(matrix[0])
times = m*n
for i in range(times):
arr.append(matrix... |
#!/usr/bin/python
import sys
import fileinput
p = int(sys.argv[1])
q = int(sys.argv[2])
files = ['out.'+str(x) for x in range(p,q+1)]
sumTotal = 0
for line in fileinput.input(files):
sumTotal = sumTotal + int(line)
outputFile = open('out.final','w')
outputFile.write(str(sumTotal))
outputFile.close()
|
#!/usr/bin/env python3
import estimation_n_grams
import unittest
class TestLinearInterpolation(unittest.TestCase):
def setUp(self):
self.corpus1 = "<S> HELLO MY DEAR FRIEND </S>"
self.corpus2 = "<S> HELLO MY DEAR FRIEND </S>\n<S> HOW ARE YOU MY FRIEND </S>"
self.corpus3 = "<S> THIS THIS I... |
"""defines the network architecture
given the limited number of images in the train set a pretrained network
will be used for the feature extraction...
the base model in considareation is the "mobilenet_v2"
https://pytorch.org/hub/pytorch_vision_mobilenet_v2/
"""
import numpy as np
from PIL import Image
import torch
... |
from rest_framework import serializers
from artists.models import Artist
class ArtistSerializer(serializers.ModelSerializer):
class Meta:
model = Artist
fields = [
"id",
"name",
"bio",
"role",
"public_url",
"public_twitter",
... |
from timeit import default_timer as timer
import numpy as np
#data = np.random.normal(0, 1, 10000)
data = np.arange(12000)
a = 0
s = timer()
for k in range(0 , data.size):
a += data
e = timer()
print('execution time of for = ' + str(e-s) + 's')
a = 0
k = 0
e_1 = timer()
while k < data.size:
a += data
k += ... |
# 581. Shortest Unsorted Continuous Subarray
#
# Given an integer array, you need to find one continuous subarray
# that if you only sort this subarray in ascending order,
# then the whole array will be sorted in ascending order, too.
#
# You need to find the shortest such subarray and output its length.
#
# Examp... |
def build(dataset_name, model_config):
if dataset_name == "Cifar10":
from .cifar import cifarTrain
return cifarTrain(model_config)
elif dataset_name == "imagenet":
from .imagenet import imagenetTrain
return imagenetTrain(model_config)
elif dataset_name == "WikiText2":
... |
import chess
import book
book.LoadOpeingBook()
board = chess.Board()
import AI
import boardset
# str=input("input: \n")
# print(str)
#print(board)
# 使用dict来初始化board_info
# 其中主要有black_queens,black_rooks,white_materials,white position,black_position,hash值,相当于将以下变量打包
board_info={}
boardset.board_start(board, board_i... |
#Tuples
x = 4,5,6,7,8
y = (4,5,6,7,8)
#List
z = [1,2,3,45,6,7]
def exampleFunc():
return 15,6
a,b = exampleFunc()
print(a)
print(b)
|
from os import name
from bs4.element import Tag
import re
import inspect
import json
import requests
from bs4 import BeautifulSoup
from contextlib import suppress
class Operation:
"""
"""
def __init__(self):
self.name = ''
self.direct_url = ''
self.related_url = ''
self.ext... |
#!/usr/bin/env python3
from collections import defaultdict
class CallCount:
"""
This module will return how many times
this module was called with same parameters
"""
def __init__(self):
self._count = defaultdict(int)
def __call__(self, argument):
self._count[argument] += 1
... |
#Dictionary is a key value pairs
p = {'apple':4,'banana':9,'orange':12,'pineapple':20}
print(p['apple']) #index
print(p['orange'])
print(p)
studentid = {
"1" : "Mehedi Amin",
"2" : "hassan",
"3" : "kamal",
}
print(studentid["1"])
|
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
# Create your models here.
class Character_sheet(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
name = models.CharField(max_length=40)
GENDER_CHOICES = (
('M', 'Mężczyzna'... |
# Generated by Django 3.2.8 on 2021-10-30 23:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pr_employee', '0002_alter_company_table'),
]
operations = [
migrations.RenameField(
model_name='employee',
old_name='first_n... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-07-11 17:21
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('store', '0005_generalproduct_gp_description'),
]
... |
from unittest import TestCase, main
from ... import UndirectedGraph
class TestGetVertexWeight(TestCase):
def setUp(self) -> None:
self.g = UndirectedGraph(
edges={("a", "b"): 1, ("b", "c"): 2, ("e", "f"): 3},
vertices={"a": 10, "b": 20, "c": 30, "e": 40},
)
def test_g... |
# Generated by Django 2.2.2 on 2020-06-08 12:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('jazz', '0032_remove_lineup_date'),
]
operations = [
migrations.DeleteModel(
name='Lineup',
),
]
|
class Solution(object):
def largestRectangleArea(self, height):
# An O(n) algorithm. (Each element is pushed and popped into/from the
# stack at most once.)
# Add a sentinel to help with cleaning the stack.
height_with_sentinel = height[:] + [0]
max_area = 0
# Recta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.