Beispiel #1
0
def create_database():
    if not os.path.exists('./database.db'):
        print("Create a database\n")
        database.create_all()
        sleep(0.1)

    file_name = "products_79936.json"
    if not os.path.exists(file_name):
        # Download of mock database
        Process.run(
            'curl https://servicespub.prod.api.aws.grupokabum.com.br/descricao/v1/descricao/produto/79936 >> %s'
            % file_name)

    ## Save database ##
    # Read $filename
    config_file = './%s' % file_name
    config_helper = ConfigHelper(config_file)
    config = config_helper.load_config()

    # Read only products of config
    config = config['familia']['produtos']
    for data in config:
        product = ProductModel(**data)
        try:
            # Save products in database
            product.save_product()
            sleep(0.01)
        except:
            print({"message": "An error ocurred trying to create product."},
                  500)  # Internal Server Error
def use_macro(macro: dict, amt: int, flags: list):
    """Uses the selected macro on a set amt of cycles.
    macro returns None if there is no macro read.
    macro format: check parse_macro() docstring.
    Args:
        macro: Comes from read_macro()
    """
    options = {"-collect": False}
    for f in flags:
        if options.get(f, "") != "":
            options[f] = True
    if not macro:
        print("ERROR: Macro name does not exist your profiles")
        quit()
    print(f"Starting {amt} crafts:")
    proc = Process()
    select = "{VK_NUMPAD0}"
    for i in range(amt):
        print(f" > Craft #{i}")
        for i in range(4):
            proc.press_key(select)
        sleep(0.5)
        for step in macro:
            wait = macro[step]["wait"]
            key = macro[step]["key"]
            print(f"   > Pressing {key}")
            proc.press_key(key)
            print(f"   > Waiting {wait}s")
            sleep(wait)
        if options["-collect"] == True:
            print(f"   > Collectable Menu")
            for i in range(4):
                proc.press_key(select)
            sleep(2.5)
    print("Crafts finished.")
 def fill_randomly(self, n, min_execution_time, max_execution_time,
                   max_time_of_arrival):
     for i in range(n):
         self.items.append(
             Process.create_random(f"{i:0{len(str(n))}}",
                                   min_execution_time=min_execution_time,
                                   max_execution_time=max_execution_time,
                                   max_time_of_arrival=max_time_of_arrival))
Beispiel #4
0
class StockView(object):
    conn = Process("config.yml")
    conn.pull_data()

    @cherrypy.expose
    def index(self, name=None):
        if name is not None:
            name = str(name).strip().lower()
        stocks = self.conn.get_data(name=name)
        return render_template('index', stocks=stocks)
 def test_connection_can_hold_more_than_one_msg(self):
     parent_conn, child_conn = Pipe()
     p = Process(target=worker_func, args=(child_conn, ))
     p.start()
     # time.sleep(2)
     self.assertEqual(parent_conn.recv(), 'test1')
     self.assertEqual(parent_conn.recv(), 'test2')
     p.join()
Beispiel #6
0
def use_macro(args):
    """Uses the selected macro on a set amt of cycles.
    Args:
        macro: Comes from read_macro()
        flags: List of options like repairing, and collectables
    """
    inputs = input_handler.craft(args)  #inputs has macro amt opt
    macro = inputs["macro"]
    options = {"-repair": False, "-food": False, "-pot": False}
    for f in inputs["opt"]:
        if options.get(f, "") != "":
            options[f] = True
    print(f"Starting {inputs['amt']} crafts:")
    proc = Process()
    select = "{VK_NUMPAD0}"
    steps = len(macro["macro"]["keys"])
    repair_counter = 0
    # Can adjust sleeps according to lag
    sleeps = {"step1": 0.5, "step2": 1, "input": 2.5}
    est = h.get_time_estimation(macro, inputs["amt"], sleeps)
    print(f" > Time estimation: {est:.2f} minutes.")
    for i in range(inputs["amt"]):
        print(f" > Craft #{i + 1}")
        for _ in range(4):
            proc.press_key(select)
        sleep(1)
        for step in range(steps):
            wait = macro["macro"]["wait"][step]
            key = macro["macro"]["keys"][step]
            print(f"   > Pressing {key}")
            sleep(sleeps["step1"])
            proc.press_key(key)
            print(f"   > Waiting {wait}s")
            sleep(wait)
            sleep(sleeps["step2"])
        if repair_counter > s.REPAIR_COUNTER:
            if options["-repair"] == True:
                print("Self repairing...")
                opt_repair(proc)
            repair_counter = 0
        repair_counter += 1
        sleep(sleeps["input"])
    print("Crafts finished.")
    notify.finished()
