Beispiel #1
0
async def on_ready():
    # global calls so we can modify these variables
    global isReady
    global RolesManager
    global googleSheet
    global discordG

    print(f'{client.user} has connected to Discord')

    for guild in client.guilds:
        if guild.name == GUILD:
            break

    discordG = guild
    rosterChan = None
    for channel in guild.text_channels:
        if channel.id == chanIds["roster"]:
            rosterChan = channel

    googleSheet = Spreadsheet(os.getenv('SHEET_IDENTIFIER'))
    RolesManager = AshesRolesManager(rosterChan, discordIds, googleSheet)
    await RolesManager.init(discordIds, guild)

    isReady = True
    print("Setup complete")
 def test_advance_column(self):
     spreadsheet = Spreadsheet()
     self.assertEqual(spreadsheet.current_cell(), 'A1')
     spreadsheet.advance_column()
     self.assertEqual(spreadsheet.current_cell(), 'B1')
     spreadsheet.advance_column()
     self.assertEqual(spreadsheet.current_cell(), 'C1')
def check_requests(request_type, auth_file, worksheet_key):
    """Check for new approved requests"""
    sheet = Spreadsheet(keyfile=auth_file, sheet_id=worksheet_key)
    rows = sheet.get_all_rows('Form Responses 1')
    timestamp = datetime.now().strftime("%d %b %Y %H:%M:%S")
    processed_rows = []

    # set som type-specific things
    if request_type == 'access':
        parse_function = parse_user_row
        csr_type = 'Access Request'

    elif request_type == 'quota':
        parse_function = parse_quota_row
        csr_type = 'Quota Request'
    else:
        raise Exception('Unknown request type: `{}`'.format(request_type))

    for idx, row in enumerate(rows):

        if (idx == 0) or (row == []):
            # skip header row and blank rows
            continue

        elif (row[0].lower().strip() == 'approved') and (row[1] == ''):
            # process rows that are marked approved but not notified
            request_info = parse_function(row)
            notify_helpdesk(template=helpdesk_template,
                            sender=helpdesk_email,
                            receiver=helpdesk_email,
                            csr_type=csr_type,
                            priority='High',
                            queue='Monitoring',
                            **request_info)

            processed_rows.append(idx)
            if args.log:
                log_request(args.log, timestamp, request_info['user_email'])

        elif (row[0] == '') and (datetime.now() >= dateparser.parse(row[2]) +
                                 timedelta(hours=24)):
            # send reminder about rows that have been waiting for approval
            # for more than 24 hours
            request_info = parse_function(row)
            reminder(template=reminder_template,
                     sender=reminder_email,
                     receiver=reminder_email,
                     request_type=request_type,
                     **request_info)

        else:
            # skip over unapproved or already-notified rows
            continue

    # Google API returns an error if you send an empty request
    if processed_rows:
        timestamp_spreadsheet(sheet, timestamp, processed_rows)
 def test_letter(self):
     spreadsheet = Spreadsheet()
     self.assertEqual(spreadsheet.letter(0), 'A')
     self.assertEqual(spreadsheet.letter(25), 'Z')
     self.assertEqual(spreadsheet.letter(26), 'AA')
     self.assertEqual(spreadsheet.letter(27), 'AB')
     self.assertEqual(spreadsheet.letter(51), 'AZ')
     self.assertEqual(spreadsheet.letter(52), 'BA')
     self.assertEqual(spreadsheet.letter(77), 'BZ')
     self.assertEqual(spreadsheet.letter(78), 'CA')
 def __init__(self, test_setup_info, test_data_collection):
     self.path = Test_Data_Persistence.test_data_path + str(test_setup_info)
     self.test_data_collection = test_data_collection
     self.spreadsheet_mode = True
     self.data_plot_mode = True
     self.tzero_mode = True
     self.spreadsheets = {}
     
     for key, value in self.test_data_collection.items():
         self.spreadsheets[key] = Spreadsheet(self.path, key, value)
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowIcon(QIcon(":/images/icon.png"))
        self.setCurrentFile("")

        # ----------- 数据 -------------
        self.spreadsheet = Spreadsheet()
        self.setCentralWidget(self.spreadsheet)

        self.findDialog = None
        self.locationLabel = None
        self.formulaLabel = None
        self.recentFiles = None  # QStringList recentFiles;
        self.curFile = None  # QString curFile;

        self.MaxRecentFiles = 5
        self.recentFileActions = [None] * self.MaxRecentFiles
        #
        self.separatorAction = None
        # #
        self.fileMenu = None
        self.editMenu = None
        self.selectSubMenu = None
        self.toolsMenu = None
        self.optionsMenu = None
        self.helpMenu = None
        self.fileToolBar = None
        self.editToolBar = None
        self.newAction = None
        self.openAction = None
        self.saveAction = None
        self.saveAsAction = None
        self.exitAction = None
        self.cutAction = None
        self.copyAction = None
        self.pasteAction = None
        self.deleteAction = None
        self.selectRowAction = None
        self.selectColumnAction = None
        self.selectAllAction = None
        self.findAction = None
        self.goToCellAction = None
        self.recalculateAction = None
        self.sortAction = None
        self.showGridAction = None
        self.autoRecalcAction = None
        self.aboutAction = None
        self.aboutQtAction = None
        # self.qApp = QApplication([]) # 这样写 有问题

        self.createActions()
        self.createMenus()
        self.createContextMenu()
        self.createToolBars()
        self.createStatusBar()
 def test_cells(self):
     spreadsheet = Spreadsheet()
     self.assertEqual(spreadsheet.current_cell(), 'A1')
     spreadsheet.set_value('1')
     self.assertEqual(spreadsheet.current_cell(), 'B1')
     spreadsheet.set_value('1', advance_row=True)
     self.assertEqual(spreadsheet.current_cell(), 'A2')
     spreadsheet.set_value('1', advance_by_rows=3)
     self.assertEqual(spreadsheet.current_cell(), 'A5')
     spreadsheet.set_values(['1'])
     self.assertEqual(spreadsheet.current_cell(), 'A6')
