text stringlengths 38 1.54M |
|---|
import csv
def read_csv_file(file_name):
result = []
with open(file_name, 'r') as file:
reader = csv.reader(file)
for row in reader:
result.append(row)
return result
def filter_by_one_agrument(file, column, content):
result = []
for row in file:
if content ==... |
#Runtime : O(n)
# here we maintain two arrays
# one call left, that maintains
# the product of all elements
# before a specific index
# similarly we maintin an array
# called right that maintains
# a product of all the elements
# after that specific index.
def solution(array):
left = [0]*len(array)
right =... |
"""
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Input: 1... |
__author__ = 'Oleksandr Shapran'
'''
Задание 6_2
Набор 1
fu, tofu, snafu
Набор 2
futz, fusillade, functional, discombobulated
Задача: напишите регулярное выражение, которое будет соответствовать всем словам из
первого набора и ни одному из второго.
'''
import re
def main():
string = """fu, tofu, s... |
'''
@author: frank
'''
import unittest
import time
from sftpbackupstorage import sftpbackupstorage
from zstacklib.utils import http
from zstacklib.utils import jsonobject
from zstacklib.utils import uuidhelper
class Test(unittest.TestCase):
CALLBACK_URL = 'http://localhost:%s/testcallback' % sftpbackupstorage.Sft... |
# -*- coding: UTF-8 -*-
import sys
from jobControl import runner
from util import project_dir_manager, conf_parser, assert_message, hdfs_util, option_util
def run(args):
conf_file = args[1]
conf = conf_parser.ConfParser(conf_file)
conf.load('DeOscillation') # 加载去震荡默认的参数配置模块
# Stable Point
print '... |
# From: https://gist.github.com/mrluanma/1480728
flatten = lambda lst: reduce(lambda l, i: l + flatten(i) if isinstance(i, (list, tuple)) else l + [i], lst, [])
import matplotlib.pyplot as plt
from itertools import *
import operator
from toolz import *
from toolz.curried import *
from efprob.efprob_qu import *
impo... |
from .submodule_reference_interface import SubmoduleReferenceInterface
from .process_interface import ProcessInterface
class SubmoduleInterface(SubmoduleReferenceInterface, ProcessInterface):
"""SubmoduleInterface
Represents a submodule
"""
def __init__(self):
self._module_reference = None # ... |
from django.db import models
from django.urls import reverse
# Create your models here.
class Account(models.Model):
userName = models.CharField(max_length = 120)
userPassword = models.CharField(max_length = 120)
userFirstName = models.CharField(max_length = 120)
userLastName = models.CharField(max_le... |
from sequ import sequenceacq
import sys
#mp = open("x,")
gogo = sys.argv[1]
gout = sys.argv[2]
inside = sys.argv[3]
file = open(gogo,"r")
lines = file.readlines()
lines = list(lines)
dic={}
temp = ""
for i in lines:
i = i.split(" ")
i[0] = i[0] + "-" + i[1]
if int(i[8]) > int(i[9]):
k = i[8]
... |
from save_experience import *
from models import *
from utils import *
from keras.utils import plot_model
from keras import callbacks
from keras.models import model_from_json
from callbacks import LossHistory, saveEveryNModels
from data_generator import DataGenerator
import h5py
def trainModel(dict):
print("Loadin... |
sign = 1
sum = 0
for i in range(1,20,2):
sum = sum + (sign * 4.0) / i
sign = -sign
print(sum) |
import numpy as np
import os
import matplotlib.pyplot as plt
import pywt
from PIL import Image
# enter relative path from the file of execution
# returns 3D numpy array of the image
def load_image(path) :
try:
img = np.array(Image.open(path))
except IOError:
print(path)
img = 0
r... |
import os
import utfutil
def main():
# Absolute Path Stop Test
stop_file = 'junk_test.out'
# Clean up the stop file if it already exists.
if os.path.exists(stop_file): os.remove(stop_file)
current_directory = os.getcwd()
stop_file = os.path.join(current_directory, stop_file)
repy_args = ['--stop', s... |
from time import sleep
bar=[[],[],[]]
numOfDisks=1
barName=['left','middle','right']
def move(bfrom, to, disk):
moveTo=0
while True:
if moveTo!=bfrom and moveTo!=to:
break
else:
moveTo+=1
if disk==1:
del bar[bfrom][-1]
bar[to].append(disk)
draw()
print('moving disk1 to '+barName[to]+'\n')
sleep(0... |
#Ageel 9/9/2019
#100 Days of Python
#Day 20 - Sets
fruit = {"apple","banana","cherry","Banana","apple"}
fruit.add("mango")
fruit.update({"pineapple","orange"})
for x in fruit:
print(x)
print( "Onion is a fruit ?" + str("onion" in fruit)) |
"""
cables.py: Module is used to implement cable section analysis and an event study
"""
__author__ = "Chakraborty, S."
__copyright__ = ""
__credits__ = []
__license__ = "MIT"
__version__ = "1.0."
__maintainer__ = "Chakraborty, S."
__email__ = "shibaji7@vt.edu"
__status__ = "Research"
import numpy as np
import p... |
from PyQt5 import QtWidgets
from PyQt5 import QtCore
import pyqtgraph as pg
import numpy as np
import socket
from ctypes import *
import time
from MainWindow import Ui_MainWindow
# PLC UDP Data Types import
from RxUdp import RxUdp
from TxUdp import TxUdp
class RemoteInterface(QtWidgets.QMainWindow, Ui_MainWindow):
... |
# Generated by Django 3.2.3 on 2021-05-15 21:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='hamilton',
name='address',
f... |
import flask
import serial
from time import sleep
import sys
COM_PORT = 'COM3' # 請自行修改序列埠名稱
BAUD_RATES = 115200
ser = serial.Serial(COM_PORT, BAUD_RATES)
app = flask.Flask(__name__)
@app.route('/', methods=['GET'])
def home():
print('connected')
return "<h1>Hello</h1>"
@app.route('/red', methods=['GET'])
d... |
def day_twelve_one():
array = [[-14, -4, -11, 0, 0, 0], [-9, 6, -7, 0, 0, 0], [4, 1, 4, 0, 0, 0], [2, -14, -9, 0, 0, 0]]
# array = [[-8, -10, 0,0,0,0],[5,5,10,0,0,0],[2,-7,3,0,0,0], [9,-8,-3,0,0,0]]
# array = [[-1, 0, 2,0,0,0],[2,-10,-7,0,0,0],[4,-8,8,0,0,0], [3,5,-1,0,0,0]]
i = 0
while i < 1000:
if array[0][0]... |
#/usr/bin/env python3
"""
This program is for testing DynamoDB easily.
written by sudsator (Nov 2019)
usage : python get_by_updatedt.py <min:update_date_time> <max:update_date_time>
for example > python get_by_updatedt.py 1970010100000 19700101000010
reference :
http://tohoho-web.com/python/index.html
https://python... |
import random
class MapTile:
def __init__(self,x,y,loot):
self.x = x
self.y = y
self.loot = []
def map_location(self,x,y):
if x < 0 or y < 0:
return "This is impossible, try again" # coordinates can not be less than 0
try:
return map_of_world[y][... |
# Generated by Django 2.1.3 on 2019-11-16 16:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Eprint_users', '0027_auto_20191116_2007'),
]
operations = [
migrations.AddField(
model_name='hostsearch',
name='comp... |
from dataextract import Type
class Double:
def __init__(self, column, value, format = None):
self.column = column
self.value = self.convert(value)
def add_to_row(self, row):
return row.setDouble(self.column, self.value)
def convert(self, value):
return float(value)
de... |
# Corrigido
print('Exercício 014')
print()
# Bloco de entrada
c = float(input('Informe uma temperatura em °C: '))
print()
# Bloco de cálculo
f = ((9 * c) / 5) + 32
# Bloco de saída
print('{}°C são equivalentes a {}F.'.format(c, f))
print()
|
from service_message import *
from constants import *
from collections import deque
from threading import Event
from asyncoro import AsynCoro, Coro, AsynCoroThreadPool, logger
import multiprocessing
import logging
class Message_Router():
_instance = None
@classmethod
def instance(cls):
if not cls._... |
baseline = "foo"
mine = "10sec_gen_foo"
target = "10sec_new_foo"
with open(target, "w") as ot, open(baseline) as 1in, open(mine) as 2in:
for 1line in 1in:
2line = 2in.readline()
1c = 1line.split()
2c = 2line.split()
if 1c[0] != 2c[0]:
print("fatal error")
exit(1)
score = str((float(1c[1]) + float(2c[1]... |
# Arbitrary Base Conversions
from ex104 import int_to_hex, hex_to_int
# Convert a number from base 10 to base new base
# @param number the base 10 number to convert
# @param new_base the base to convert to
# @return the string of digits in new base
def decimal_to_n(decimal: int, new_base: int):
out = ''
whil... |
#!/usr/bin/env python3
coins = [
(50, 10),
(10, 10),
(5, 3)
]
def csum(l):
return sum(coin*num for coin, num in l)
class NoChange(Exception):
pass
def change(amount, coins=coins):
print("called with", amount, coins)
if amount == 0:
return []
if not coins:
raise NoChange
coin, num = coins... |
import pandas as pd
import csv
DATA_DIR = r"G:\Documents\Drexel\Final_Project\cresci-2017.csv\datasets_full.csv\social_spambots_1.csv\social_spambots_1.csv"
CRESCI_TWEET_COLS = ['user_id', 'retweet_count', 'reply_count', 'favorite_count', 'num_hashtags',
'num_urls', 'num_mentions', 'created_at', ... |
from unittest import TestCase
from pycec.commands import CecCommand
from pycec.const import CMD_POWER_STATUS, CMD_VENDOR, CMD_OSD_NAME, \
CMD_PHYSICAL_ADDRESS
from pycec.network import HDMIDevice
class TestHDMIDevice(TestCase):
def test_logical_address(self):
device = HDMIDevice(2)
self.asser... |
import asyncio
import os
import socket
import ccxt.async_support as ccxta
"""
三角套利demo2:寻找三角套利空间,包含下单模块,异步请求处理版
交易对:用一种资产(quote currency)去定价另一种资产(base currency),比如用比特币(BTC)去定价莱特币(LTC),
就形成了一个LTC/BTC的交易对,
交易对的价格代表的是买入1单位的base currency(比如LTC)
需要支付多少单位的quote currency(比如BTC),
或者卖出一个单位的base currenc... |
from collections import defaultdict, deque
class Solution:
def minimumSemesters(self, N: int, relations: List[List[int]]) -> int:
pre = {i: set() for i in range(1, N + 1)}
after = {i: set() for i in range(1, N + 1)}
for i, j in relations:
pre[j].add(i)
after[i].add(j)... |
import os
import glob
from google.cloud import storage
from sklearn.externals import joblib
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
def get_model(bucket_name):
"""Lists all the blobs in the bucket."""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
models = []
... |
e, s, m = map(int, input().split())
if e % 15 == 0:
e -= 15
if s % 28 == 0:
s-= 28
if m % 19 == 0:
m -= 19
year = 1
while True:
if year % 15 == e and year % 28 == s and year % 19 == m:
break
year += 1
print(year) |
from adminapp.views import bookings
from django.shortcuts import render,redirect
from carapp.models import Customers,Users,CarVariant,Category,JourneyStage,Feedback,Drivers,Payment,Bookings,Car
from django.core.mail import send_mail
from django.contrib import messages
from datetime import date
from django.core.paginato... |
from token_dispenser import TokenDispenser
import grpc
from v1_pb2 import GetHomeGraphRequest
from v1_pb2_grpc import StructuresServiceStub
class GoogleAPIService:
def __init__(self, username: str, password: str):
self.token_dispener = TokenDispenser(username, password)
def get_devices(self) -> list:... |
from django.conf.urls import url
from shop_manager import views
urlpatterns = [
url(r'categories/(?P<category_name>[a-zA-Z0-9]+)/new', views.new_product, name="new_product"),
url(r'categories/(?P<category_name>[a-zA-Z0-9]+)/(?P<item_id>[0-9]+)', views.product, name="product"),
url(r'categories/(?P<category... |
def minibatch_weighted_gradient_descent(X,y,theta,learning_rate=0.01,iterations=10,batch_size =20):
cov=np.cov(normal[:,[0,1]])
for i in range(len(cov)):
for j in range(len(cov)):
if (i!=j):
cov[i][j]=0
m = len(y)
cost_history = np.zeros(iterations)
theta_history ... |
#-*- coding: utf-8 -*-
#
# Copyright © 2014 Jonathan Storm <the.jonathan.storm@gmail.com>
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See the COPYING.WTFPL file for more details.
__author__... |
import re
from contracts import contract
class Utils:
WS_PATTERN = re.compile("\\s+")
@staticmethod
@contract
def replace_redundant_ws(string: str):
return re.subn(Utils.WS_PATTERN, " ", string)[0].strip()
@staticmethod
def normalize_string(string: str):
return re.subn(Utils... |
import command as cm
class CommandFactory():
# constructor takes in voice object
def __init__(self,voiceobj):
self.command = voiceobj.getcommand()
self.arg = voiceobj.getarg()
def getcmdobj(self):
if self.command == "rm":
return cm.rm(self.command,self.arg) #returns ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
urlpatterns = patterns('site_fotos.album.views',
url(r'^$', 'albuns', name='albuns'),
) |
from sys import argv
import lxml.html as lh
html = lh.parse(argv[1])
root = html.getroot()
rootiter = html.getiterator()
for i in rootiter:
print(html.getpath(i))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, shutil
from conans import ConanFile, tools, CMake
from glob import glob
class EigenConan(ConanFile):
name = "eigen"
version = "3.3.7"
url = "https://github.com/conan-community/conan-eigen"
homepage = "http://eigen.tuxfamily.org"
description ... |
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from src.core.flask_app import app
from src.core.database import db
from src.models.user import User
from src.models.todos import Todo
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __na... |
import pytest
from app import create_app
@pytest.fixture
def client():
app = create_app()
app.config["TESTING"] = True
context = app.app_context()
context.push()
yield app.test_client()
context.pop()
|
import os.path
import shutil
from unittest.mock import patch
from programy.storage.stores.file.config import FileStorageConfiguration
from programy.storage.stores.file.engine import FileStorageEngine
from programy.storage.stores.file.store.conversations import FileConversationStore
from programytest.storage.asserts.sto... |
import os
import sys
# input a valid adress of the target folder to path after running the file hw4.py
path = sys.argv[1]
print(f"Start in {path}")
# create a list of file-names of the target folder
files = os.listdir(path)
# create a set for file extensions
extensions_names = set()
# create lists for each file-grou... |
# Generated by Django 3.0.3 on 2020-11-13 07:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='class',
name='attributes',
... |
import logger
import network
import network.network_base
import config_handler
LOG_FILENAME = "server.log"
LOGGER = logger.logger_generator(LOG_FILENAME)
network.network_base.LOGGER = LOGGER
PROTOCOL_CATEGORY = "protocol"
PROTO_CODES = "protocol_codes"
NETWORK_CATEGORY = "network"
DATABASE_CATEGORY = "database"
ADMIN_... |
import graphene
import crud_app.crud_api.schema
class Query(crud_app.crud_api.schema.Query, graphene.ObjectType):
pass
class Mutation(crud_app.crud_api.schema.Mutation, graphene.ObjectType):
pass
schema = graphene.Schema(query = Query, mutation = Mutation)
|
#!/usr/bin/env python
'''Test to see whether class variables and methods are in fact
inherited.'''
class Parent(object):
'''Parent class'''
__class_var = 10
@classmethod
def get_class_var(cls):
return cls.__class_var
@classmethod
def set_class_var(cls, value):
cls.__class_var... |
# Generated by Django 2.2.4 on 2020-11-11 16:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('objects', '0006_auto_20201111_1159'),
('circuits', '0003_auto_20201111_1506'),
]
operations = [
mig... |
# -*- coding: utf-8 -*-
# @Time : 2019-05-09 20:26
# @Author : focusxyhoo
# @FileName : pdf_reader.py
import os
from pdfminer.pdfparser import PDFParser, PDFDocument, PDFSyntaxError
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfmine... |
import json
import falcon
import peewee
from models import models_api
from utils.myjson import JSONEncoderPlus
class MinisterioId(object):
@models_api.database.atomic()
def on_get(self, req, resp, ministerio_id):
try:
ministerio_id = int(ministerio_id)
except ValueError:
... |
import unittest
import os
from application import create_app
class TestRootEndpoint(unittest.TestCase):
def setUp(self):
self.app = create_app(config="testing")
self.client = self.app.test_client()
def tearDown(self):
pass
def test_root_endpoint(self):
res = self.client.p... |
from src.tasks.api import Task
def test_task_equality():
t = Task('buy car', 'igor')
b = Task('buy beer', 'pawel')
assert not t == b
def test_dict_equality():
t_dict = Task('buy car', 'igor')._asdict()
expected = Task('buy beer', 'pawel')._asdict()
assert t_dict != expected
|
#!/usr/bin/python
# Mat4Pep-matrix_scorer.peptide.py
# Jeremy Horst, 04/06/2010
#####################################
# this program takes as input #
# [1]- a FASTA file #
# [2]- a directory of FASTA files #
# [3]- a scoring matrix #
# [4,5]- gap penalties #
# calculat... |
import checks
import discord
import logging
import traceback
import valve.rcon
from bot import Discord_10man
from databases import Database
from discord.ext import commands
from logging.config import fileConfig
from steam.steamid import SteamID, from_url
from typing import List
class Setup(commands.Cog):
def __i... |
#!/usr/bin/env python
import Tkinter
tk=Tkinter
import aniwinch
import threading
from datetime import datetime
import time
import serial
import sys
import winch_settings
from humminbird import HumminbirdMonitor
from gpio_wrapper import SerialGPIO
from async import async,OperationAborted
import logg... |
n, m = map(int, input().split())
array = input().split()
array.sort() #사전식으로 출력해야 하므로 입력이후에 정렬 수행
#조합 사용하면됨
from itertools import combinations
#모음 2개가 꼭 있어야 한다
vowels = ('a', 'e', 'i', 'o', 'u')
# #난 이렇게 품
# comb = combinations(array, 4)
# for i in comb:
# for j in i:
# print(j, end = '')
# print()
... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ConsentCatalogueAudit'
db.create_table('bhp_consent_conse... |
# Generated by Django 2.1.2 on 2018-12-17 20:54
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),
('pharmacies', ... |
# problem [1204] : 최빈수 구하기
# 고등학교 1000명의 수학성적을 토대로 최빈수 구하기
# 학생의 수는 1000명이며, 각 학생의 점수는 0점 이상 100점 이하의 값이다.
test_cnt =int(input())
for i in range(test_cnt):
test_num = int(input())
score_list = list(map(int,input().split()))
score_dict = dict()
result = list()
for score in score_list:
if (... |
import modulex
modulex.panikimanlinollu()
print("jithu is ",modulex.edava)
x=modulex.Student('jithu','xyz')
x.display()
|
from functools import wraps
def authenticate_user(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
user = request.user
if not user.is_authenticated:
return restful.un_signup(message='请先登录')
return func(request, *args, **kwargs)
return wrapper
|
import envi.archs.amd64 as e_amd64
import envi.archs.i386.renderer as e_i386_rend
class Amd64OpcodeRenderer(e_i386_rend.i386OpcodeRenderer):
def __init__(self):
e_i386_rend.i386OpcodeRenderer.__init__(self)
self.arch = e_amd64.Amd64Module()
self.rctx = e_amd64.Amd64RegisterContext(... |
import pandas as pd
import numpy as np
dataset_data = pd.read_csv('/home/valentin/human_tracker_ws/FERIT_dataset/kinect_k07_1/results/k07_stamps_annotations.csv').to_numpy()
method_data = pd.read_csv('/home/valentin/human_tracker_ws/FERIT_dataset/kinect_k07_1/results/k07_method21.csv').to_numpy()
# print(method_data)... |
from django.conf.urls import url
from django.views.generic.base import RedirectView
from . import views, accountViews, queries
app_name = 'ASUi3dea'
urlpatterns = [
#accountViews.py
url(r'^$', RedirectView.as_view(url='login', permanent=False), name='login'),
url(r'^login/$', accountViews.login, name='lo... |
from JumpScale9 import j
class JSBase:
def __init__(self):
# self.__j = None
self.__logger = None
@property
def j(self):
if self.__logger == None:
self.__logger = j.logger.get()
return self.__logger
# @property
# def j(self):
# if self.__j==No... |
#!/usr/bin/python
# -*- coding:utf8 -*-
import numpy as np
from scipy.integrate import odeint
import sympy as sp
import math as mt
########################################################################
################ ########## SEIR_DIT CLASS ########## ##################
#########################################... |
import sys
import re
from PySide.QtGui import *
from EntryForm import *
class EntryApplication(QMainWindow, Ui_MainWindow):
states = ["AK", "AL", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY",
"LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", ... |
import serial
import speech_recognition as sr
def soz():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Скажите что-нибудь")
audio = r.listen(source)
try:
return(r.recognize_google(audio, language="ru-RU"))
except sr.UnknownValueError:
print("Робот не расслы... |
from flask import Flask, render_template, request
from Flaskproject.models import *
@app.route('/user/registration/', methods=['GET','POST'])
def register_page():
if request.method=='POST':
user = Userinfo(name=request.form['nm'],
address=request.form['adr'],
... |
class Solution:
def isPossible(self, n: int, edges: List[List[int]]) -> bool:
es, nc, on = set(), defaultdict(int), []
for a,b in edges:
nc[a], nc[b] = nc[a]+1, nc[b]+1
es.add((a,b)), es.add((b,a))
for k in nc:
if nc[k] % 2 !=0: on.append(k)
if... |
# Copyright 2015 Google Inc. 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 required by applicable law or agreed ... |
from computer import Computer
def main():
fname = "Input/9.1.in"
arr = map(int, open(fname).readline().split(","))
for i in xrange(1,3):
c = Computer(arr[:])
ret, outputs, dump = c.run_computer([i])
print(outputs)
if __name__=="__main__":
main() |
import cv2
import numpy as np
import time
class gridSquare:
topLeft = np.zeros([2])
topRight = np.zeros([2])
bottomLeft = np.zeros([2])
topRight = np.zeros([2])
def perp( a ) :
b = np.empty_like(a)
b[0] = -a[1]
b[1] = a[0]
return b
def intersection(a1,a2, b1,b2) :
da = a2-a1
... |
from functools import wraps
def catch_all_exceptions(func):
"""
This decorator is used to abstract the try except block for functions that don't affect the final status of an action.
"""
@wraps(func)
def func_wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except:... |
# pylint: disable=protected-access
import os
import glob
import radical.utils as ru
from .. import states as s
from .session import fetch_json
_debug = os.environ.get('RP_PROF_DEBUG')
# ------------------------------------------------------------------------------
#
# pilot and unit activities: core hours a... |
import os, sys
import logging
import time
import shutil
logging.basicConfig(level=10)
logger = logging.getLogger(__name__)
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(parentdir)
logger.debug("parentdir: %s" % parentdir)
from _common_test import TestDummyResponse, DummyDis... |
# Generated by Django 2.1.1 on 2018-09-15 15:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('rooms', '0009_room_event'),
]
operations = [
migrations.RemoveField(
model_name='room',
name='event',
),
]
|
import sys
n, k = map(int, sys.stdin.readline().split(' '))
arr = list(range(1, n+1))
res = list()
idx = k-1
while len(arr) > 0:
res.append(arr.pop(idx))
idx += (k-1)
while len(arr) > 0 and idx >= len(arr):
idx -= len(arr)
ret = '<'
for i in res[:-1]:
ret += (str(i) + ', ')
ret += (str(res[-1]... |
"""imageadmin URL Configuration
"""
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('view_all_diva/', views.view_all_diva, name='view_all_diva'),
path('view_diva/<str:document_id>', views.view_diva, name='view_diva'),
path('view_ext_diva/<path:ma... |
#!/usr/bin/env python3
from wtforms import (Form, StringField, PasswordField, BooleanField)
from wtforms.validators import DataRequired
class LoginForm(Form):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = Boo... |
"""
@file filter2D.py
@brief Sample code that shows how to implement your own linear filters by using filter2D function
"""
import sys
import cv2 as cv
import numpy as np
def main(argv):
window_name = 'filter2D Demo'
## [load]
imageName = argv[0] if len(argv) > 0 else 'lena.jpg'
# Loads an image
... |
"""
This type stub file was generated by pyright.
"""
from .vtkImageReader import vtkImageReader
class vtkBMPReader(vtkImageReader):
"""
vtkBMPReader - read Windows BMP files
Superclass: vtkImageReader
vtkBMPReader is a source object that reads Windows BMP files. This
includes indexed an... |
#!/usr/bin/env python3
# Documentation: https://docs.python.org/3/library/socket.html
# from MasterMenu import Menu
from MasterMenu import Menu
import socket
import json
import sys
import struct
sys.path.append("..")
class MasterPi:
"""
This class shows the connection through socket programming between
ma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 20:34:25 2019
@author: aleksandr
"""
import graphics as gr
window = gr.GraphWin('wondow', 300, 300)
def fractal_rectangle(A, B, C, D, deep=10):
if deep < 1:
return
gr.Line(gr.Point(*A), gr.Point(*B)).draw(window)
gr... |
#!/usr/bin/env python
"""
Demonstrate how to do two plots on the same axes with different left
right scales.
The trick is to use *2 different axes*. Turn the axes rectangular
frame off on the 2nd axes to keep it from obscuring the first.
Manually set the tick locs and labels as desired. You can use
separate matplo... |
# Adafruit NeoPixel library port to the rpi_ws281x library.
# Author: Tony DiCola (tony@tonydicola.com), Jeremy Garff (jer@jers.net)
import atexit
import numpy as np
import _rpi_ws281x as ws
def Color(red, green, blue, white=0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each colo... |
#!/usr/bin/python
import sys
def making_change(amount, denominations):
total = 0
if amount == 0:
return 1
if not denominations and amount > 0:
return 0
if amount < min(denominations):
return 0
# for every denomination less than the amount:
# - determine how many of th... |
# Generated by Django 3.0.1 on 2020-01-24 16:04
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
"""
http://www.diveintopython3.net/xml.html
"""
from xml.dom import minidom
import os
xmlfile=os.path.dirname(os.path.abspath(__file__))+'/staff.xml'
doc = minidom.parse(xmlfile) #~ json.dumps(file,indent=)
# doc.getElementsByTagName returns NodeList
name = doc.getElementsByTagName("name")[0]
#print("Node Name : %s"... |
'''
1277. Count Square Submatrices with All Ones
Medium
2575
40
Add to List
Share
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example 1:
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 s... |
# Generated by Django 2.0.6 on 2018-07-15 15:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('course', '0007_auto_20180715_2337'),
]
operations = [
migrations.RenameField(
model_name='course',
old_name='or_banner',
... |
txt = "H\te\tl\tl\to"
print(txt)
print(txt.expandtabs())
print(txt.expandtabs(2))
print(txt.expandtabs(4))
print(txt.expandtabs(8))
print(txt.expandtabs(10))
txt = "H\te\tl\tl\to"
x = txt.expandtabs(2)
print(x)
txt = "Hello, welcome to my world."
x = txt.endswith("my world.", 5, 11)
print(x)
txt = "Hello, w... |
with open('words.txt','r') as file :
words = file.readlines()
for i in words:
a = i.strip('\n')
if a == a[::-1]:
print(a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.