Beispiel #7
0
                os.makedirs(dl_path)
            except Exception as e:
                pass
            num_files = int(config[site]['number_of_files'])
            progress_file = config[site]['progress_file'].lower()
            threads = int(config[site]['threads'])
            log_file = os.path.join(dl_path, site + '.log')
            logger = setup_custom_logger('root', log_file)
            try:
                search = config[site]['search'].split(',')
            except KeyError as e:
                search = []
            if search:
                for term in search:
                    site_term = site + ":" + term
                    scrape[site_term] = Process(site_class, dl_path,
                                                progress_file, term, num_files,
                                                threads)
            else:
                scrape[site] = Process(site_class, dl_path, progress_file, '',
                                       num_files, threads)

    # Start site parser
    try:
        for site in scrape:
            print("#### Scrapeing: " + site)
            scrape[site].start()
    except Exception as e:
        print("Exception [main]: " + str(e))
        stop()
Beispiel #8
0
kubeconfig_path = ["kubeconfig_path"] if args["kubeconfig_path"] else (
    config.get_env("KUBECONFIG") if config.get_env("KUBECONFIG") else None)
helm_release_filter_days = int(
    ["helm_release_filter_days"] if args["helm_release_filter_days"] else (
        config.get_env("HELM_RELEASE_FILTER_DAYS") if config.
        get_env("HELM_RELEASE_FILTER_DAYS") else None))

log_path = args["logpath"] if args["logpath"] else (
    config.get_env("LOG_PATH") if config.get_env("LOG_PATH") else None)
log_file = args["logfile"] if args["logfile"] else (
    config.get_env("LOG_FILE") if config.get_env("LOG_FILE") else None)

log = Log(log_path, log_file, config.get_env("LOG_LEVEL"),
          config.get_env("LOGGER")).logger

date, process, helm, exception = Date(log), Process(log), Helm(
    log), ExceptionDefault()

# =============================================================================
# FUNCTIONS
# =============================================================================


def run_execution(command: Text) -> NoReturn:

    today = date.date_today()

    try:
        output, errors = process.run_command(command)

        if errors:
Beispiel #9
0
from utils.constants import DATA, VALUE_P, TEST
from utils.process import Process
from threading import Thread

from flask import Flask, Response, request, render_template
from flask_cors import CORS
import json

app = Flask(__name__)
CORS(app)

Proc = Process()


@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')


@app.route('/maximin', methods=['POST'])
def maximin():
    req_data = request.get_json()
    Proc.set_table(req_data['data'])
    return Response(json.dumps(Proc.get_results_maximin()),
                    status=200,
                    mimetype='application/json')


@app.route('/maximax', methods=['POST'])
def maximax():
    req_data = request.get_json()
Beispiel #10
0
import torch
import json
from collections import OrderedDict
import numpy as np
import jieba
from utils.Dict import Dict
from utils.AoAKW import AoAKW
from utils.process import Process, KWSample
from flask import Flask, request
from gevent.wsgi import WSGIServer

app = Flask(__name__)

word2idx = Dict(json.load(open('docs/word2idx.json', 'r')))
cate2idx = Dict(json.load(open('docs/cate2idx.json', 'r')))
process = Process(word2idx, cate2idx)


def initModel():

    state = torch.load("model/05-29-15:05:06_checkpoint.pth.tar")

    model = AoAKW(word2idx,
                  dropout_rate=0.3,
                  embed_dim=50,
                  hidden_dim=50,
                  n_class=92)
    model.load_state_dict(state["state_dict"])
    print("init model sucessfully.")
    return model
Beispiel #11
0
def auto_leve(*args, **kwargs):
    """
    check dimension settings
    run capture2text, get output
    parse output
        - keep track of placement to compare with last step
    move arrows correctly
    """
    amt = input_handler.leve()
    print(f"Starting {amt} auto leves...")
    for a in range(amt):
        proc = Process()
        proc.press_to_leve_menu_seq()
        idx = ocr.get_quest_index()
        print(f"found cookie quest index @ {idx}")
        proc.press_leve_menu_seq(idx)
        proc.press_tfocus_macro()
        proc.press_leve_quest_seq()
        proc.press_tnpc_macro()
Beispiel #12
0

if __name__ == "__main__":
    # Read config file
    if not os.path.isfile(args.config):
        print("Invalid config file")
        sys.exit(0)
    config.read(args.config)

    # Parse config file
    scrape = {}
    for site in config.sections():
        if config[site]['enabled'].lower() == 'true':
            try:  # If it not a class skip it
                site_class = getattr(sys.modules[__name__], site.lower())
            except AttributeError as e:
                print("\nThere is no module named " + site + "\n")
                continue
            dl_path = os.path.expanduser(config[site]['download_path'])
            num_files = int(config[site]['number_of_files'])
            threads = int(config[site]['threads'])
            scrape[site] = Process(site_class, dl_path, num_files, threads)

    # Start site parser
    try:
        for site in scrape:
            print("#### Scrapeing: " + site)
            scrape[site].start()
    except Exception as e:
        print("Exception [main]: " + str(e))
        stop()