Beispiel #8
0
def show_all():
    # TODO make toolbar buttons work
    ntb = backend_bases.NavigationToolbar2
    ntb.toolitems = (
        ('Home', 'Reset original view', 'home', 'home'),
        (None, None, None, None),
        ('Back', 'Back to  previous view', 'back', 'back'),
        ('Forward', 'Forward to next view', 'forward', 'forward'),
        (None, None, None, None),
        ('Save', 'Save the figure', 'filesave', 'save_figure'),
    )
    for column in Spreadsheet().columns():
        TTest(
            title=column.get_title(),
            measure_unit=column.get_unit(),
            instrument_error=column.get_instr_err(),
            nums=column.get_nums(),
            dpi=130,
        ).express_solution()
    plt.show()
def main():
    session = Session()
    session.start_session()
    creds = session.get_credentials()

    spreadsheet = Spreadsheet(creds)

    while True:
        operation = int(input('Operations:\n1 - Read sheet\n2 - Update sheet\n3 - Cancel\n'))
        if operation == 1:  
            values = spreadsheet.get_spreadsheet_values("A1:E12")
            spreadsheet.print_sheet(values)
        elif operation == 2:
            payment_one = int(input('Payment One: '))
            payment_two = int(input('Payment Two: '))
            month = int(input('Month: '))
            spreadsheet.insert_values_in_sheet(payment_one, payment_two, month)
        elif operation == 3:
            break
        else:
            print('Invalid operation!')
Beispiel #10
0
def import_to_googlesheets(records, search_term, credentials):
    ss = Spreadsheet(credentials, debug_mode=False)
    try:
        f = open('temp.txt', 'x')
        email = input('Email: ')
        ss.create('Amazon', search_term)
        ss.share_with_email_for_writing(email)
        f.write(ss.spreadsheet_id)
        f.close()
    except FileExistsError:
        f = open('temp.txt', 'r')
        ss.set_spreadsheet_by_id(f.read())
        try:
            ss.add_sheet(search_term)
        except googleapiclient.errors.HttpError:
            ss.set_sheet_by_title(search_term)
            ss.clear_sheet()
        f.close()
    finally:
        ss.prepare_set_values('A1:E1', [['Name', 'Price', 'Rating', 'Reviews', 'Url']])
        ss.prepare_set_values('A2:E%d' % (len(records) + 1), records)
        ss.run_prepared()
 def test_get_sheet(self):
     spreadsheet = Spreadsheet()
     self.assertFalse('Stats' in spreadsheet.workbook.sheetnames)
     sheet = spreadsheet.get_sheet('Stats')
     self.assertEqual(sheet.title, 'Stats')
