text
stringlengths
38
1.54M
class PartyAnimal: x = 0 name = '' # constructor with variab;e def __init__(self, z): self.name = z print('I am constructed') def party(self): self.x = self.x + 1 print(self.name, 'So far', self.x) # destructor def __del__(self): print('I am destruct...
import random def display_board(board): print('\n'*100) print(board[7] + ' | ' + board[8] + ' | ' + board[9]) print('-------------') print(board[4] + ' | ' + board[5] + ' | ' + board[6]) print('-------------') print(board[1] + ' | ' + board[2] + ' | ' + board[3]) de...
myfirstlist = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] print(myfirstlist) listone = range(10,21) print(listone) listtwo = [0, 0, 0, 0, 0] print(listtwo) emptylist = [] print(emptylist) listfour = [] for i in range(5): listfour.append(0) print(listfour) listfive = ["a", 5, "doodle", 3, 10] p...
def only_randint(): from random import randint x = randint(5,15) return x print(only_randint())
#-*- coding: UTF-8 -*- import logging import urllib import urllib2 from django.conf import settings from django.utils.encoding import smart_str from sendsms.backends.base import BaseSmsBackend logger = logging.getLogger(__name__) HTTP_URL = 'http://api.infosmska.ru/interfaces/SendMessages.ashx' USERNAME = settings...
from .base import Base import os class Prune(Base): """Prompts the user to prune their docker environment""" def run(self): os.system("docker system prune")
""" Copyright 2014 Rackspace 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 to in writing, software dist...
from enum import Enum class Bound(Enum): UPPER = 'ub' LOWER = 'lb' class Op(Enum): ADD = 0 MINUS = 1
from setuptools import setup setup( name='bitbelt', packages=['bitbelt'], include_package_data=True, install_requires=[ 'flask', 'pymongo', 'mongoengine', 'six' ] )
inputFile = open ('myimage.jpg', 'rb') outputFile = open ('myoutputimage.jpg', 'wb') msg = inputFile.read(10) while len(msg): #outputFile.write(msg + '\n') outputFile.write(msg) msg = inputFile.read(10) inputFile.close() outputFile.close()
# -*- coding: utf-8 -*- __author__ = 'karavanjo' from models import * from helpers import * from decorators import authorized from pyramid.view import view_config from pyramid.response import Response from sqlalchemy import func, distinct, and_ from sqlalchemy.orm import joinedload from sqlalchemy.sql.expression impor...
import requests import format Servers = [] def Submit(url): with requests.Session() as s: r = requests.Request(method='GET', url=url) prep = r.prepare() prep.url = url return s.send(prep, verify=False, timeout=2) def Scan(ip, port): try: print("Scanning for CVE-2019-...
from getpass import getpass from quantuminspire.credentials import get_token_authentication, get_basic_authentication def get_authentication(qi_email=None, qi_password=None, token=None): """ Gets the authentication for connecting to the Quantum Inspire API.""" if token is not None: return get_token_au...
import boto3 import json import os from datetime import date datetime = str dynamodb = boto3.client('dynamodb') def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) SG = event["queryStringParameters"]["Security_Group"] print (SG) SG_region = event["queryStringPa...
#! /usr/bin/env python ########################################################################## # CAPSUL - Copyright (C) CEA, 2013 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html ...
"""""Given an array nums of n integers, are there elements a, b, c in nums such # that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. #Note: #The solution set must not contain duplicate triplets. #Example: #Given array nums = [-1, 0, 1, 2, -1, -4], #A solution set is: [ [-1, 0, 1]...
import sys, math from autobahn.websocket import connectWS from twisted.python import log from twisted.internet import defer, reactor from autobahn.websocket import listenWS from autobahn.wamp import exportRpc, \ WampServerFactory, \ WampServerProtocol, WampClientFac...
# 257. Binary Tree Paths # Given a binary tree, return all root-to-leaf paths. # Note: A leaf is a node with no children. # Example: # Input: # 1 # / \ # 2 3 # \ # 5 # Output: ["1->2->5", "1->3"] # Explanation: All root-to-leaf paths are: 1->2->5, 1->3 # Definition for a binary tree node. # class T...
import pygame, sys, time, random from pygame.locals import * class MySprite(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('platform.png').convert() self.rect = self.image.get_rect() self.x = 0 self.y = 0 ...
def largest_sum(arr): if (len(arr) == 0): return max_sum = current_sum = arr[0] for num in arr[1:]: current_sum = max(current_sum + num, num) max_sum = max(current_sum, max_sum) return max_sum print(largest_sum([7,8,4,-5,22,3,5,-9,12,15,-4]))
#!/usr/bin/env python import rospy from std_msgs.msg import String, Bool import sys class Timer(): def __init__(self): # Get system start time until clock actually starts self.start_time = rospy.get_time() while self.start_time == 0.0: self.start_time = rospy.get_time() ...
n = int(input('Введите количество чисел в массиве ')) print('Введите число ') print('Вводим массив') # Вводим элементы массива A i = 0 A = [] # Проверка на то, что вводят число for j in range(n): x = input() if x.isdigit(): A.append(int(x)) if len(A) == 0: print('Введите хотя...
# -*- coding: utf-8 -*- from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule, Request from items import VideoScrapyItem class IqiyiSpider(CrawlSpider): name = 'iqiyi' allowed_domains = ['iqiyi.com'] start_urls = ['http://news.iqiyi.com/'] rules = ( Rule...
metros = float(input('Digite o valor em metros: ')) print('{} metros é igual à {} centimetros'.format(metros, metros*100)) print('{} metros é igual à {} milimetros'.format(metros, metros*1000))
# Generated by Django 3.0.5 on 2020-08-27 17:05 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recommend_system', '0018_click_item'), ] operations = [ migrations.AddField( model_name='contact_broker', ...
#!/bin/env python ## # @file # This file is part of SeisSol. # # @author Alex Breuer (breuer AT mytum.de, http://www5.in.tum.de/wiki/index.php/Dipl.-Math._Alexander_Breuer) # # @section LICENSE # Copyright (c) 2013, SeisSol Group # All rights reserved. # # Redistribution and use in source and binary forms, with or wit...
''' Kepler-442b Author: Rudolf M. Created for Python Programming competition April-May 2020 ''' import pygame import random import math from image_loader import* from sound_loader import* from initial_values import* t = pygame.time.Clock() pygame.init() win = pygame.display.set_mode((720, 480)) pygame.display.set_cap...
# Generated by Django 2.0.1 on 2018-01-18 15:15 import biography.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('entity', '0002_auto_20180117_2043'), ('biography', '0001_initial'), ] operations = ...
def add_units(a , b): return a + b print (add_units(2,5)) c = 12.34656 um = 412443.1343 print(c) print(float(c)) ###print(int(c)) word = "helloa" print(word.replace("a","e")) print(word.capitalize()) print(word.isalpha()) "aqwe,qwqtqwr,qwewe".split(",") "my name is {0} and i love {1}".format(word, c) check...
# Using range for loops. Range only takes integers. for num in range(1,5): print (num) # Result will be -> # 1 # 2 # 3 # 4 # While Loop x = 10 while x > 0: print ('X is ' + str(x)) x -= 1
__author__ = 'Nic' import numpy import os import scipy.io import datetime from collections import namedtuple # Manually set here the path to the pyCSalgos package # available at https://github.com/nikcleju/pyCSalgos import sys, socket hostname = socket.gethostname() if hostname == 'caraiman': pyCSalgos_path = '/h...
# Trimmed lilac.py #!/usr/bin/env python3 # # This file is the most simple lilac.py file, # and it suits for most packages in AUR. # from lilaclib import * PATCH = b""" diff --git a/archlinuxcn/vivaldi/PKGBUILD b/archlinuxcn/vivaldi/PKGBUILD index 2b1aeb2df..9a9868e2a 100644 --- a/archlinuxcn/vivaldi/PKGBUILD +++ b/a...
import numpy as np import cv2 import matplotlib.pyplot as plt import random import glob import numba as nb import time from segment import Segment from statistics import mean from itertools import product from multiprocessing import Pool @nb.jit def vertical_match(upper,lower): matches=[] for u in upper: ...
#!/usr/bin/python3 from gpiozero import LED, PingServer from gpiozero.tools import negated from signal import pause green = LED(17) red = LED(22) RPIold = PingServer('192.168.2.106') green.source = RPIold green.source_delay = 5 red.source = negated(green) pause()
# -*-coding: UTF-8-*- """ Autor: Matthias Herbein Erstellt: 04.10.2018 Ueberarbeitet: heute Py Version: 3.6 Beschreibung: Der Nutzer kann einer Feature Class oder einem Layer mit Hilfe dieses Tools neue Felder in der Attributtabelle hinzufuegen. Der Nutzer kann dabei meh...
# Author: Branden Kim # Assignment: 5 # Description: Recursive function to print out pascal's triangle def pascals(cur_level, num_levels, level_list): if cur_level > num_levels: return level_list elif cur_level == 0: level_list.append([1]) elif cur_level == 1: level_list.append([1,...
import tkinter as tk from app import App def center(win): win.update_idletasks() width = win.winfo_width() height = win.winfo_height() x = (win.winfo_screenwidth() // 2) - (width // 2) y = (win.winfo_screenheight() // 2) - (height // 2) win.geometry(f'+{x}+{y}') if __name__ == '__main__': ...
import tensorflow as tf from examples.autoencoder.layer_utils import get_deconv2d_output_dims def conv(input, name, filter_dims, stride_dims, padding='SAME', non_linear_fn=tf.nn.relu): input_dims = input.get_shape().as_list() assert(len(input_dims) == 4) # batch_size, height, width, num_channels_in ...
import json import logging import os from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError HOOK_URL = os.environ['HOOK_URL'] logger = logging.getLogger() logger.setLevel(logging.INFO) def handler(event, context): logger.info("Event: " + str(event)) message = json.loads(ev...
from flask_sqlalchemy import SQLAlchemy from flask import Flask from flask_script import Manager import os basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] =\ 'sqlite:///' + os.path.join(basedir, 'data.sqlite') app.config['SQLALCHEMY_COMMIT_ON_TEARD...
# -*-coding:Utf-8 -* """File containing the base of all obstacles.""" class Obstacle: """Class representing all obstacles. Obstacles are herited from this class. She defined further methods and attributs. You need maybe to modified this methods or attributs in the class daughter. """ ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """Exposes interfaces of benchmarks used by SuperBench executor.""" from superbench.benchmarks.return_code import ReturnCode from superbench.benchmarks.context import Platform, Framework, Precision, ModelAction, BenchmarkType, BenchmarkContext f...
import time import image from character.base import Character class Hero(Character): def __init__ (self, name='Becky', health=10, power=4, attack='gore', evade=0, coins=8, win_count=0): super().__init__(name, health, power, attack, evade, coins) self.win_count = win_count @classmethod de...
# -*- coding: utf-8 -*-# #------------------------------------------------------------------------------- # Name: DrawMultiLine # Description: # Author: Dell # Date: 2019/10/6 #------------------------------------------------------------------------------- ''' 绘制不同类型的直线 ''' import sys from ...
# # Project: # glideinWMS # # File Version: # # Description: # Frontend creation module # Classes and functions needed to handle dictionary files # created out of the parameter object # import os,os.path,shutil,string import cvWDictFile,cWDictFile import cvWConsts,cWConsts import cvWCreate from glideinwms.li...
#!/usr/bin/env python import rospy from std_msgs.msg import String, Header from geometry_msgs.msg import Twist import serial import time import pygame as pyg from joystick_utils import SlaveContact class RoboController(): def __init__(self,port,baud_rate): self.slave = SlaveContact(port,baud_rate) ...
def int_numbers(a,b): if a < b: for i in range(a, b + 1): yield i else: for i in range(a, b - 1, -1): yield i a1 = int(input("Введите целое число A: ")) b1 = int(input("Введите целое число B: ")) for num in int_numbers(a1,b1): print(num)
import numpy as np #默认为浮点数 x=np.ones(5) print(x) #自定义类型 x=np.ones([2,2],dtype=int) print(x)
""" Copy metainfo files from Transmission for backup. Usage: clutchless archive [--dry-run] [--errors] <destination> Arguments: <destination> Directory where metainfo files in Transmission will be copied. Options: --errors Moves files into folders below the archive directory according to their e...
import pygame from pygame.sprite import Sprite from pygame.sprite import Group class Alien(Sprite): """Aliens of the game""" def __init__(self, screen): super(Alien, self).__init__() self.speed = 1 self.direction = 1 self.rows = 4 self.screen = screen self.image = pygame.image.load('...
from circulo import Circulo # importando a classe circulo from retangulo import Retangulo # importando a classe retangulo from triangulo import Triangulo # importando a classe triangulo from trapezio import Trapezio # importando a classe Trapezio print("Programa para calcular formas geométricas") # Nome do Programa...
class A: vc = 123 a1 = A() a2 = A() A.vc = 321 # eu consigo mudar todos os valores da variável , mas não da classe, mesmo que já tenha lá #se eu quiser realmente alterar o valor de uma variável de classe: A.vc = "Alterado" print(a1.vc) # pegando o valor da variavel da classe q está disponível para todas as inst...
from matplotlib.pyplot import * import numpy as np big = 1.1 figure(figsize=(big*5,big*2)) ax = axes() ax.set_position([0.15, 0.2, 0.8, 0.7]) T = 2 max_seq = 2**4 max_time = 40 ax.plot(np.arange(max_seq), color = 'black') ax.plot(np.arange(T, max_seq + T), np.arange(max_seq), color = 'black') ax.plot(np.arange(max_s...
from os.path import dirname from os.path import join import numpy as np from astropy.io import fits from sklearn import preprocessing class Bunch(dict): """Container object for datasets: dictionary-like object that exposes its keys as attributes.""" def __init__(self, **kwargs): dict.__init__(s...
''' Автомат обрабатывает натуральное число N по следующему алгоритму: 1. Строится троичная запись числа N. 2. В конец записи (справа) дописывается остаток от деления числа N на 3. 3. Результат переводится из троичной системы в десятичную и выводится на экран. Пример. Дано число N = 11. Алгоритм работает следующим образ...
from numbers import Number from manimlib import * import numpy as np class problemIntro(Scene): def construct(self): text = """ Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. """ ...
from __future__ import unicode_literals from django.apps import AppConfig class NegotConfig(AppConfig): name = 'Negot'
""" It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written...
import argparse import csv import math import glob import librosa import pandas as pd from subcommands.create_samples import create_samples from subcommands.classify_file import classify_file if __name__ == "__main__": parser = argparse.ArgumentParser(description="Sonumator") subparsers = parser.add_su...
# Generated by Django 2.2 on 2019-09-08 14:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('generes', '0001_initial'), ] operations = [ migrations.CreateModel( name='Mov...
// https://leetcode.com/problems/two-sum-iii-data-structure-design class TwoSum: def __init__(self): """ Initialize your data structure here. """ self.map={} def add(self, number): """ Add the number to an internal data structure.. :type number: int ...
import string print("Our punct:", string.punctuation) def clean_punkts(srcpath,destpath, badchars = string.punctuation): with open(srcpath,mode="r", encoding="utf-8") as inf, open(destpath,mode="w", encoding="utf-8") as outf: # for line in inf: # for char in badchars: # line = li...
#!/usr/bin/env python from unittest import main, TestCase import numpy as np import pandas as pd from pandas.util.testing import assert_frame_equal, assert_index_equal from neurokernel.plsel import PathLikeSelector, PortMapper df1 = pd.DataFrame(data={'data': np.random.rand(12), 'level_0': ['foo'...
#!/usr/bin/python # -*- coding: UTF-8 -*- import os import io import sys import re import urllib.request from bs4 import BeautifulSoup from urllib.parse import quote import string import operator; import xlwt #sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8') #获取当前脚本文件所在的路径 def cur_file_dir(): #...
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'changeCarNumber.ui' ## ## Created by: Qt User Interface Compiler version 5.14.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ##########...
from django.shortcuts import render from django.http import HttpResponse from django.template.loader import get_template from django.template import Context, Template from .models import * import datetime # Create your views here. def index (request): p = Food.objects.all() now = datetime.datetime.now() t...
# -*- coding: utf-8 -*- # author: seven from pocsuite3.api import register_poc, POCBase, Output,logger,POC_CATEGORY,requests from pocsuite3.lib.core.threads import run_threads import json class ElasticsearchUnauthPOC(POCBase): vulID = '' version = '1.0' author = ['seven'] vulDate = 'Aug 9, 2020' cr...
import json from datetime import datetime, timedelta from typing import Dict, List, Optional import requests from dateutil import parser import pytz from requests.exceptions import HTTPError tz_vienna = pytz.timezone("Europe/Vienna") def get_local_now(): return datetime.now(tz_vienna) def parse_local(time): ...
import datetime from django.conf import settings from django.contrib.sites.models import Site from conescy.apps.stats.models import Day from conescy.apps.stats.utils import * from conescy.apps.stats.processor import process_request class AddToStats(object): """Add current request to stats if it is 200! The respon...
# TODO - commade with argument is handle but the revershell can't resolve it # 1 - Import the right module import socket import pyfiglet import os # Upload File Test file_test = "test2.txt" # Pyfiglet stuff pyflig = pyfiglet.figlet_format("Revers Shell") # 2 - Server IP / Port server_conf = 'localho...
from time import time # All custom events # MOUSE CUSTOM EVENTS LEFTMOUSEBUTTONHOLD = "LMB" LEFTMOUSEBUTTONPRESS = "LMBP" RIGHTMOUSEBUTTONHOLD = "RMB" RIGHTMOUSEBUTTONPRESS = "RMBP" ANYMOUSEBUTTONHOLD = "AMBH" ANYMOUSEBUTTONPRESS = "AMBP" # KEYBOARD EVENT from pygame.locals import * keys = [K_BACKSPACE, K_T...
#!/usr/bin/python # -*- coding: utf-8 -*- from api_dict import api_dict SuitDict = { 'LoginSuit':[api_dict['Login']['cls_name'],api_dict['Login']['cls_name'],api_dict['Login']['cls_name'],api_dict['PersonDriverLogin']['cls_name']], 'GetCreatOrderData':[api_dict['SearchCustomer']['cls_name'],api_dict['S...
def find_characters(my_list, char_check): new_list = [] for num in my_list: if (num.find(char_check) > 0): new_list.append(num) print new_list word_list = ['hello','world','my','name','is','Anna'] char = 'o' find_characters (word_list, char)
"""empty message Revision ID: 7b5e316395a5 Revises: 72dff322d778 Create Date: 2020-09-25 18:35:15.811595 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7b5e316395a5' down_revision = '72dff322d778' branch_labels = None depends_on = None def upgrade(): # ...
# Solution # O(n) time / O(n) space def sunsetViews(buildings, direction): buildingsWithSunsetViews = [] startIdx = 0 if direction == "WEST" else len(buildings) - 1 step = 1 if direction == "WEST" else - 1 idx = startIdx runningMaxHeight = 0 while idx >= 0 and idx < len(buildings): bu...
#!/usr/bin/env python3 # Requires PyAudio and PySpeech. from practicum import find_mcu_boards from peri import McuWithPeriBoard from time import sleep import speech_recognition as sr r = sr.Recognizer() order = "hello" import pyautogui, sys , time center_x=int(pyautogui.size()[0]/2) center_y=int(pyautogui.size()[1]/...
#!/usr/bin/env python from abc import ABCMeta from abc import abstractmethod """ generated source for module Shape """ # Abstract Class class Shape(object): """ generated source for class Shape """ __metaclass__ = ABCMeta @abstractmethod def area(self): """ generated source for...
from sys import argv from os.path import exists script, from_file, to_file = argv # # print("Copying from %s to %s" % (from_file, to_file)) # # we could do these two on one line too, how? # # by invoking open on the from_file, we create a file object (io) # in_file = open(from_file) # # invoking read on the file obj...
from setuptools import setup, find_packages def readfile(name): with open(name) as f: return f.read() readme = readfile('README.rst') changes = readfile('CHANGES.rst') requires = [ 'pyramid' ] docs_require = [ 'Sphinx', 'pylons-sphinx-themes', ] tests_require = [ 'pytest', 'pytest...
#-*- coding: utf-8 -*- ''' logMonitor, Created on Apl, 2015 #version: 1.0 ''' import logging #import time import datetime class LogMonitor: def __init__(self): self.logger=logging.getLogger() self.handler=logging.FileHandler("./_log/LogHistory_"+str(datetime.date.today())+".txt") self.l...
from django.contrib.auth.models import User from django.db import models class Urls(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owners', null=True) url = models.URLField(max_length=200) sorturl = models.CharField(max_length=200) changeurl = models.URLField(ma...
#!usr/bin/env python ''' BuildManager.py by Mitchell Nordine A script used for managing the process of compiling and running C++ programs. So far it... - Checks for headers and rebuilds clang_complete commands if required. Usage: BuildManager.py [-h | --help] [-v | --version] BuildManager.py [--lang=<ext...
import tkinter import matplotlib from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import numpy root = tkinter.Tk() root.wm_title("Sample genrator") figure = Figure(figsize=(5, 5), dpi=150) plot = figure.add_subplot(1,1,1) plot.axis([0, 1.1, 0, 1.1]) canvas = Figu...
import population import genotype import mutators from random import randint import timeCounter def ga(time, popSize=100): pop = population.generatePop(popSize) # make population pop = population.sort(pop) # sort by fitness best = pop[0] # best of the pop always index 0 after sort noImprove = 0 ti...
from django.conf.urls import patterns, include, url from test1.views import index from test1.views import fuck from blog.views import intro from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: #url(r'^$', 'test1.views.home', name='home'), #url(r'^blog/', include('bl...
import numpy as np import matplotlib.pyplot as plt import sys pcl = sys.argv[5] var1 = sys.argv[1] var2 = sys.argv[2] var3 = sys.argv[3] var4 = sys.argv[4] txtend = str(pcl) + '_VAR1_' + str(var1) + '_VAR2_' + str(var2) + '_VAR3_' + str(var3) + '_VAR4_' + str(var4) A = np.loadtxt('TTapPCL_' + txtend + '.txt') apds = ...
import argparse from PIL import Image import random import time import urllib, cStringIO from display import Display from matrix import Matrix if __name__ == "__main__": parser = argparse.ArgumentParser(description='Show image stream from url on led matrix, will refetch image for every frame') parser.add_argu...
import re,sys import xml.dom.minidom def printToFile(content,filename): firstname=filename.split(".")[0] newname=firstname+"_cl.coref" f = open(newname, 'w') f.write(content) f.close() def removeEmptyCat(filename): f = open(filename, 'r') raw=f.read() insBefore=addNewlineBefore(raw...
# # Copyright 2015-2020 CNRS-UM LIRMM, CNRS-AIST JRL # import collections import copy import csv import ctypes import functools import json import numpy as np import os import re import signal import sys import tempfile from functools import partial from PyQt5 import QtCore, QtGui, QtWidgets from . import ui from ....
#!/usr/bin/env python """ Get raw data for pacbio from Mount Sinai """ import sys , io ,os , urllib import optparse, logging class ReadGetter: def __init__( self ): self.__parseArgs( ) self.__initLog( ) def __parseArgs( self ): """Handle command line argument parsing""" ...
from django import forms from api.models import UploadFileModel, Post class UploadFileModelForm(forms.ModelForm): class Meta: model = UploadFileModel fields = ('user', 'file') app_label = 'api' class PostForm(forms.ModelForm): class Meta: model = Post fields = ('user...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-29 08:35 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users_app', '0010_profile_dispensary'), ] operations = [ migrations.AddFiel...
from distutils.core import setup setup( name='django-verbose-logging', version='0.0.1', packages=['django_verbose_logging'], package_dir={'': 'src'}, url='https://github.com/TargetHolding/django-verbose-logging', license='Apache License 2.0', description='Verbose exception logging for Djang...
import dash_bootstrap_components as dbc import dash_html_components as html import dash_core_components as dcc import plotly.offline as pyo import plotly.graph_objs as go statslayout = html.Div([ dcc.Location(id='stats-url', pathname='/stats'), dbc.Container( [dbc.Row( ...
from flask import Blueprint, render_template, request, flash, jsonify,redirect from flask_login import login_user, login_required, logout_user, current_user from .models import Activity, Cardio from . import db import json views = Blueprint('views', __name__) @views.route('/', methods = ['GET']) @login_required def ...
from combat.defenseresult import DefenseResult from combat.defenses.base import Defense from echo import functions class ArmorAbsorb(Defense): name = "Armor Absorb" description = "Your Armor absorbs the damage." attacker_message = "but your {attacker_weapon} glances off {defender_his} {defender_armor}!" ...
def isPrime(x): if x == 1 or x == 0: return False for y in range(2, int(x / 2) + 1): if x % y == 0: return False return True def digitPrime(x): for digit in str(x): if not isPrime(int(digit)): return False return True sum = 0 for x in range(10000): ...
from base_app.models.mongodb.keyword.keyword import KeyWordModel __author__ = 'Morteza' class KeyWordClass: def __init__(self, user_keyword=None): self.user_keyword = user_keyword def get_keyword_info(self, __key): user_keywords = self.user_keyword r = filter(lambda _key: _key['_id']...
# Copyright (C) 2021 # Author: Kacper Sokol <ks1591@my.bristol.ac.uk> # License: new BSD """ Implements the `cssterm` directive for Jupyter Book and Sphinx. """ import os import sys from docutils import nodes from docutils.parsers.rst import Directive import sphinx_term DEPENDENCIES = { # See sphinx_term/_static/R...
import requests import json class VoiceToText: UNKNOWN_ERROR = 'X' CODES = {'-1': '認証に失敗しました。', '-2': '必須パラメータがありません。', '-3': '音声データがありません。', '-4': '音声認識サーバー側でエラーが発生しました。', '-5': '無効なEngineModeが指定されました。', '1': '利用回数制限を超えています。', ...