text
stringlengths
8
6.05M
value1 = '1,4,7,-4,88,102,-1234' # write your solution here def sort_list(integers): return ','.join(sorted(integers.split(','), key=int, reverse=True)) print(sort_list(value1))
"""Search/report page.""" import json import flask from dnstwister import app import dnstwister.tools as tools def html_render(domain): """Render and return the html report.""" reports = dict([tools.analyse(domain)]) return flask.render_template( 'www/report.html', reports=reports, ...
""" This is an example for image reading """ import h5py import matplotlib.pyplot as plt read_path = '/media/blade/road_hackers/training_images/137.h5' image_object = h5py.File(read_path, 'r') for utc_time in image_object: # utc_time is a string print(utc_time) # get an image from 137.h5 dictionary selected_i...
from __future__ import division import sys import traceback from PyQt5.QtWidgets import QApplication, QDialog, QTextBrowser, QLineEdit from PyQt5.QtWidgets import QVBoxLayout class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.broswer = QTextBrowser() # di...
class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ ret = [] mapper = {} for i in range(1, len(nums)+1): if i in mapper: pass else: mapper[i] = ...
import pafy import numpy as np import time from tqdm import tqdm import tensorflow as tf from tensorflow.keras.applications.mobilenet_v2 import preprocess_input print('tensorflow.__version__', tf.__version__) #print('GPU name test',tf.test.gpu_device_name()) import cv2 print('cv2 version',cv2.__version__) import imuti...
import sys import numpy as np import matplotlib.pyplot as plt #plt.switch_backend('agg') filename = 'PA_final.dat' x = [[] for i in range(3)] y = [[] for i in range(3)] shells = int(sys.argv[1]) hw = float(sys.argv[2]) with open(filename) as f: data = f.read() data = data.split('\n') for num in range(2,len(dat...
#!/usr/bin/python import sys import os if( __name__ == '__main__' ): ver = tuple( map( int, sys.argv[1].split( '.' ) ) ) hdbfs = None if( ver[0] > 8 or ver[0] == 8 and ver[1] > 0 ): import hdbfs else: import higu hdbfs = higu if( ver[0] >= 5 ): hdbfs.ark.MIN_THUM...
def result(points): xs = sorted([point[0] for point in points]) ys = sorted([point[1] for point in points]) rtx, rty = 0, 0 if xs[0] == xs[1]: rtx = xs[2] else: rtx = xs[0] if ys[0] == ys[1]: rty = ys[2] else: rty = ys[0] print(rtx, rty) points = [] f...
# -*- coding: utf-8 -*- import pandas as pd import numpy as np filename = 'hahu0291@uni.sydney.edu.au--N168554113.csv' full = pd.read_csv(filename, index_col=False, header=None, low_memory=False) dropped = full.dropna(axis=0, subset=[5]) nodup = dropped.drop_duplicates(subset=[0]) nodup.to_csv('nodup.csv')
# Generated by Django 3.1.1 on 2020-11-10 14:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Comment', fields=[ ...
import cv2 import os import numpy as np class SimpleDatasetLoader: def __init__(self, preprocessors=None, labels_set=None): if preprocessors is None: self.preprocessors = [] else: self.preprocessors = preprocessors if labels_set is None: ...
while 1: n=int(input()) if n==0: break a=[int(input()) for i in range(n)] temp = 0 most = -999999999 for i in range(n): temp = 0 for j in range(i,n): temp += a[j] if temp > most: most = temp print(most)
# Copyright 1998-2012 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 __all__ = [ "close_portdbapi_caches", "FetchlistDict", "portagetree", "portdbapi" ] import portage portage.proxy.lazyimport.lazyimport(globals(), 'portage.checksum', 'portage.data:portage_gid,secpass', 'port...
class Solution: def convertToBase7(self, num: int) -> str: if num == 0: return "0" res = [] flag = True if num < 0: flag = False num = - num while num: res.append(str(num % 7)) num //= 7 if not flag: ...
import sys, types from thUtils.stdlib import * from threading import Thread # Builtin Commands class thCommands: def __init__(self): return None class thMonitor: def __init__(self): cmd = Commands() self.commands = {} self.hosts = {} self.hostg = {'default': []} def _is_in_list(self, itm, lst): for it...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainwindow.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtWidgets import Methods.Bisection as Bisection import Methods.RegularFalse as RegularFalse im...
import kopf import re from kubernetes import client, config @kopf.on.delete('clustersecret.io', 'v1', 'clustersecrets') def on_delete(spec,body,name,logger=None, **_): syncedns = body['status']['create_fn']['syncedns'] v1 = client.CoreV1Api() for ns in syncedns: logger.info(f'deleting secret {name...
import streamlit as st import json from io import StringIO from pybtex.database import parse_string from datosConexion import conectarBd from clases import Paper def mostrarSeccionCarga(): conectarBd() uploaded_file = st.file_uploader("Archivo Bibtex con la información de los papers") before = len(Pape...
# coding with UTF-8 # ****************************************** # *****CIFAR-10 with ResNet8 in Pytorch***** # *****test_classify.py ***** # *****Author:Shiyi Liu ***** # *****Time: Oct 22nd, 2019 ***** # ******************************************import torch import torch import ...
# -*- coding: utf-8 -*- import ctypes as ct from .trezor_ctypes import * from .trezor_cfunc_gen import * def random_buffer_r(sz): buff = (ct.c_uint8 * sz)() cl().random_buffer(buff, sz) return bytes(buff) def init256_modm(r, a): cl().set256_modm(r, ct.c_uint64(a)) return r def init256_modm_r(...
import json import re def extract(title): with open(file) as file_current: for line in file_current: json_line = json.loads(line) if json_line['title'] == title: return json_line['text'] def clean(text): pattern_emphasis = re.compile(r' (\'{2,5}) (.*?) (\1) ', r...
import NvRules def get_identifier(): return "CPIStallMioThrottle" def get_name(): return "CPI Stall 'MIO Throttle'" def get_description(): return "Warp stall analysis for 'MIO Throttle' issues" def get_section_identifier(): return "WarpStateStats" def apply(handle): ctx = NvRules.get_context(ha...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from telegram.ext import Updater, InlineQueryHandler, CommandHandler from urllib.parse import quote_plus import requests, logging from bs4 import BeautifulSoup from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) from telegram.ext import (Updater, Com...
""" Performs continuous communication with an Arduino (or any Serial device) through the serial port. Type "exit" to quit. """ import serial, sys, getopt from select import select _DEBUG = False _DEVICE_FILE = "/dev/cu.usbmodem1411" _BAUDRATE = 9600 _TIMEOUT = 1 _JSON_CMD = 'json\n' _EXIT = 'exit\n' def openSerial...
from flask import Blueprint plate = Blueprint('plate', __name__, url_prefix='/') # never forget from . import routes
class Test: pass test_type = type(Test) assert test_type == type # That's kind of weird assert type(type) == type # Other way to define a class bases = () attr = {} Foo = type('Foo', bases, attr) assert type(Foo()) == Foo # Sample metaclass for building # Singleton objects class SingletonMeta(type): _inst...
"""Treadmill metrics collector. Collects Treadmill metrics and sends them to Graphite. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import import glob import logging import os import socket import time import click ...
from django.urls import path from news.views import news_list, news_in_category, news_items, like_or_dislike app_name = 'news' urlpatterns = [ path('', news_list, name='news_list'), path('<int:news_pk>/', news_items, name='news_items'), path('<int:news_pk>/<int:comment_pk>/<str:vote>', like_or_dislike, na...
#I pledge my honor that I have abided by the Stevens Honor System. Jake Roux def main(): print("This program will return the sum of numbers you enter") num=eval(input("Separated by commas, enter your numbers:")) sum=0 for i in num: sum+= int(i) print(sum) main()
#!/usr/bin/python3 '''Takes in an argument and displays all values in the states table of hbtn_0e_0_usa where name matches the argument.''' from sys import argv import MySQLdb if __name__ == "__main__": MY_USER = argv[1] MY_PASS = argv[2] MY_DB = argv[3] STATE = argv[4] db = MySQLdb.connect(host="...
#!/usr/bin/python import math def power(a,b): if( b==0): return 1; elif(b==1): return a; else: if(b%2==0): t=power(a,b/2); return t*t; else: t=power(a,b/2); return t*t*a; def main(): T=int(raw_input()); c=0; while (c<T): c=c+1; L,D,S,C = [int(x) for x in raw_input().split()] ;...
from __future__ import unicode_literals import arrow from pyaib.plugins import keyword, observe, plugin_class def serialize_seen(seen): return { 'user': seen['user'], 'timestamp': seen['timestamp'].isoformat(), 'channel': seen['channel'], 'message': seen['message'] } def deser...
""" Functions to count and cluster amino acid sequences. """ import numpy as np from . import utils class PSFM: """Meta class for a position specific scoring matrix""" def __init__(self, pssm, alphabet=utils.AMINO_ACIDS, comments=(), consensus=None): self._psfm = psfm self.alphabet = alphabe...
import os import imaplib import email from email.header import decode_header import traceback USERNAME = os.getenv('email') PASSWORD = os.getenv('password') def get_otp(): try: otp = [] # create an IMAP4 class with SSL imap = imaplib.IMAP4_SSL("imap.gmail.com") # authenticate ...
import socket import select def rc4_crypt(data, key): """RC4 algorithm""" x = 0 box = range(256) for i in range(256): x = (x + box[i] + ord(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], b...
import findspark findspark.init('C:\spark-2.4.5-bin-hadoop2.7') # May cause deprecation warnings, safe to ignore, they aren't errors from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import SQLContext from pyspark.sql.functions import desc from pyspark.sql import Row imp...
from django.views import View from django.shortcuts import render, redirect from django.http import JsonResponse from rest_framework import viewsets, generics from django.contrib import messages from .models import Priode, Matakuliah, Grade, KRS, KRSDetail from .models import Mahasiswa, Angkatan, ProgramStudi, Calcul...
from api.send_request import futblot24 page_url = 'https://www.futbol24.com/teamCompare/Thailand/Chonburi-FC/vs/Thailand/Nakhon-Ratchasima/?statTALR-Table=1&' \ 'statTALR-Limit=2&statTBLR-Table=2&statTBLR-Limit=2' response = futblot24.send_request(page_url) print(response)
example = "Python is classic" lower_example = example.lower() print("Lower case example - {}".format(lower_example)) upper_example = example.upper() print("Upper case example - {}".format(upper_example)) length = len(example) print("String length - {}".format(length)) words = example.split(" ") print("Words in the ...
import numpy as np from pylearn2.utils import serial from copy import deepcopy class BinaryResult(object): """ dummy class for binary results """ pass class CSPResult(object): """ For storing a result""" def __init__(self, csp_trainer, parameters, training_time): self.multi_class = csp_trainer...
from genderbias.detector import Report, Issue, Flag, BiasBoundsException from pytest import fixture, raises report_name = "Text Analyzer" summary = "[summary]" flag = Flag(0, 10, Issue(report_name, "A", "B")) positive_flag = Flag(20, 30, Issue(report_name, "C", "D", bias = Issue.positive_result)) no_summary_text = "...
from django.contrib import admin from .models import ExamLibItem, Paper, ExamItem, ExamResult # Register your models here. class ExamItemInline(admin.TabularInline): model = ExamItem extra = 0 class ExamLibItemAdmin(admin.ModelAdmin): class Meta: model = ExamLibItem class PaperAdmin(admin.ModelAdmin): list_d...
from keras.preprocessing.image import ImageDataGenerator, DirectoryIterator import numpy as np class BalancedGenerator(ImageDataGenerator): """ Generate minibatches of image data with real-time data augmentation, while randomly over-sampling to fix the class imbalance. featurewise_center: set...
# coding: utf-8 import csv from pathlib import Path """Part 1: Automate the Calculations. Automate the calculations for the loan portfolio summaries. First, let's start with some calculations on a list of prices for 5 loans. 1. Use the `len` function to calculate the total number of loans in the list. 2. Use...
# -*- coding: utf-8 -*- #Variaveis: nome = "Anderson Oliveira" print(nome) nome = "Padawan para Jedi" print(nome) #perceba que posso mudar o valor da variavel no momento em que precisar. input("Pressione qualquer tecla para continuar")
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2020-05-19 22:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('selecao', '0006_auto_20190901_2325'), ] operations = [ migrations.AddField( ...
# -*- coding: utf-8 -*- """ Created on Mon May 4 23:13:38 2020 @author: Abhishek Hiremath """ import pandas as pd def rename(full_name): if full_name=="United States": return "USA" elif full_name=="United Kingdom": return "GBR" elif full_name=="Spain": return "ESP...
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> Programm =("java","python","swift") >>> if "python" in Programm: print("Yes , 'python' is in the programm tuple") Yes , 'python' is in the programm tupl...
#9. Write a Python program to get the Fibonacci series between 0 to 50. Go to the editor #Note : The Fibonacci Sequence is the series of numbers : #0, 1, 1, 2, 3, 5, 8, 13, 21, .... #Every next number is found by adding up the two numbers before it. #Expected Output : 1 1 2 3 5 8 13 21 34 #index = 0 #fib = 0 #temp =...
# the problem is here: # https://www.hackerrank.com/challenges/sherlock-and-array #!/bin/bash/python T = int(raw_input()) for i in range(T): n = int(raw_input()) a = map(int, raw_input().split(' ')) sumRight, sumLeft, flag = 0, 0, True for j in a: sumRight += j for j in range(len(a)): ...
#input = ["Hello"," World"] #x = input.split() #print(input[6:11]) #print(input[0:5]) def flipWords(word): return " ".join(word.split()[::-1]) print(flipWords("Hello World!"))
from game import Game from main import new_game from model.config import config def test_new_game_creates_new_game(): """Too slow to split into multiple tests.""" new_game() assert Game.instance.area_map is not None assert (Game.instance.area_map.width, Game.instance.area_map.height) != (0, 0) as...
# coding=utf-8 from typing import List from .bot import ZaifBot from .config import Config class App: def __init__(self, configs: List[Config]) -> None: self.configs = configs def start(self) -> None: for config in self.configs: bot = ZaifBot(config) bot.start()
#!/usr/bin/python3 from pathlib import Path import urllib.request IP_FILE = "ip-list.txt" DATA_DIRECTORY = "data" iplist = [] def getipFilename(ip): return DATA_DIRECTORY + "/" + ip def hasIPFile(ipfilename): file = Path(ipfilename) if file.is_file(): return True return False # do not call...
# 双周赛 class Solution: def minimumCost(self, cost: List[int]) -> int: ts = sorted(cost, key=lambda x : -x) res, i = 0, 0 n = len(cost) cnt = 0 while i < n: if cnt != 2: res += ts[i] i += 1 cnt += 1 ...
from keras.models import Sequential, Model, load_model from keras.layers import Dense, Embedding, Activation, merge, Input, Lambda, Reshape from keras.layers import Conv2D, Flatten, Dropout, MaxPooling2D, UpSampling2D, GlobalAveragePooling1D, BatchNormalization from keras.optimizers import Adam from keras.callbacks imp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 14 21:59:46 2020 @author: thomas """ import numpy as np import pandas as pd import os, sys import time as t import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from matplotlib.patches import Circle from matplotlib.ticker import ...
# -*- coding: utf-8 -*- from odoo import fields, models class SaleReport(models.Model): _inherit = 'sale.report' sales_person = fields.Many2one('res.users', 'Sales Person(s)', readonly=True) sale_line_id = fields.Many2one('sale.order.line', 'Sales Line', readonly=True) contribution_price = fields.Flo...
n = input() current_state = input() required_state = input() no_moves = 0 for i in range(int(n)): current_digit = current_state[i] required_digit = required_state[i] digit = list(map(int, [current_digit, required_digit])) minimum = min(digit) maximum = max(digit) no_moves += min(...
# -*- coding: utf-8 -*- import unittest from pycolorname.pantone.cal_print import CalPrint class CalPrintTest(unittest.TestCase): def setUp(self): self.uut = CalPrint() self.uut.load(refresh=True) def test_data(self): self.assertEqual(len(self.uut), 992) self.assertIn("Whit...
a=[0,2,2,3,4,4,5,5,8,9] a=[1,1,4,2,2,3,3] s=0 e=0 for i in range(0,len(a)-1): a[s] = a[i] if(a[i] != a[i+1]): s+=1 a[s] = a[len(a)-1] print(a[0:s+1])
# Limit the numbers from 0 - 100 users_input = int(input("Enter an integer value: ")) if users_input in range(0, 100 + 1): pass else: print("Please enter a number between 0 - 100") exit(1) if users_input % 3 == 0 and users_input % 5 == 0: print("FizzBuzz") elif users_input % 3 == 0: print("Fizz")...
from django.contrib import admin from stiltonstriders.models import * # Register your models here. admin.site.register(Event)
a = 0 b = 0 c = 0 for i in range(1, 1000): for j in range(i + 1, 1000): k = 1000 - i - j if (i * i + j * j == k * k) and (i + j + k == 1000): print(i * j * k) break
import requests def req_peak_data(site, start_date, end_date, url_prefix): """ This function first requests water peak flow data in rdb format from NWIS peak water data service. ARGS: site - string site ID for the site to be charted start_date - starting date to chart peak flow data ...
from direct.distributed.DistributedObjectAI import DistributedObjectAI from direct.directnotify import DirectNotifyGlobal class DistributedDailyQuestSpotAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedDailyQuestSpotAI') def __init__(self, air): DistributedObje...
# -*- coding: utf-8 -*- """ Tests of neo.io.stimfitio """ # needed for python 3 compatibility from __future__ import absolute_import import sys import unittest from neo.io import StimfitIO from neo.io.stimfitio import HAS_STFIO from neo.test.iotest.common_io_test import BaseTestIO @unittest.skipIf(sys.version_inf...
# -*- coding: utf-8 -*- """ This file covers all the classes and functions for performing Named Entity Recognition on text objects. We developed an in-house NER tool based primarily on POS tags. We compare our results against state-of-art NLP tools designed and calibrated by Stanford University NLP Group. There a...
import numpy as np def initialize(K,D): # Probabilities of the components of the mixture #pi = np.random.uniform(size=(1, K))[0] #pi = pi / pi.sum() pi = 1/K * np.ones(K) # Transition probabilities (from one state to another) A = np.random.rand(K, K) A = A / A.sum(axis=1,keepdims=True) ...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import os from textwrap import dedent from typing import cast from pants.backend.go.testutil import gen_module_gomodproxy from pants.testutil.pants_int...
from nio import MatrixRoom from dors import command_hook, Jenny, HookMessage import random @command_hook(['pick', 'choose', 'choice'], help=".choice <something> <something else> [third choice] ... " "-- Makes a choice for you") async def choice(bot: Jenny, room: Matri...
# Copyright (c) 2020 Adam Souzis # SPDX-License-Identifier: MIT import six from .runtime import NodeInstance from .util import UnfurlError, Generate, toEnum from .support import Status, NodeState, Reason from .configurator import ( ConfigurationSpec, getConfigSpecArgsFromImplementation, TaskRequest, ) from ...
# 1. 入门配置 import argparse parser = argparse.ArgumentParser(description="used for test") parser.add_argument('--version', '-v', action='version', version='%(prog)s version: v 0.01', help='show the version') parser.add_argument('--debug', '-d', action='store_true', help='show the version', default=False) args = parser...
# Generated by Django 2.2.4 on 2019-11-27 06:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('security_guards', '0003_auto_20191006_1603'), ('visitors', '0015_track_entry_with_vehicle'), ] operations =...
from flask import Flask, render_template, redirect, url_for, jsonify, send_from_directory from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_bootstrap import Bootstrap from flask_cors import CORS from config import config #from .model import Role db = SQLAlchemy() cors = CORS() boo...
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import sys def Round(a): return int(a+.5) def init(): glClearColor(1.0,1.0,1.0,0.0) glColor(1.0,0.0,1.0) glPointSize(3.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0.0,600.0,0.0,600.0) def setpixel(x,y): glBegin(GL_POI...
def dominator(arr): for x in arr: if arr.count(x) > len(arr)/2: return x return -1 ''' A zero-indexed array arr consisting of n integers is given. The dominator of array arr is the value that occurs in more than half of the elements of arr. For example, consider array arr such that arr = [3...
"""Async and Octree config file. Async/octree has its own little JSON config file. This is temporary until napari has a system-wide one. """ import json import logging from pathlib import Path from typing import Optional from napari.settings import get_settings from napari.utils.translations import trans LOGGER = lo...
""" This is simple test suit. The test suit must be start with "test" or end with "test". It must be annoted with pytest fixture. """ import logging import os from posixpath import basename from typing import List import glob from time import sleep import re import pytest from pathlib import Path import inspect from ...
import arcpy from arcpy import env from arcpy.sa import * from arcpy.sa import Con if arcpy.CheckExtension("Spatial") == "Available": arcpy.CheckOutExtension('Spatial') #Checkout the extension else: print "no spatial analyst license available" #Checkout if the extension is working #*****************...
#!/usr/bin/python3 import sys if __name__ == "__main__": contArg = len(sys.argv) - 1 print("{:d}".format(contArg), end="") if contArg != 1: print(" {:s}".format("arguments"), end="") if contArg == 1: print(" {:s}".format("argument"), end="") if contArg == 0: print("{:s}".form...
import os import glob import h5py import keras import numpy as np from Name import * from PIL import Image from keras import backend as K from keras.utils import np_utils from keras.models import Sequential from keras.models import load_model from keras.models import Model from keras.optimizers import SGD, ...
import matplotlib matplotlib.use('Agg') import numpy as np import argparse import matplotlib.pyplot as plt from os import path, makedirs import itertools def load_files(authentic_file, impostor_file): authentic = np.loadtxt(authentic_file, dtype=np.str) if np.ndim(authentic) == 1: authentic_score = a...
import os from django.conf import settings from django.conf.urls.defaults import include, patterns, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView admin.autodiscover() url...
from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import regularizers from keras import backend as K from keras.optimizers import Adam from kera...
""" Views """ import decimal from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Field, Layout, Submit from django import forms from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.db import IntegrityError from dj...
__author__ = 'iceke' class SparkData(object): def __init__(self, property): self.__property = property self.__app_id = '' self.__app_name = '' self.__stage__num = 0 self.__total_time = '' self.__status = 'Finished' self.__finished_stages = [] # only run...
from kivy.gesture import GestureDatabase from kivy.uix.boxlayout import BoxLayout from kivy.gesture import Gesture # 生成的手势字符串 gesture_strings = { 'top_to_bottom_line':'eNptl2tQlFUYxxcvqGQBooYoQWW6lindL2a7lbXdJURbBRQW3lwEYZ+9KKgHQQ26WCJhiIZShlommRRh4YjD4EzNVBRdjKjB8UszlVnTB0c/2Nl3nmfmP2fcOQMvv/2dPc/5v897gOqRhSXFayr...
# port of https://phab.hepforge.org/source/fastjetsvn/browse/contrib/contribs/ConstituentSubtractor/tags/1.4.4/example_event_wide.cc # to python w/ heppy import fastjet as fj import fjcontrib from pyjetty.mputils import MPBase class CEventSubtractor(MPBase): def __init__(self, **kwargs): # constants # self.max_e...
import os from dataset import audio_dataset from torch.utils.data import DataLoader from utils import reconstruction_plot, attention_plot, create_folder from tqdm import tqdm def get_dataloader(data_path, yaml_path, args, cuda): train_dataset = audio_dataset(data_path, yaml_path, args.val_fold, train = True) v...
from django.contrib.auth import get_user_model from rest_framework import serializers from apps.auction.models import Lot, Bet User = get_user_model() class LotSerializer(serializers.ModelSerializer): class Meta: model = Lot fields = [ 'id', 'starting_price', 'pet', 'seller', 'statu...
from read_only_guard import ReadOnlyGuard from pathlib import Path from crypto import Crypto from datetime import datetime import shutil class Diary: def __init__(self, filename, readonly): self._filename = filename self._readonly_guard = ReadOnlyGuard(readonly=readonly) self._contents = "...
# encoding: utf-8 from abc import abstractmethod, ABCMeta from configparser import ConfigParser from src.utils import singleton import logging.config import logging import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../')) logging.config.fileConfig(fname='log.config', disable_existing_logge...
import logging from sleekxmpp import ClientXMPP from inbetween import pull_data # from sleekxmpp.exceptions import IqError, IqTimeout # noinspection PyMethodMayBeStatic class EchoBot(ClientXMPP): def __init__(self, jid, password): ClientXMPP.__init__(self, jid, password) self.add_event_handl...
''' MIT License Copyright (c) 2017 Sterin, Farrugia, Gripon. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, mer...
#-*- coding: utf-8 -*- import unittest from litefs import TreeCache class TestTreeCache(unittest.TestCase): def setUp(self): self.cache = TreeCache(clean_period=60, expiration_time=3600) def test_put(self): caches = { 'k_int': 1, 'k_str': 'hello', 'k_float...
from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='gsheetapi', version='0.1.0', description='Sample Stuff for Implement Google Sheet API', long_description=readme, author='Fathur Rohman', ...
from urllib.request import urlopen as uRep from bs4 import BeautifulSoup as soup start_url='https://www.mytek.tn/3-informatique' links=[] max_page=1 current_page=0 def Article(url): global links uClient = uRep(url) page_html = uClient.read() uClient.close() page_soup = soup(page_html,"html.pars...
from hashlib import sha224 users = ([1, 'bob', 'secret'],[2, 'alice', 'sekrit'], [3, 'eve', 'secret']) for user in users: user[2] = sha224(user[2]).hexdigest()[:8] print users