Beispiel #12
0
def cli_summary_write(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.summary_write(args.spreadsheet_dir)
Beispiel #13
0
       text="Pie Chart",
       width=button_width,
       command=lambda: switch_window(pie_chart)).pack()
button_frame.grid(column=0, row=0, sticky="NW")

# Creates content at the right
content_frame = Frame(root)
content_frame.grid(column=1, row=0)

main_window_list = []

home = Home(content_frame)
main_window_list.append(home)

num_of_cases = NumOfCases(content_frame)
main_window_list.append(num_of_cases)

spreadsheet = Spreadsheet(content_frame)
main_window_list.append(spreadsheet)

time_plot = TimePlot(content_frame)
main_window_list.append(time_plot)

pie_chart = PieChart(content_frame)
main_window_list.append(pie_chart)

current_window = home
current_window.pack()

root.mainloop()
Beispiel #14
0
def cli_summary_read(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.summary_read(args.spreadsheet_dir, args.reset)
Beispiel #15
0
def cli_summary_transform(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.summary_transform(args.fracking)
Beispiel #16
0
def cli_write(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.write(args.spreadsheet_dir, args.editable, args.reset)
Beispiel #17
0
def cli_matches(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.matches(args.spreadsheet_dir)
Beispiel #18
0
def check_requests(request_type, auth_file, worksheet_key):
    """Check for new approved requests"""
    # Some definitions that should eventually be set in config
    TIMESTAMP_FORMAT = "%d %b %Y %H:%M:%S"
    # hours until first reminder sent
    reminder_start = timedelta(hours=int(config.get('reminder', 'start')))
    # interval to send subsequent reminders
    reminder_interval = timedelta(
        hours=int(config.get('reminder', 'interval')))
    sheet = Spreadsheet(keyfile=auth_file, sheet_id=worksheet_key)
    rows = sheet.get_all_rows('Form Responses 1')
    timestamp = datetime.now().strftime(TIMESTAMP_FORMAT)
    processed_rows = []
    reminder_list = []
    reminder_rows = []
    now = datetime.now()

    # set some type-specific things
    if request_type == 'Access':
        parse_function = parse_user_row
        csr_type = 'Access Request'

    elif request_type == 'Quota':
        parse_function = parse_quota_row
        csr_type = 'Change Quota'
    else:
        raise Exception('Unknown request type: `{}`'.format(request_type))

    for idx, row in enumerate(rows):

        if (idx == 0) or (row == []):
            # skip header row and blank rows
            continue

        elif (row[0].lower().strip() == 'approved') and (row[1] == ''):
            # process rows that are marked approved but not notified
            request_info = parse_function(row)
            notify_helpdesk(csr_type=csr_type,
                            priority='High',
                            queue='Monitoring',
                            **request_info)

            processed_rows.append(idx)
            if args.log:
                log_request(args.log, timestamp, request_info['user_email'])

        # if request is not approved and is more than `reminder_start`
        # hours old, send a reminder
        elif row[0] == '' and (now >=
                               dateparser.parse(row[3]) + reminder_start):
            # but only send if this is the first one, or if enough time
            # has passed since the last one
            if row[2]:
                last_sent = datetime.strptime(row[2], TIMESTAMP_FORMAT)
            else:
                last_sent = None

            if not last_sent or (now >= last_sent + reminder_interval):
                request_info = parse_function(row)
                reminder_list.append(request_info)
                reminder_rows.append(idx)
        else:
            # skip over unapproved rows <24 hours old, or already-notified rows
            continue

    # Skip sending empty requests to Google API because it is slow and returns
    # an error.  Try/catch would handle the error but not avoid the time cost.
    if processed_rows:
        timestamp_spreadsheet(sheet, timestamp, processed_rows, column=1)

    if reminder_list:
        send_reminder(request_type=request_type,
                      reminders=reminder_list,
                      worksheet_key=worksheet_key)
        timestamp_spreadsheet(sheet, timestamp, reminder_rows, column=2)
Beispiel #19
0
#! /usr/bin/env python3.6
from tkinter import Tk
from spreadsheet import Spreadsheet

root = Tk()
root.title("Spreadsheet Self-Test")
nRows = 4
nCols = 4
spreadsheet = Spreadsheet(root, nRows, nCols)
spreadsheet.grid(row=0, column=0, columnspan=nCols)
spreadsheet.focusLabel.grid(row=1, column=0)
spreadsheet.focusEntry.grid(row=1, column=1)
root.mainloop()
 def test_select_sheet(self):
     spreadsheet = Spreadsheet()
     self.assertNotEqual(spreadsheet.current_sheet().title, 'Stats')
     spreadsheet.select_sheet('Stats')
     self.assertEqual(spreadsheet.current_sheet().title, 'Stats')
Beispiel #21
0
""" Application to analyze an .xlsx file"""

import os
import sys
import openpyxl
from spreadsheet import Spreadsheet

workbook = Spreadsheet()
for sheet in workbook.sheets:
    for key, value in sheet.items():
        print("{}:\t{}".format(key, value))
Beispiel #22
0
         "Content-Type", "Authorization", "Access-Control-Allow-Credentials"
     ],
     supports_credentials=True)
api = Api(app)
CORS(app,
     origins="http://127.0.0.1:8080",
     allow_headers=[
         "Content-Type", "Authorization", "Access-Control-Allow-Credentials"
     ],
     supports_credentials=True)

spreadsheet_args = reqparse.RequestParser()
spreadsheet_args.add_argument("text", type=str, required=True)
spreadsheet_args.add_argument("url", type=str, required=True)

curr_spreadsheet = Spreadsheet()

model = MyClassifier(vectorizer='pretrained_glove_50',
                     spreadsheet=curr_spreadsheet,
                     debug=False)


class SpreadsheetManager(Resource):
    def post(self):
        args = spreadsheet_args.parse_args()
        url = args["url"]
        text = args["text"]

        # get sheet number
        parsed = urlparse.urlparse(url)
        gid = parse_qs(parsed.fragment)['gid'][0]
Beispiel #23
0
    exit(1)

sleep_Period = cfg['DHT']['Period']
site_For_Check = cfg['Main']['Site_for_check'].lower()
mail_Status = cfg['email']['Mail_status']
spreadsheet_Status = cfg['Spreadsheet']['Status']
clear_spreadsheet_on_start = cfg['Spreadsheet']['Clear spreadsheet on start']
send_by_str = cfg['Spreadsheet']['Send_by_str']
period_before_send = cfg['Main']['Period_before_send'].split(',')
period_before_archive = cfg['Main']['Period_before_arch'].split(',')

# Создаем экземляры классов
temp_logfile = File(Path, path_To_Temperature_Log, logger)
sensor = Sensor(logger, cfg.get('DHT'))
mail = Mail(temp_logfile, logger, cfg.get('email'))
spr_sheet = Spreadsheet(logger, Path, path_To_Temperature_Log,
                        cfg.get('Spreadsheet'))

# Если есть инет, пробуем законнектится
if is_Connected(site_For_Check) == True:
    # Инициализруем почту, если включена отправка почты
    if mail_Status is True:
        mail.login()
        is_Connected_To_Mail = True

    # Инициализруем гугл докс, если они включены в конфиге
    if spreadsheet_Status is True:
        # Логинимся и открываем таблицу
        spr_sheet.login()
        spr_sheet.open()

        # Если нужно, отчищаем гугл таблицу при старте
Beispiel #24
0
# Create the Reddit instance
reddit = praw.Reddit('bot1')

# and login
reddit = praw.Reddit(client_id='',
                     client_secret='',
                     user_agent='',
                     username='',
                     password='')

subreddit = reddit.subreddit('3dprintmything')

# Get the newest 6 values from the subreddit
for submission in subreddit.new(limit=6):
    #print(submission.title)
    spreadsheet = Spreadsheet(submission.id)
    seen_bool = spreadsheet.run()
    counter = 0
    # If we haven't seen this post before
    if not seen_bool:
        send_sms.send_alert()









Beispiel #25
0
 def load_spreadsheet(self,filepath=None,url=None):
     self.spreadsheet = Spreadsheet(filepath,url)
Beispiel #26
0
def cli_read(args):
    api = Spreadsheet(args.creds)
    cli = CLI(api, args.path)
    cli.read(args.reset)
Beispiel #27
0
# -*- coding: utf-8 -*-

from telebot import types
from telebot import TeleBot
from spreadsheet import Spreadsheet

import operator
import datetime
import sys
import os

sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'resources'))
from config import token

