text stringlengths 38 1.54M |
|---|
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
res = 0
for n in range(1, len(arr)+1, 2):
for i in range(len(arr)-n+1):
res += sum(arr[i:i+n])
return res
|
import logging
from fastapi import FastAPI
from starlette.staticfiles import StaticFiles
from app.api import ping, summaries
from app.db import init_db
from app.views import home
log = logging.getLogger("uvicorn")
def create_application() -> FastAPI:
application = FastAPI()
application.mount("/app/static",... |
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import config
from flask_login import LoginManager
from sqlalchemy import MetaData, func
from flask_cors import CORS
# For... |
from __future__ import print_function
import boto3
import json
print('Invoking updatePizzaMenu function')
def lambda_handler(event, context):
print ('printing event and context')
print (event)
print (event['menu_id'])
table = boto3.resource('dynamodb').Table('Menus')
table.update_ite... |
# Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.
# Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор.
# Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-06-03 02:40
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import leprikon.models.fields
class Migration(migrations.Migration)... |
from __future__ import print_function
import subprocess
import os
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('base',
help='location of directory containing larpix-scripts, '
'larpix-control, etc.')
args = parser.parse_args()
def git_describe(directory):
curre... |
from app import db
from app.main import bp
from flask import render_template, request, redirect, jsonify
from flask_login import login_required, current_user
from app.main.forms import CreateOrder
from app.models import OrderTypes, Tag, Order
from werkzeug.utils import secure_filename
from config import Config
import o... |
# card data comes from:
# http://hearthstonejson.com/
# last updated: August 7th, 2014
# mechanics: Taunt, Stealth, Divine Shield, Windfury, Freeze, Enrage,
# HealTarget, Charge, Deathrattle, Aura, Combo, AdjacentBuff, Battlecry,
# Poisonous, Spellpower
from json import loads
from card_types import MinionCard, SpellCa... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import defaultdict
import codecs, re
def load_analogy_pair(fname):
ap_dict = defaultdict(list)
with codecs.open(fname, 'r', encoding='utf-8', errors='ignore') as f:
for i, line in enumerate(re.split('[\r\n]+', f.read())):
if l... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 15 00:52:59 2021
@author: glenn
"""
#%% - import libraries
import pandas
import time
import pickle
from local_module import fcts
#%% input / output paths
RAW_CASE_DATA = 'raw_cases/conposcovidloc.csv'
SORTED_CASES = 'pickled_cases/sorted_data_per... |
from pwn import *
#context.arch = "amd64"
p = remote("chall.pwnable.tw",10201)
#p = process("./death_note")
def add(idx,name):
p.sendlineafter("Your choice :","1")
p.sendlineafter("Index :",str(idx))
p.sendlineafter("Name :",str(name))
def show(idx):
p.sendlineafter("Your choice :","2")
p.sendline... |
{'application':{'type':'Application',
'name':'StackWidgetsTest',
'backgrounds': [
{'type':'Background',
'name':'bgWidgets',
'title':'Widgets Test',
'size':(800, 600),
'menubar': {'type':'MenuBar',
'menus': [
{'type':'Menu',
'nam... |
# Generated by Django 2.1.1 on 2018-10-08 08:36
import DjangoUeditor.models
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('polls', '0012_customerappraise'),
]
operations = [
... |
import time
import queue
import threading
from SQS import *
ingredientes = {"Guacamole": 500, "Cebolla": 500, "Cilantro": 500, "Frijoles": 500, "Salsa": 500}
responseTimes = {"Pequeño": [], "Mediano": [], "Grande": []}
tortillas = [500, 500, 500]
# Global queues
queue_asada_tripa = queue.Queue()
queue_adobada_lengua ... |
# Display all patterns in Golly's Patterns folder.
# Author: Andrew Trevorrow (andrew@trevorrow.com), March 2006.
import golly as g
import os
from os.path import join
from time import sleep
# ------------------------------------------------------------------------------
def slideshow ():
oldalgo = g.getalgo()
... |
"""Merge sort algorithm."""
def merge_sort(a_list):
"""Use MS to sort the provided list and return it."""
if not isinstance(a_list, list):
raise TypeError("Only list is a valid input type!")
if len(a_list) < 2:
return a_list
parts = [[i] for i in a_list]
while len(parts) > 1:
... |
import urllib.request
import os
import sys
def downloadImages(strQueryString, arrUrls):
for url in arrUrls:
downloadImage(strQueryString, url)
def downloadImage(strQueryString, url):
try:
strPath = setup(strQueryString)
print(f"Downloading {url} to {strQueryString}")
image_na... |
import time
print("Welcome to MY ATM")
print("Swipe Card")
amount=1000000
o="4078"
print("_________________")
p=input("enter pin")
print("Verifying.......!!")
time.sleep(3)
if p==o:
print("1.Cash Withdrawl")
print("2.Check enquiry")
print("3.Balance enquiry")
print("4.Print receipt")
print("5.... |
import numpy as np
import matplotlib.pyplot as mp
import time
from NeuralNetwork import Neural_Network
fileStr = 'C:\\Users\\WahSeng\\Desktop\\Neural Network Tutorial\\TrainingData.txt'
# Open the file and read the contents
data = np.genfromtxt(fileStr)
# Load data
tin = data[:,0:2]
tout = data[:,2:3]
# Normalize... |
# word = list(map(str, input()))
# alpha = list('abcdefghijklmnopqrstuvwxyz')
# alpha_list = [-1 for i in range(len(alpha))]
# for i in range(len(word)):
# if alpha_list[alpha.index(word[i])] == -1:
# alpha_list[alpha.index(word[i])] = i
# for i in alpha_list:
# print(i, end= ' ')
word = input()
alpha... |
from serial import Serial
import RPi.GPIO as GPIO
import time
import paho.mqtt.client as mqtt
ser=Serial("/dev/ttyACM0",9600) #change ACM number as found from ls /dev/tty/ACM*
ser.baudrate=9600
def blink(pin):
GPIO.output(pin,GPIO.HIGH)
time.sleep(1)
GPIO.output(pin,GPIO.LOW)
time.sleep(1)
return
def disp... |
"""
This module describe data model for "tag_association" table
tag_association table filled automatically by SQLalchemy.
It provides many to many relation between restaurant and tag
"""
from sqlalchemy import (
Column,
Integer,
ForeignKey,
)
from sqlalchemy.orm import relationship
from .meta import Base
... |
from django.conf.urls import url
from mrbelvedereci.github import views as github_views
urlpatterns = [
url(r'^$', github_views.repo_list),
url(r'^repo/(?P<owner>\w+)/(?P<name>[^/].*)/branch/(?P<branch>.*)$', github_views.branch_detail),
url(r'^repo/(?P<owner>\w+)/(?P<name>[^/].*)/commit/(?P<sha>\w+)$', g... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from shop.config import DevConfig
from flask_migrate import Migrate
app=Flask(__name__)
app.config.from_object(DevConfig)
db=SQLAlchemy(app)
bcrypt=Bcrypt(app)
login_manager=LoginManage... |
from django.shortcuts import render,redirect, get_object_or_404
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.decorators import permission_required
from ..views import staff_member_required
from django.contrib.sites.shortcuts import get_current_site
from django.template.response i... |
__author__ = "Markus Reiter"
__copyright__ = "(c) Markus Reiter 2022"
__license__ = "MIT"
import shutil
from subprocess import PIPE, Popen
from proxmoxer.backends.command_base import CommandBaseBackend, CommandBaseSession
class LocalSession(CommandBaseSession):
def _exec(self, cmd):
proc = Popen(cmd, st... |
import sys
import os
from distutils.core import setup, Extension
incDirList= []
libDirList= []
libList= []
defList= []
undefList= []
otherCompileFlags= []
otherLinkFlags= []
if 'CFLAGS' in os.environ:
cflags= os.environ['CFLAGS']
else:
cflags= ''
words= cflags.split()
for word in words:
if word.startswit... |
import sys
import math
from collections import defaultdict
import numpy as np
LOG_PATH_random="summary_results.txt"
POUR_PLOT_deficit="plot_deficit"
POUR_PLOT_throughput="plot_throughput"
POUR_PLOT_APs_std_load="plot_APs_std_load"
POUR_PLOT_APs_maximum_load="plot_APs_maximum_load"
POUR_PLOT_clients_Nb_deficit="p... |
import os
class Console():
def write_title(self,title):
self.write_header(title,1)
def write_header(self,msg,level=1):
output=msg
if level==1:
output= "*" * 50 + "\n" + "*" * 50 + "\n" + " " + msg + "\n" + "*" * 50 + "\n" + "*" * 50 + "\n"
if level==2:
... |
import pwd
import grp
larsx = pwd.getpwnam('larsx')
print larsx
print """
Name: {}
UID: {}
Home: {}
Shell: {}
""".format(larsx.pw_name, larsx.pw_uid, larsx.pw_dir, larsx.pw_shell)
group = grp.getgrgid(larsx.pw_gid)
print """
Group: {}
GID: {}
""".format(group.gr_name, group.gr_gid)
|
# -*- coding: utf-8 -*-
"""
Title:
Description:
Author: haithem ben abdelaziz
Date:
Version:
Environment:
"""
import sc_stbt
import time
import stbt
def step1():
"""
steps: 1-go to home
2-open library menu
3-open movies menu
4-searching a free video
... |
import os
from svmutil import svm_read_problem, svm_train, svm_save_model
cdir = os.path.abspath('.') + "/"
def train_svm_model():
y, x = svm_read_problem(cdir + 'train_pix_feature_xy.txt')
model = svm_train(y, x)
print type(model)
svm_save_model(cdir + 'model', model)
if __name__ == "__main__":
t... |
# Import itemgetter from the operator module
# Now create a variable named sorted_fruit that used sorted() and itemgetter() to sort fruit_list by the second item in each tuple
from operator import itemgetter
fruit_list = [
('apple', 2),
('banana', 5),
('coconut', 1),
('durian', 3),
('elderberries'... |
# coding: utf-8
#
# Copyright 2022 The Oppia Authors. All Rights Reserved.
#
# 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 requi... |
# pyroulette in development. dave ikin 2021
# roulette simulator
from sys import exit
from random import choice
def roulette():
numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,
19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]
x = choice(numbers)
print(f' {x} wins.')
... |
# переработка фотки лица в набор координат
import sys
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
BLOCKS_COUNT = 4
"""
Объявляем параметры которые нужны для обучения
face_params = (x, y, w, h) координаты и размеры найденного лица
eyes_params = (x, y, w, h) координаты и размеры п... |
import pandas as pd
# specify the keywords to look for
keywords = [
"public review",
"public hearing",
"vote",
"public participation"
]
# open the NYC city charter text file exported from
# http://library.amlegal.com/nxt/gateway.dll/New%20York/charter/newyorkcitycharter?f=templates$fn=default.htm$3.0$... |
# -*- coding: utf-8 -*-
from django import forms
class StudentInfoForm(forms.Form):
id = forms.CharField(max_length=10)
contact = forms.CharField(max_length=11)
name = forms.CharField(max_length=20)
gender = forms.IntegerField()
college = forms.CharField(max_length=50)
major = forms.CharField(m... |
#! /usr/bin/python
#coding=utf-8
import socket
import ParseData
import readxml
import struct
import time
import ConfigParser
HOST = ''
PORT = 50001
ADDR = (HOST, PORT)
BUFFSIZE = 65535
def xmlparse(fname):
configdict = readxml.ConvertXmlToDict(fname)
#data = struct.pack('!B3sBHB2I', 1, '234', 0x00, 6, 7, 8,... |
import os
import itertools
import numpy as np
import cPickle
from collections import Counter
from sklearn.neighbors import NearestNeighbors
src_tag = 'val'
base_dir = '/media/researchshare/linjie/data/'
target_path = base_dir + 'snapchat/features/vgg.bin'
src_path = base_dir + 'dreamstime/features/vgg_'+src_tag+'.bin'
... |
# Client that doesn't use the Name Server. Uses URI directly.
from __future__ import print_function
import sys
import Pyro4
if sys.version_info < (3, 0):
input = raw_input
uri = input("Enter the URI of the quote object: ")
with Pyro4.core.Proxy(uri) as quotegen:
print("Getting some quotes...")
print(qu... |
from flask import Flask, jsonify, request, current_app, send_from_directory
import twitter_to_movie as t2m
from pymongo import MongoClient
import datetime
app = Flask(__name__, static_url_path='')
@app.route("/", methods=["GET"])
def send_index():
return send_from_directory('', 'index.html')
@app.route("/output.mp4... |
def SumFunc(num):
'''Take in integer i and return sum of all multiples of 3 and 5 below it'''
answer = 0
for i in range(0,num):
if i % 3 == 0 or i % 5 == 0:
answer += i
return answer
print(SumFunc(1000))
|
import json
import torch
import datetime
import time
import argparse
import numpy as np
import torch.nn as nn
import traceback
from collections import defaultdict
from utils.word_embedding import WordEmbedding
from models.agg_predictor import AggPredictor
from models.col_predictor import ColPredictor
from models.desas... |
import numpy as np
from scipy.optimize import leastsq
import pylab as plt
def sinR():
f=open("12_31_15.csv",'r')
lineNum=1
timeA=[]
voltageSet=[]
for line in f:
if lineNum==1:
#station=line.split(",")[0]
#statName=line.split(",")[1]
lineNum+=1
elif... |
import doublyPeriodic
import numpy as np; from numpy import pi
import time
class model(doublyPeriodic.numerics):
def __init__(
self,
name = "linearizedBoussinesqEquationsExample",
# Grid parameters
nx = 128,
Lx = 2.0*pi,
ny = None,
... |
from decimal import Decimal
from functools import total_ordering
import re
import itertools
from datetime import date
from dateutil.relativedelta import relativedelta
from helper import keyify, as_number
class Service:
EXPECTED_QUARTERS = [
# worked through oldest to newest to calculate %age changes
... |
#!/usr/bin/env python
#must run iptables -I INPUT -j NFQUEUE --queue-num 0 (use for packets whose destination is your computer)
#must run iptables -I OUTPUT -j NFQUEUE --queue-num 0 (use for packets whose source is your computer)
#>> must run iptables -I FORWARD -j NFQUEUE --queue-num 0 (use for packets being rout... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
datasets = pd.read_csv('/home/aman/kans/work_folder/malware456.csv')
Y = datasets.iloc[:, 456].values
X = datasets.iloc[:, 0:456].values
from sklearn.model_selection import train_test_split
X_Train, X_Test, ... |
def longestPeak(array):
longestPeak = 0
i = 1
while i < len(array)-1:
left = array[i-1]
curr = array[i]
right = array[i+1]
peakFound = left < curr and curr > right
if not peakFound:
i += 1
continue
... |
number = 2 + 3 * 4 #14
print(number)
number = number + 2 #16
print(number)
number += 2 # 18
print(number)
number *= 2 # 36
print(number)
number /= 2 # 18
print(number)
number -= 2 # 16
print(number)
number %= 2
print(number) |
#!/bin/python2
### This ncfile is set up to compare the Mass Extinction Coefficients with
### internal vs. external mixing
from netCDF4 import Dataset
import numpy as np
#import scipy.ndimage
#import types
import sys as sys
### Read data files
volspkd = 10
# Open netCDF file
ncfile_3im = 'bcm-sul-oc-im.nc'
ncfile_... |
class Solution:
def reverse(self, x):
print(0.75%10)
a=str(x)
if a[0]=='-':
b=a[::-1]
if (int(b[:-1:])*-1) < -2147483648:
return 0
else:
return (int(b[:-1:])*-1)
else:
if (int(a[::-1]))>2147483648:
... |
#WAP to accept a number and check if it's even or odd without using arithmetic operators
def IsOdd(num):
if((num & 1) == 0):
return False
else:
return True
def main():
inputNum = eval(input('Please enter a number: '))
print('Number is Odd: ', IsOdd(inputNum))
if __name__ == '__main__'... |
# Find the greatest common divisor of two numbers using recursion.
def gcd(n1, n2):
if n1 > n2:
if n1 % n2 == 0:
return n2
else:
return gcd(n2, n1 % n2)
else:
if n2 % n1 == 0:
return n1
else:
return gcd(n1, n2 % n1)
print(gcd(24, ... |
#!remote-logger/bin/python
from flask import Flask, request, abort, jsonify
from collector_logger import logger
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
@app.route('/log', methods=['POST'])
def add_record():
if not request.json or 'content' not in request.json:
abo... |
import os
from flask import g, current_app
# ...
current_app.config['SQLALCHEMY_DATABASE_URI'] = \
'sqlite:////' + os.path.join(g.app.root_path, 'data.db') |
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Jun 17 2015)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
impo... |
import json
import numpy as np
from SQLNet.utils import run_lstm, col_name_encode
import tensorflow as tf
import tensorflow.keras.layers as layers
class SelPredictor(tf.keras.Model):
def __init__(self, N_word, N_h, N_depth, max_tok_num, use_ca):
super(SelPredictor, self).__init__()
self.use_ca = ... |
#!/usr/bin/env python3
################################################################################
## ##
## This file is part of NCrystal (see https://mctools.github.io/ncrystal/) ##
## ... |
from tkinter import *
from tkinter import filedialog
def saveFile():
file = filedialog.asksaveasfile(initialdir="C:\\Users\\Marcus\\Documents\\python files",
defaultextension='.txt',
filetypes=[
... |
def pets(petlist):
try:
with open(petlist) as furry:
meowbarks = furry.read()
except FileNotFoundError:
pass
else:
print(meowbarks)
FreimanPets = ['text_files/cats.txt', 'text_files/dogs1.txt']
for petnames in FreimanPets:
pets(petnames) |
"""
The data points are uniformly distributed on a unit sphere.
To generate these 3-dimensional points, we first generate standard
normally distributed points as vectors lying in 3D space, and then
normalize these vectors (X:= X / ||X||) to make it lie on a sphere
(S^2) which acts as an embedded manifold in 3-D ambient... |
import threading
import datetime
import re
import sys
import time
def thread(input,thread_id):
for i in range(6):
tp = ThreadPool()
self_timer = tp.pool.get(thread_id)
if self_timer==-1:
exit()
print('hello+'+str(input))
time.sleep(1)
if i == 2:
... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
# @Time :2019-11-06 16:55
# @Author: cd
# @FileName:pye_001.py
# @Copyright: @2019-2020
# 使用 time 模块的 sleep() 函数。 |
from horst import Horst
from horst.versioning import bumpversion, UpdateBumpConfig, CreateBumpConfig, RunBumpVersion, _render_int_bump_config
from os import path
import horst.versioning
import pytest
@pytest.fixture(autouse=True)
def set_up_horst():
horst = Horst(__file__)
yield
horst._invalidate()
here... |
import rospy
from std_msgs.msg import String
rospy.init_node('PrimNo')
def matricCallBack(msg):
soma = msg.data
print(soma)
def timerCallBack(event):
msg = String()
msg.data = '2017016162'
pub.publish(msg)
pub = rospy.Publisher('/topico1', String, queue_size=1)
rospy.Timer(rospy.Duration(1), timer... |
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.db import models
from django.db.models.signals import pre_save, post_delete
from django.dispatch import receiver
from student.models import Student
from group.models import Group
# Create your models here.
TYPE... |
from airflow import DAG
from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator
from airflow.utils.dates import days_ago
args = {
"project_id": "etl-1012105319",
}
dag = DAG(
"etl-1012105319",
default_args=args,
schedule_interval="@once",
start_date=days_ago(1),
de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import getopt
import os.path
import re
import sys
class Formatter():
@staticmethod
def format(str):
# Handle {_xxx_} for italics.
m = re.match(r'^(.*)\{_(.+?)_\}(.*)$', str)
if m:
pre = m.group(1)
content = m.group(2)
post = m.group(3)
str = Formatter.... |
#!/usr/bin/env python
# Python libraries
import os
import cgi
import urllib
import json
# Google App Engine api
from google.appengine.api import users
from google.appengine.ext import ndb
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api im... |
# Execercise form w3resources
# Link => https://www.w3resource.com/python-exercises/list/
from random import randint
lists = []
for i in range(1, 15):
num = randint(1, 100)
lists.append(num)
# 1. Write a Python program to sum all the items in a list
print(lists)
print("Sum of list is " + str(sum(lists)))
# 2.... |
import pytest
import unittest
from sqlparse.experiments import view_handler as v
sql='select v1.name as nom,V2.code,count(*) from view1 as v1, view2 as v2 where v1.code like "12345" group by nom;'
query=sqlparse.parse(sql)
class TestGeneratedView(unittest.TestCase):
view=v.GeneratedView({},{},{})
def test_root_... |
from django.conf import settings
from django.db import models
from mongoengine import *
connect(settings.MONGODB_DATABASE)
class Profile(models.Model):
uuid = models.CharField(max_length=36, unique=True, blank = False, null = False, db_index = True)
def getDBName(self):
return "User_" + str(self.uui... |
from typing import Optional, Iterator, Iterable, FrozenSet, Tuple, List, Dict
import io
from math import ceil, log as mlog
from itertools import chain
from pysmt.environment import Environment as PysmtEnv
from pysmt.formula import FormulaManager
from pysmt.fnode import FNode
import pysmt.typing as types
from pysmt.sho... |
import pandas as pd
from Titanic.titanic_lib import *
def run_column_boxplot(input_file, column, by=None):
df = pd.read_csv(input_file)
return column_boxplot(data=df, column=column, by=by)
def run_column_barchart(input_file, column, by):
df = pd.read_csv(input_file)
return column_barchart(data... |
# %%
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import sys
sys.path.insert(0, os.path.dirname('.'))
sys.path.insert(0, os.path.dirname('../'))
from data_utils import video_to_frames
from data_utils import metadata_loader
from data_uti... |
from django.shortcuts import render,HttpResponse
from django.http import HttpResponseRedirect
def global_data(view_func):
def login_check(request,code=0):
return view_func(request)
return login_check |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^auth$', views.vk_auth, name='vk_auth'),
]
|
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
# @param {Interval[]} intervals
# @param {Interval} newInterval
# @return {Interval[]}
def insert(self, intervals, newInterval):
start = newInterval.start
end = newInterval.end
t = ''
ans = []
if len(intervals)... |
# Examples from Mining the Social Web, section 8
import webbrowser
import requests # pip install requests
from BeautifulSoup import BeautifulSoup # pip install BeautifulSoup
# XXX: Any URL containing a geo microformat...
URL = 'http://en.wikipedia.org/wiki/Kaunas'
req = requests.get(URL, headers={'User-Agent': "... |
import subprocess
from io import StringIO
import numpy as np
from pyorca import orcaconfig as config
class OrcaWrapper:
def __init__(self, jobname, elements, theory, basis, *args, parallel=None):
self.elements = elements
self.jobname = jobname
if 'mp2' in theory.lower():
args... |
class Hero:
#class variabel
jumlah_hero = 0
def __init__(self, inputName, inputHealth, inputPower, inputArmor):
#instance variabel
self.name = inputName
self.health = inputHealth
self.power = inputPower
self.armor = inputArmor
Hero.jumlah_hero += 1
#void function, method tanpa retu... |
from django.db import models
from django.contrib.auth.models import AbstractUser
class TTUser(AbstractUser):
bio = models.TextField(max_length=500, blank=True)
portrait = models.ImageField(upload_to='profile_pictures/')
reference = models.CharField(max_length=50, default='User Reference')
def __str__... |
from linkedlist import LinkedList
def delmiddle(n,i):
current = n.start
prev = None
while current:
if current.value == i:
prev.next = current.next
n.length -= 1
return True
else:
prev = current
current = current.next
return False
... |
import flask
from flask import request, jsonify
# from flaskext.mysql import MySQL
from flask_jwt import JWT, jwt_required
from werkzeug.security import safe_str_cmp
from flasgger import Swagger
# SQLITE3 setup for Flask
import sqlite3 as sql
app = flask.Flask(__name__)
app.config["DEBUG"] = True
app.config['SECRET_K... |
__version__ = '0.5'
from .antenna import *
from .topica import TopicaResult
from .digital_twin import DigitalTwin
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-04-16 03:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0001_initial'),
]
operations = [
migrations.AddField(
mod... |
# Example script to run methods on sample data
# Code modified from the version by Byron Yu byronyu@stanford.edu, John Cunningham jcunnin@stanford.edu
from extract_traj import extract_traj, mean_squared_error, goodness_of_fit_rsquared, getPredErrorVsDim
from data_simulator import load_data
import numpy as np
from cor... |
from typing import List
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# 完全背包
# 最少值
dp = [None] * (amount + 1)
dp[0] = 0
for x in coins:
for i in range(x, amount + 1):
if dp[i - x] is not None:
if d... |
"""Miscellaneous tools and shortcuts"""
from datetime import datetime
from functools import wraps
from dataclasses import asdict
from toolz import excepts
def onlyone(iterable):
"""get the only item in an iterable"""
value, = iterable
return value
def replace(instance, **kwargs):
"""replace values ... |
n = int(input())
matrix = [list(map(int, input().split())) for _ in range(n)]
blue, white = 0,0 #blue, white count
def square(x, y, n):
global matrix, blue, white
check = True
first_color = matrix[x][y]
for i in range(x, x+n):
if not check: break
for j in range(y, y+n):
if... |
from setuptools import setup, find_packages
exec(open("./src/pytest_vts/version.py").read())
with open("PyPI_LONGDESC.rst") as fd:
long_description = fd.read()
keywords = ("pytest plugin http stub mock record responses recorder "
"vcr betamax automatic")
setup(
name="pytest-vts",
version=__v... |
# This program solves Ackermann's function
# Ackermann's function
def ackermann(m, n):
if m == 0:
return n + 1
elif n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n - 1))
# The main function
def main():
print(ackermann(2, 5))
# Cal... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 12:42:19 2020
@author: tomasla
"""
from optimize import optimize
import argparse
import os
import time
# %% ArgParse
parser = argparse.ArgumentParser('Gradient Descent based Structure Optimization')
parser.add_argument('-d', '--domain', metavar=... |
###################################################
## sobel.py : utility script for applying a sobel filter to all images in a folder
## @author Luc Courbariaux 2018
###################################################
import argparse
parser = argparse.ArgumentParser(description='gets all images in INPUT folder, appl... |
import scrapy
import os
import subprocess
import urlparse
from datetime import datetime, timedelta
import time
import re
from texttable import Texttable
import json
#format file with regex:
#(vixen|tushy)\s(\d\d\.\d\d\.\d\d)\.(.*)(\.And.*)?\.XXX.*
old_article_XPath = "//article[@class='videolist-item']"
old_date_XPat... |
import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
dtResolutionAnalysisTest = DQMEDHarvester("DTResolutionAnalysisTest",
diagnosticPrescale = cms.untracked.int32(1),
maxGoodMeanValue = c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.