bot = TeleBot(token)
spreadsheet = Spreadsheet()
owner_id = ''
lean_coffee = {}
themes = set()
voting = False


@bot.message_handler(commands=['lean'])
def lean(message):
    global lean_coffee
    global themes
    global owner_id

    if not owner_id:
        lean_coffee = {}
        themes = set()
Beispiel #28
0
"""Tracker main program example.

Create your own main.py to use Scraper.
Your main.py will not be Git-tracked.

Сreates Google spreadsheet and fills it with the
specified repositories data at the specified intervals.
"""
import time
import config
from spreadsheet import Spreadsheet

# TODO: set the existing spreadsheet id, or
# None if new spreadsheet wanted to be created
spreadsheet_id = "1Z9QoQ8xUoOtHVUtrtLV6T78J30jvQS4uE0G4AK2Bhkc"
spreadsheet = Spreadsheet(config, spreadsheet_id)

# updating the spreadsheet at the specified period
while True:
    spreadsheet.reload_config(config)
    spreadsheet.update_structure()
    spreadsheet.update_all_sheets()

    time.sleep(config.UPDATE_PERIODICITY)
Beispiel #29
0
def handle_websocket():
    # assign a uuid to the client
    client_id = str(uuid.uuid4())
    print client_id, 'websocket connected'
    # request the websocket
    ws = request.environ.get('wsgi.websocket')
    if not ws:
        abort(400, 'Expected WebSocket request.')
    clients[client_id] = ws
    state = None
    while True:
        try:
            raw_msg = ws.receive()
        except:
            break
        msg = safely(lambda: json.loads(raw_msg))
        if not msg:
            time.sleep(0.1)
            continue
        print 'msg:', msg
        command = msg.get('command')
        # {command: "search", keywords: "hello world"}
        if command == 'search':
            keywords = msg['keywords'].split()
            items = pages.search(keywords)
            ws.send(json.dumps({'command': 'search-results', 'items': items}))
        # {command: "open", id: "r18r4g18734tr1087t"}
        elif command == 'open':
            id = msg['id']
            locker(
                lambda: id in sheets or sheets.update({id: Spreadsheet(id)}))
            page = pages.retrieve(id) or {
                'id': id,
                'title': 'new page',
                'markup': '',
                'code': ''
            }
            ws.send(json.dumps({'command': 'page', 'page': page}))
        # {command: "compute", id: "..." code: "...", formulas: {..}}
        elif command == 'compute':
            id = msg['id']
            if not id in sheets: continue
            sheet = sheets[id]
            if 'code' in msg:
                context = {}
                try:
                    exec(msg['code'], {}, context)  # NOT SAFE CHECK THIS HERE
                    sheets[id].context = context
                except:
                    pass
            changes = msg['formulas']
            if changes == None: return
            for key in changes.keys():
                if not changes[key] == '=':
                    safely(lambda: changes.update(
                        {key: ast.literal_eval(changes[key])}))
            changes = locker(lambda: sheets[id].process(changes))
            values = {
                key: render(value)
                for key, value in changes['values'].iteritems()
            }
            ws.send(json.dumps({'command': 'values', 'values': values}))
        # {command: "save", page: {id:..., title:..., markup:..., code:...} }
        elif command == 'save':
            pages.store(**msg['page'])
Beispiel #30
0
from spreadsheet import Spreadsheet
from visualize import *

sheet = Spreadsheet('1cH4OGCXdfq_3CNAec6hWsXUtXJ9-4PPBUBEbMPg5XRc')
# test_tags = {"Action": "make", "Graph": "line graph", "Range": "range from A1 to D4"}


def process(tags):
    if "Action" not in tags:
        print("ERROR: Action is not in tags")

    # TODO: think of better ways to store data since this is a singleton
    action_type = tags["Action"][0]
    if action_type == "make":
        graph = get_graph(tags)
        data = get_data(tags)
        kwargs = {"color": "red"}  # TODO: come back to this
        graph(data, kwargs=kwargs)
    elif tags["Action"] == "change":
        pass


def get_graph(tags):
    if "Graph" not in tags:
        print("ERROR: Graph is not in tags")

    # TODO: think of better ways to store data since this is a singleton
    graph_type = tags["Graph"][0]
    if graph_type == "line graph":
        return line_plot