def main():
    base_url = 'https://app.testudo.umd.edu/soc/'
    html = urlopen(base_url)
    bs = BeautifulSoup(html.read(), 'html.parser')

    left_list = bs.find('div', {
        'id': 'left-course-prefix-column'
    }).findAll('div', {'class': 'course-prefix row'})
    right_list = bs.find('div', {
        'id': 'right-course-prefix-column'
    }).findAll('div', {'class': 'course-prefix row'})
    complete_list = left_list + right_list

    try:
        for i in complete_list:
            department_url = i.find('a').attrs['href']
            department_html = urlopen(base_url + department_url)
            bs = BeautifulSoup(department_html.read(), 'html.parser')
            course_list = bs.findAll('div', {'class': 'course'})
            for j in course_list:
                course_name = j.attrs['id']
                course_sec_num = 0
                individual_instruction = j.find(
                    'div', {'class': 'individual-instruction-message'})
                if (individual_instruction is None):
                    course_url = base_url + department_url + '/' + course_name
                    course_sec_num = findSecNum(course_url)
                    is_update = verify_sec_num(course_name, course_sec_num)
                    if (is_update):
                        processSendMail(course_name)
                        update(course_name, course_sec_num)
    except AttributeError as e:
        main()
Ejemplo n.º 2
0
def launch():
    global launched
    launched = False
    if launched == config.islaunched:
        generate_key()
        global user_name, password, user, pw_db, dbname
        print("---------------------------------------------------------")
        print('Please Enter the masterUsername: '******'--> ')
        print("---------------------------------------------------------")
        password = encrypt_pw(input('Enter your password: \n--> '))
        print("---------------------------------------------------------")
        print('Enter the name of the user of your data base: ')
        user = input('--> ')
        print("---------------------------------------------------------")
        print('The password of the data base: ')
        pw_db = input('--> ')
        print("---------------------------------------------------------")
        print('Finally, the name of the data base: ')
        dbname = input('--> ')
        print("---------------------------------------------------------")
        launched = True
        args = [
            "islaunched", "user_name", "password", "dbuser", "dbname", "dbpw"
        ]
        credentials = [launched, user_name, password, user, dbname, pw_db]
        update(args, credentials)
    else:
        user_name = config.user_name
        password = config.password
        user = config.dbuser
        pw_db = config.dbpw
        dbname = config.dbname
    return launched, user_name, password, user, pw_db, dbname
Ejemplo n.º 3
0
def update_post():
    """Updates TinyPilot to the latest version available.

    This is a slow endpoint, as it is expected to take 2~4 minutes to
    complete.

    Returns:
        A JSON string with two keys: success and error.

        success: true if successful.
        error: null if successful, str otherwise.

        Example of success:
        {
            'success': true,
            'error': null,
        }
        Example of error:
        {
            'success': false,
            'error': 'sudo: /opt/tinypilot-privileged/update: command not found'
        }
    """
    try:
        update.update()
    except update.Error as e:
        return _json_error(str(e)), 200
    return _json_success()
Ejemplo n.º 4
0
def main():
    print "- Starting ZeroNet..."

    main = None
    try:
        app_dir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(app_dir)  # Change working dir to zeronet.py dir
        sys.path.insert(0, os.path.join(app_dir, "src/lib"))  # External liblary directory
        sys.path.insert(0, os.path.join(app_dir, "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import gc
            import update
            import atexit
            # Try cleanup openssl
            try:
                if "lib.opensslVerify" in sys.modules:
                    sys.modules["lib.opensslVerify"].opensslVerify.closeLibrary()
            except Exception, err:
                print "Error closing opensslVerify lib", err
            try:
                if "lib.pyelliptic" in sys.modules:
                    sys.modules["lib.pyelliptic"].openssl.closeLibrary()
            except Exception, err:
                print "Error closing pyelliptic lib", err

            # Close lock file
            sys.modules["main"].lock.close()

            # Update
            try:
                update.update()
            except Exception, err:
                print "Update error: %s" % err
Ejemplo n.º 5
0
def main():
    print " - Starting ZeroNet..."
    import sys, os
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__),
                                        "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import update, sys, os, gc
            # Update
            update.update()

            # Close log files
            logger = sys.modules["main"].logging.getLogger()

            for handler in logger.handlers[:]:
                handler.flush()
                handler.close()
                logger.removeHandler(handler)

    except Exception, err:  # Prevent closing
        import traceback
        traceback.print_exc()
        raw_input("-- Error happened, press enter to close --")
Ejemplo n.º 6
0
def main():
	print "- Starting ZeroNet..."
	import sys, os
	main = None
	try:
		sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) # Imports relative to src
		import main
		main.start()
		if main.update_after_shutdown: # Updater
			import update, sys, os, gc
			# Try cleanup openssl
			try:
				if "lib.opensslVerify" in sys.modules:
					sys.modules["lib.opensslVerify"].opensslVerify.close()
			except Exception, err:
				print "Error closing openssl", err

			# Update
			update.update()

			# Close log files
			logger = sys.modules["main"].logging.getLogger()

			for handler in logger.handlers[:]:
				handler.flush()
				handler.close()
				logger.removeHandler(handler)

	except Exception, err: # Prevent closing
		import traceback
		traceback.print_exc()
		traceback.print_exc(file=open("log/error.log", "a"))
def main():

	pygame.init()
	globals.pygame = pygame # assign global pygame for other modules to reference
	globals.inputs = Inputs(pygame) # assign global inputs for other modules to reference
	update_display_mode() # now that the global display properties have been set up, update the display
	clock = pygame.time.Clock() # clock to tick / manage delta

	entities = [] # contains every object that will be drawn in the game

	entities.append(Entity()) # our testing entity will be the default entity

	loop = True # for controlling the game loop

	while(loop):
		clock.tick(60) # tick the clock with a target 60 fps
		globals.window.fill((255, 255, 255))

		globals.inputs.update() # refresh inputs

		update(entities) # update all entities
		render(entities) # draw all entities

		if(globals.inputs.isKeyDown("space")): toggle_fullscreen() # space bar toggles fullscreen
		if(globals.inputs.isKeyDown("escape")): loop = False # escape key exits game
		if(globals.inputs.isQuitPressed()): loop = False # red 'x' button exits game

		pygame.display.flip() # flip the display, which finally shows our render

	pygame.quit() # unload pygame modules
Ejemplo n.º 8
0
def main():
    print "- Starting ZeroNet..."

    main = None
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src/lib"))  # External liblary directory
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import gc
            import update
            # Try cleanup openssl
            try:
                if "lib.opensslVerify" in sys.modules:
                    sys.modules["lib.opensslVerify"].opensslVerify.closeLibrary()
            except Exception, err:
                print "Error closing opensslVerify lib", err
            try:
                if "lib.pyelliptic" in sys.modules:
                    sys.modules["lib.pyelliptic"].openssl.closeLibrary()
            except Exception, err:
                print "Error closing pyelliptic lib", err

            # Update
            update.update()

            # Close log files
            logger = sys.modules["main"].logging.getLogger()

            for handler in logger.handlers[:]:
                handler.flush()
                handler.close()
                logger.removeHandler(handler)
def do_config(action,data):
    #=========================================================================#
    if action=="reboot":
        for name in sub_routines:
            sub_routines[name].stop()
            sub_routines[name].start()
        #TODO: do anything else
    #=========================================================================#
    elif action=="update":
        update.update()
    #=========================================================================#
    elif action=="script":
        if "script" in data:
            script=data["script"]
            with open("temp_script","w") as tsf:
                tsf.write(script)
                tsf.close()
                subprocess.call(["chmod","+x","temp_script"])
                subprocess.call(["temp_script"])
        else:
            pass
    #=========================================================================#
    elif action=="calibrate":
        if "Sender" in sub_routines:
            mult=data.get("mult_by",1.0)
            add=data.get("add_by",0.0)
            sub_routines["Sender"].getInterface().Calibrate(mult,add)
    #=========================================================================#
    else:
        pass
def main():
    canvas.pack()

    text = canvas.create_text(
        screen_width / 2,
        indent_y - 10,
        text="Use WASD to accelerate the white ball, to quit use Q")

    border = canvas.create_rectangle(field_x,
                                     field_y,
                                     field_x + field_width,
                                     field_y + field_height,
                                     fill=border_color,
                                     outline="")

    field = canvas.create_rectangle(field_x + border_width,
                                    field_y + border_width,
                                    field_x + field_width - border_width,
                                    field_y + field_height - border_width,
                                    fill=field_color,
                                    outline="")

    root.bind("<Key>", key)

    make_holes()
    update(last_time, start_balls(), root)
    root.mainloop()
Ejemplo n.º 11
0
def main():
	print "- Starting ZeroNet..."
	import sys, os
	main = None
	try:
		sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) # Imports relative to src
		import main
		main.start()
		if main.update_after_shutdown: # Updater
			import update, sys, os, gc
			# Update
			update.update()

			# Close log files
			logger = sys.modules["main"].logging.getLogger()

			for handler in logger.handlers[:]:
				handler.flush()
				handler.close()
				logger.removeHandler(handler)

	except Exception, err: # Prevent closing
		import traceback
		traceback.print_exc()
		raw_input("-- Error happened, press enter to close --")
Ejemplo n.º 12
0
def main():
    print "- Starting ZeroNet..."

    main = None
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__),
                                        "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import gc
            import update
            # Try cleanup openssl
            try:
                if "lib.opensslVerify" in sys.modules:
                    sys.modules[
                        "lib.opensslVerify"].opensslVerify.closeLibrary()
            except Exception, err:
                print "Error closing opensslVerify lib", err
            try:
                if "lib.pyelliptic" in sys.modules:
                    sys.modules["lib.pyelliptic"].openssl.closeLibrary()
            except Exception, err:
                print "Error closing pyelliptic lib", err

            # Update
            update.update()

            # Close log files
            logger = sys.modules["main"].logging.getLogger()

            for handler in logger.handlers[:]:
                handler.flush()
                handler.close()
                logger.removeHandler(handler)
Ejemplo n.º 13
0
async def reload(ctx):
    update.update()

    global mDict, sList
    mDict = load.memes() #load dictionary of memes
    sList = load.stops() #load list of stops

    await ctx.send(":white_check_mark: **Files Reloaded**")
Ejemplo n.º 14
0
def handle_message(event):
    message_type = event.message.type
    user_id = event.source.user_id
    reply_token = event.reply_token

    logger.info('message_type: ' + str(message_type))
    logger.info('user_id: ' + str(user_id))

    if (message_type == 'location'):
        update()
        result = get_mask(event)
        Card = json.load(
            open(data_folder + 'json/Card.json', 'r', encoding='utf-8'))
        for i in range(len(result)):
            bubble = json.load(
                open(data_folder + 'json/Bubble.json', 'r', encoding='utf-8'))
            # 醫事機構代碼
            Code = result[i][0]
            # 藥局名稱
            Name = result[i][1]
            # 地址
            Address = result[i][2]
            # 電話
            Phone = result[i][3]
            # 成人口罩剩餘
            AdultRemain = result[i][4]
            # 兒童口罩剩餘
            KidRemain = result[i][5]
            # 最後更新時間
            LastUpdate = result[i][6]
            # 緯度
            Latitude = result[i][7]
            # 經度
            Longitude = result[i][8]

            # 標題
            bubble['body']['contents'][0]['text'] = Name
            # 電話
            bubble['body']['contents'][1]['contents'][1]['text'] = Phone
            # 地址
            bubble['body']['contents'][2]['contents'][1]['text'] = Address
            # 成人口罩剩餘
            bubble['body']['contents'][3]['contents'][1]['text'] = AdultRemain
            # 兒童口罩剩餘
            bubble['body']['contents'][4]['contents'][1]['text'] = KidRemain
            # 最後更新時間
            bubble['body']['contents'][5]['contents'][1]['text'] = LastUpdate[
                5:-3]
            # PostBack Action
            bubble['footer']['contents'][0]['action'][
                'data'] = 'GetMap {}'.format(Code)
            Card['contents'].append(bubble)
        line_bot_api.reply_message(reply_token,
                                   FlexSendMessage('查詢結果出爐~', Card))
    elif (message_type == 'text'):
        user_text = event.message.text
        logger.info('user_text: ' + user_text)
        line_bot_api.reply_message(reply_token, TextSendMessage(text='早安^^'))
Ejemplo n.º 15
0
def get_name(request):
    form=NameForm()
    form1=UpdateForm()
    s8 = prediction_content.get_prediction_content()
    json_pre = json.dumps(s8)

    # if this is a POST request we need to process the form data
    if request.method == 'POST' and 'search' in request.POST:
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            #start of search processing time
            start_time=time.time()
            your_name = request.POST.get('your_name')
            your_name1=your_name
            s=search1.get_search_result(your_name1)
            s1=search1.get_file_name()
            s3=[]
            s4=search1.pre()
            s5=search1.get_knownerror()
            for i in s1:
                if i not in s3:
                    s3.append(i)
            s2=zip(s,s1,s4,s5)
            c=len(s)
            tim=time.time()-start_time
            tim=str(tim)+" sec"
            #end of search process time
            form=NameForm()

            return render(request,'myapp/thanks.html',{'name':your_name1,'file':s3,'filename':s2,'number':c,'result':s,'form':form,'form1':form1,'soln':s,'ti':tim,'json_pre':json_pre})

    if request.method == 'POST' and 'update' in request.POST:
        form1 = UpdateForm(request.POST)
        if form1.is_valid():
            question = request.POST.get('question')
            answer = request.POST.get('comment')
            pre = request.POST.get('pre')
            file_choice=request.POST.get('file_choice')
            print answer

            print question
            print file_choice
            form1 = UpdateForm()
            update.update(question,answer,pre,file_choice)

            return render(request, 'myapp/thanks.html',
                          {'form':form,'form1':form1,'json_pre':json_pre})
    else:
            form = NameForm()
            form1=UpdateForm()


    #template = loader.get_template("myapp/name.html")
    context = {'form': form,'form1':form1,'json_pre':json_pre}
    #return HttpResponse(template.render(context, request))
    return render(request, "myapp/name.html", context)
Ejemplo n.º 16
0
def main():
    if sys.version_info.major < 3:
        print("Error: Python 3.x is required")
        sys.exit(0)

    if "--silent" not in sys.argv:
        print("- Starting ZeroNet...")

    main = None
    try:
        app_dir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(app_dir)  # Change working dir to zeronet.py dir
        sys.path.insert(0,
                        os.path.join(app_dir,
                                     "src/lib"))  # External liblary directory
        sys.path.insert(0, os.path.join(app_dir,
                                        "src"))  # Imports relative to src
        import main
        main.start()
    except Exception as err:  # Prevent closing
        import traceback
        try:
            import logging
            logging.exception("Unhandled exception: %s" % err)
        except Exception as log_err:
            print("Failed to log error:", log_err)
            traceback.print_exc()
        from Config import config
        error_log_path = config.log_dir + "/error.log"
        traceback.print_exc(file=open(error_log_path, "w"))
        print("---")
        print(
            "Please report it: https://github.com/HelloZeroNet/ZeroNet/issues/new?assignees=&labels=&template=bug-report.md"
        )
        if sys.platform.startswith(
                "win") and "python.exe" not in sys.executable:
            displayErrorMessage(err, error_log_path)

    if main and (main.update_after_shutdown
                 or main.restart_after_shutdown):  # Updater
        if main.update_after_shutdown:
            print("Shutting down...")
            prepareShutdown()
            import update
            print("Updating...")
            update.update()
            if main.restart_after_shutdown:
                print("Restarting...")
                restart()
        else:
            print("Shutting down...")
            prepareShutdown()
            print("Restarting...")
            restart()
Ejemplo n.º 17
0
def start():
    app_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(app_dir)  # Change working dir to zeronet.py dir
    sys.path.insert(0, os.path.join(app_dir, "src/lib"))  # External liblary directory
    sys.path.insert(0, os.path.join(app_dir, "src"))  # Imports relative to src

    if "--update" in sys.argv:
        sys.argv.remove("--update")
        print("Updating...")
        import update
        update.update()
    else:
        main()
Ejemplo n.º 18
0
def prepare():
    prepareUserAreas()

    from makerfuncs import config, download as d
    import update as u

    default = {
        'img': 'maps',
        'pbf': 'pbf',
        'polygons': 'polygons',
        'hgt': 'hgt',
        'temp': 'temp',
        'sea': 'sea',
        'bounds': 'bounds',
    }

    data = {}

    #TODO kontroly validity vstupu
    data['img'] = input(
        'The name of the output folder with garmin maps (default maps): ')
    data['pbf'] = input(
        'The name of the folder for map data download (default pbf): ')
    data['polygons'] = input(
        'The name of the folder for polygons (default polygons): ')
    data['hgt'] = input(
        'The name of the folder for height data (default hgt): ')
    data['temp'] = input(
        'The name of the folder for temporary data (default temp): ')
    data['sea'] = input('The name of the folder for sea data (default sea): ')
    data['bounds'] = input(
        'The name of the folder for bounds data (default bounds): ')

    for item in data:
        if data[item] == '':
            data[item] = default[item]
        if data[item][-1] != '/':
            data[item] = data[item] + '/'

        try:
            os.mkdir(data[item])
        except:
            print("Directory " + data[item] + " already exists")
            pass

    data['splitter'] = 0
    data['mkgmap'] = 0

    config.save(data)

    u.update()
Ejemplo n.º 19
0
 def menu(self):
     while self.dato:
         selection = input(
             '\nSelect 1 to insert, 2 to update, 3 to read, 4 to delete \n')
         if selection == '1':
             insert.insert()
         elif selection == '2':
             update.update()
         elif selection == '3':
             read.read()
         elif selection == '4':
             delete.delete()
         else:
             print('\n Invalid selection \n')
Ejemplo n.º 20
0
def processing(client):
    cv, rows = get_cv_rows(client, URLS['WHAT_TO_WATCH'])
    _, rows_yt = get_cv_rows(client, URLS['YOUTUBE_LIST'])
    _, rows_td = get_cv_rows(client, URLS['TODY_KILLER'])
    _, rows_pr = get_cv_rows(client, URLS['PRIVATE'])
    cv_w, rows_w = get_cv_rows(client, URLS['WEATHER'])
    cv_h, rows_h = get_cv_rows(client, URLS['WORK_HOURS'])
    last_date = get_last_date(rows)
    update(cv, rows, MangaRSS(last_date), False)
    update(cv, rows, SportsRSS(URLS['BLOG_RSS'], last_date), False)
    try:
        update(cv, rows, SeriesRSS(last_date), False)
    except Exception:
        pass
    for url in get_youtube_urls(rows_yt):
        update(cv, rows, YouTubeRSS(url, last_date), True)
    update_last_date(rows)
    # update_tody(rows_td)
    # update_private(rows_pr)
    # update_weather(cv_w, rows_w, key_num=2)
    update_work_hours(cv_h, rows_h)

    for source in ['google', 'outlook']:
        cv, rows = get_cv_rows(client, URLS['CALENDAR'])
        add_events(cv, rows, os.environ[f'{source}_ics'])
    if gethostname() == 'LAPTOP-6MEALABP':
        cv_h, rows_h = get_cv_rows(client, URLS['WORK_HOURS'])
        plot_work_hours(rows_h)
Ejemplo n.º 21
0
    def menu(self):

        while self.dato:
            selecction = input("\n Selecciona una de las opciones del menu \n 1.- Insertar \n 2.- Leer \n 3.-Actualizar \n 4.-Borrar \n\n")
            if selecction=='1':
                insert.insert()
            elif selecction=='2':
                read.read()
            elif selecction=='3':
                update.update()
            elif selecction=='4':
                delete.delete()
            else:
                print("Instruccion invalida")
Ejemplo n.º 22
0
async def redeem(ctx, arg1):
    valid = False
    await ctx.message.delete()
    update.update()
    with open(config['SerialFile']) as license_file:
        lines = license_file.read().splitlines()
        if arg1 in lines:
            embed2 = discord.Embed(title=config['ValidTitle'], color=0x00ff00)
            embed2.add_field(name=config['ValidName'],
                             value=config['ValidValue'],
                             inline=False)
            embed2.set_author(name=ctx.author.name,
                              icon_url=ctx.author.avatar_url)
            embed2.set_footer(text=config['ValidFooter'])
            mess = await ctx.send(embed=embed2)
            role = discord.utils.get(ctx.guild.roles, name=config['RoleName'])
            user = ctx.message.author
            await user.add_roles(role)
            print('Valid orderid: ', str(user), arg1)
            valid = True
        elif arg1 + "used" in lines:
            embed2 = discord.Embed(title=config['UsedTitle'], color=0xFF0000)
            embed2.set_author(name=ctx.author.name,
                              icon_url=ctx.author.avatar_url)
            embed2.set_footer(text=config['UsedFooter'])
            mess = await ctx.send(embed=embed2)
            print('Used OrderID: ', str(ctx.message.author), arg1)
        else:
            embed2 = discord.Embed(title=config['InvalidTitle'],
                                   color=0xFF0000)
            embed2.set_author(name=ctx.author.name,
                              icon_url=ctx.author.avatar_url)
            embed2.set_footer(text=config['InvalidFooter'])
            mess = await ctx.send(embed=embed2)
            print('Invalid orderid: ', str(ctx.message.author), arg1)
        if valid:
            with open(config['SerialFile'], "r+") as f:
                file_content = f.readlines()
                f.seek(0)
                for line in file_content:
                    if arg1 + "used" in line:
                        f.write(line)
                    elif arg1 in line and arg1 + "used" not in line:
                        f.write(line.strip() + "used\n")
                    else:
                        f.write(line)
                f.truncate()
        await asyncio.sleep(2)
        await mess.delete()
Ejemplo n.º 23
0
def main():
    parser = argparse.ArgumentParser(description='Collect information about the number of job offers in IT industry from main Polish portals.')
    parser.add_argument('-u', '--update', help='update database', action="store_true")
    parser.add_argument('-d', '--display', help='display current database', action="store_true")
    args = parser.parse_args()

    threads = list()
    print("Welcome to iTrendsPL!")

    if vars(args)['update']:
        for language in scrap.languages:
            update.update(language)
    elif vars(args)['display'] == True:
        update.open()
        time.sleep(1)
Ejemplo n.º 24
0
def calibrate(working_directory,
              start_iter=1,
              sample_rate=None,
              max_iters=3,
              input_path='.',
              output_path='../Model Calibration'):
    """Calibrate abm with given parameters.

    Parameters
    ----------
    working_directory : str
        The path to the directory containing the gisdk and uec directories.
    start_iter : int, default : 1
        The iteration to start the process from.
    sample_rate : float or str, default : None
        The sample rate for the given starting iteration, or a string
        representing all of the sample rates.
    max_iters : int, default : 3
        The maximum number of iterations to run for each step.
    input_path : str, default : '.'
        The relative path to the output and uec directories.
    output_path : str, default : '../Model Calibration'
        The relative path to the directory containing the calibration
        directories.

    """
    steps = ['AO', 'CDAP']
    for step in steps:
        cal_path = output_path + '/{}'.format(FILES[step][2])
        update(0, input_path, cal_path, method=step)
        for iter_ in range(max_iters):
            proc = launch_transcad()
            setup_abm(working_directory,
                      start_iter=start_iter,
                      sample_rate=sample_rate)
            launch_abm(working_directory)
            start_time = time()
            sleep(18000)
            result_file = input_path + '/output/' + FILES[step][1]\
                .format(start_iter)
            last_mod = osp.getmtime(result_file)
            while last_mod < start_time:
                sleep(1800)
                last_mod = osp.getmtime(result_file)
            kill_proc_tree(proc.pid, including_parent=True)
            update(iter_ + 1, input_path, cal_path, method=step)
            print('Completed Step {} iteration {}.\n'.format(
                FILES[step][0], iter_ + 1))
Ejemplo n.º 25
0
def sudoku(A):
    # =====================================================================
    # A: 9x9 np.array int, stores the real sudoku matrix
    # B: 9x9 np.array int, corresponds to A
    #	 undecided position: stores number of options
    #    filled position: stores 10
    # C: 9x9 2d list set of int's
    #    undecided position: stores a set of  all options for each position
    #    filled position: 0
    # =====================================================================
    B = np.zeros((9,9), dtype=int)
    C = [[0 for x in xrange(9)] for x in xrange(9)]
    
    #pivot_stack:
    #   A stack storing all pivot points that facilitate back-tracing algorithm
    pivot_stack = []
    StackElem = namedtuple('StackElem', 'ind choice A')
   
    A_old = A.copy()
    conflict = update(A,B,C)
#    update_counter = 1
#    print "="*30
#    print "Update %d" %update_counter
#    update_counter = update_counter + 1

    #sudoku_print(A)

#    color_print(A_old, A)
    #sudoku_print(A)
    while(A.min() == 0):
        if(not conflict):
            i,j = get_leastopt_ind(B)
            elem = StackElem((i,j), list(C[i][j]), A.copy())
            pivot_stack.append(elem)
        else:
            if(len(pivot_stack[-1].choice) > 1):
                del pivot_stack[-1].choice[0]
            else:
                while(len(pivot_stack[-1].choice) == 1):
                    del pivot_stack[-1]
                del pivot_stack[-1].choice[0]
            np.copyto(A, pivot_stack[-1].A)

        i,j = pivot_stack[-1].ind
        np.copyto(A_old, A)

        A[i,j] = pivot_stack[-1].choice[0]
        conflict = update(A,B,C)
Ejemplo n.º 26
0
def sudoku(A):
    # =====================================================================
    # A: 9x9 np.array int, stores the real sudoku matrix
    # B: 9x9 np.array int, corresponds to A
    #	 undecided position: stores number of options
    #    filled position: stores 10
    # C: 9x9 2d list set of int's
    #    undecided position: stores a set of  all options for each position
    #    filled position: 0
    # =====================================================================
    B = np.zeros((9, 9), dtype=int)
    C = [[0 for x in xrange(9)] for x in xrange(9)]

    #pivot_stack:
    #   A stack storing all pivot points that facilitate back-tracing algorithm
    pivot_stack = []
    StackElem = namedtuple('StackElem', 'ind choice A')

    A_old = A.copy()
    conflict = update(A, B, C)
    #    update_counter = 1
    #    print "="*30
    #    print "Update %d" %update_counter
    #    update_counter = update_counter + 1

    #sudoku_print(A)

    #    color_print(A_old, A)
    #sudoku_print(A)
    while (A.min() == 0):
        if (not conflict):
            i, j = get_leastopt_ind(B)
            elem = StackElem((i, j), list(C[i][j]), A.copy())
            pivot_stack.append(elem)
        else:
            if (len(pivot_stack[-1].choice) > 1):
                del pivot_stack[-1].choice[0]
            else:
                while (len(pivot_stack[-1].choice) == 1):
                    del pivot_stack[-1]
                del pivot_stack[-1].choice[0]
            np.copyto(A, pivot_stack[-1].A)

        i, j = pivot_stack[-1].ind
        np.copyto(A_old, A)

        A[i, j] = pivot_stack[-1].choice[0]
        conflict = update(A, B, C)
Ejemplo n.º 27
0
def main():
    """Main game function."""
    try:
        data = load_data()
        data = update.update(data)
    except:
        # print(sys.exc_info())
        data_constructor.build_data()
        data = load_data()
    data["want_to_play"] = True
    data["start"] = time.time()
    actions = {"quit": quit,
               "look": check_status,
               "shop": buy_menu.menu,
               "yard": placement.menu,
               "collect money": collect_money,
               "check food": placement.check_food,
               "help": print_help}
    banner()
    data["prefix"] = "{.BLUE}[Welcome!]{.ENDC}".format(
        printer.PColors, printer.PColors)
    check_status(data)
    data["prefix"] = "[Main Menu]"
    while data["want_to_play"] is True:
        data["prefix"] = "{.MAIN}[Main Menu]{.ENDC}".format(
            printer.PColors, printer.PColors)
        printer.prompt(data["prefix"], actions.keys())
        inp = input("{0} Choose an action! ".format(data["prefix"]))
        # pdb.set_trace()
        if inp in actions:
            actions[inp](data)
            continue
        else:
            printer.invalid(data["prefix"])
Ejemplo n.º 28
0
 def do_POST(self):
     try:
         subscribe_list = (self.rfile.read(int(self.headers['content-length']))).decode('utf-8')
         subscribe_list = subscribe_list.split('$')
     except:
         self.send_response(400)
         self.send_header("Content-Type", "text/html; charset=UTF-8")
         self.end_headers()
         self.wfile.write(bytes("parameters error!", "utf-8"))
     else:
         try:
             value = update(subscribe_list)
         except:
             self.send_response(500)
             self.send_header("Content-Type", "text/html; charset=UTF-8")
             self.end_headers()
             self.wfile.write(bytes("update error!", "utf-8"))
         else:
             if type(value).__name__ == 'str':
                 self.send_response(500)
                 self.send_header("Content-Type", "text/html; charset=UTF-8")
                 self.end_headers()
                 self.wfile.write(bytes(value, "utf-8"))
             else:
                 self.send_response(200)
                 self.send_header("Content-Type", "application/json")
                 self.end_headers()
                 self.wfile.write(bytes(json.dumps(value), "utf-8"))
Ejemplo n.º 29
0
def mainLoop(config, repeat=False):
    """Loop for the friendly interface with the program"""
    if repeat:
        choice = input("Please enter a valid option\n")
    else:
        choice = input(welcome_txt)

    if choice not in ["0", "1", "2", "3"]:
        mainLoop(config, repeat=True)
    elif choice == "0":
        help()
    elif choice == "1":
        ID = input("Enter your playlist ID\n")
        pl_file = upd.update(ID)
        downloadB = input("Download this playlist ? [y/n]\n")
        if downloadB.lower() == "y":
            music_folder = config["music_folder"]
            with open(pl_file, "r") as playlist_file:
                final_list = json.load(playlist_file)
            dlf.Download_Playlist(final_list, music_folder)
    elif choice == "2":
        playlist_file = input(
            "Enter the name of your playlist file for which you want stats\n")
        stats.statistfy(f"userdata/{playlist_file}")
    elif choice == "3":
        print("Goodbye !")
        sys.exit(0)
Ejemplo n.º 30
0
 def SetGlobalVars(self):
     globalVars.update = update.update()
     dl = player.getDeviceList()
     dl[0] = "default"
     dc = globalVars.app.config.getstring("player", "outputDevice",
                                          "default", dl)
     if dc == "default": device = PLAYER_DEFAULT_SPEAKER
     elif dc != None: device = dc
     else: device = PLAYER_DEFAULT_SPEAKER
     globalVars.play = player.player(PLAYER_DEFAULT_SPEAKER)
     if device != PLAYER_DEFAULT_SPEAKER:
         globalVars.play.setDeviceByName(device)
     globalVars.play.setVolume(
         globalVars.app.config.getint("volume",
                                      "default",
                                      default=100,
                                      min=0,
                                      max=100))
     globalVars.eventProcess = event_processor.eventProcessor()
     globalVars.sleepTimer = sleep_timer.sleepTimer()
     globalVars.m3uHistory = m3uManager.loadHistory()
     globalVars.listInfo = listManager.listInfo()
     globalVars.lampController = netRemote.lampController()
     globalVars.lampController.start()
     globalVars.filter = filterManager.FilterManager()
Ejemplo n.º 31
0
def mainloop():
    update.initupdate()
    draw.draw()
    delete.delete()
    while True:
        update.update()
        draw.draw()
        delete.delete()
        if config.quit:
            draw.draw("end")
            getpass.getpass("")
            break
        elif config.pause:
            draw.draw("pause")
            keyboard.wait("space+p")
            config.pause = False
Ejemplo n.º 32
0
    def menu(self):
        while self.dato:
            selection = input(
                '\nSelecciona 1 para insertar, 2 para actualizar, 3 para leer, 4 para borrar.\n'
            )

            if selection == '1':
                insert.insert()
            elif selection == '2':
                update.update()
            elif selection == '3':
                read.read()
            elif selection == '4':
                delete.delete()
            else:
                print('\nSelección inválida.')
Ejemplo n.º 33
0
def dispatch(intent_request):
    """
    Called when the user specifies an intent for this bot.
    """

    # logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))

    intent_name = intent_request['currentIntent']['name']
    print intent_name
    # # Dispatch to your bot's intent handlers
    if intent_name == SCALAR_RETRIEVE:
        return scalarCellRetrievalIntent.scalarCellRetrieval(intent_request)
    if intent_name == LIST_RETRIEVE:
        return ListRetrievalIntent.listRetrieval(intent_request)
    # elif intent_name == WF_ACTION:
    #     return perform_wf_action(intent_request)
    # elif intent_name == HELP_NAVIGATE:
    #     return help_navigate(intent_request)
    # elif intent_name == HELP_TICKET:
    #     return help_ticket(intent_request)
    elif intent_name == NAVIGATE:
        return NavigateIntent.navigate(intent_request)
    elif intent_name == CREATE:
        return CreateIntent.create(intent_request)
    elif intent_name == UPDATE:
        return UpdateIntent.update(intent_request)
    # elif intent_name == SAVE_TO_WORKSPACE:
    #     return save_to_workspace(intent_request)
    elif intent_name is None:
        #raise Exception('Intent not found')
        print 'ff'
    else:
        raise Exception('Intent with name ' + intent_name + ' not supported')
Ejemplo n.º 34
0
    def do_update(self, event):
        # Action name
        action = strings.UPDATING_APPSNAP
        
        # Disable GUI
        self.disable_gui()
        
        # Update statusbar
        self.update_status_bar(action, strings.DOWNLOADING + ' ...')

        # Perform the update
        update_obj = update.update(self.configuration, self.curl_instance)
        returned = update_obj.update_appsnap()
        
        if returned == update.SUCCESS:
            self.update_status_bar(action, strings.RELOADING_APPSNAP + ' ...')
            time.sleep(defines.SLEEP_GUI_DB_UPDATE_STEP)
            self.do_restart()
        elif returned == update.UNCHANGED:
            self.update_status_bar(action, strings.NO_CHANGES_FOUND)
            time.sleep(defines.SLEEP_GUI_DB_UPDATE_STEP)
        elif returned == update.NEW_BUILD:
            return self.error_out(action, strings.NEW_BUILD_REQUIRED)
        elif returned == update.READ_ERROR:
            return self.error_out(action, strings.UNABLE_TO_READ_APPSNAP)
        elif returned == update.WRITE_ERROR:
            return self.error_out(action, strings.UNABLE_TO_WRITE_APPSNAP)
        elif returned == update.DOWNLOAD_FAILURE:
            return self.error_out(action, strings.DOWNLOAD_FAILED)

        # Reset the GUI
        self.update_status_bar('', '')
        self.enable_gui()
Ejemplo n.º 35
0
 def newest_version(self):
     if (self.satisfy()):
         ud = update(self)
         return ud.check()
     else:
         # pretend we are up to date if not installed
         return True
Ejemplo n.º 36
0
def main():
    print ("test")
    #inialize
    ldr = LightSensor(4) ;
    var = 1
    value = 1
    #have the  program loop forever or until the user close the file
    while var != 0:
        var = 1
        if ldr.value != 0:
            toaddr = "*****@*****.**"  #email address to send email to
            now = datetime.datetime.now()           #time and date that the laser is tripped
            filename = str(now) + ".JPG"                   #name of picture file to send
            #take a picture
            newcam = cam(filename)
            newcam.takePic()
            #send the notification that the wire is tripped with the photo
            newEmail = Email(toaddr, filename)
            newEmail.SendEmail()
            #update the html
            up = update(filename)
            up.updateHTML()
            #upload the file to update the website
            upload = FTPClass()
            upload.UploadFile(filename)
            upload.UploadFile("index.html")
        #won't anymore picture to be taken until the laser hit the sensor
	    while ldr.value !=0:
		    print('0')
	else:
	    print('X')
Ejemplo n.º 37
0
 def newest_version(self):
     if(self.satisfy()):
         ud = update(self);
         return ud.check();
     else:
         # pretend we are up to date if not installed
         return True;
Ejemplo n.º 38
0
    def __init__(self):
        #
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        #self.__about = aboutDialog()
        self.__options = optionsDialog()
        self.__aboutDialog = aboutDialog()
        self.__logsDialog = logsDialog()
        self.__update = update()


        #Aliases for GUI objects
        self.__status = self.label_3
        self.__ip = self.label_4
        self.__ipStatus = self.label_12
        self.__lastupdateIp = self.label_7
        self.__lastupdateTime = self.label_9


        #Get user dialogs and decriptions
        self.i18n()

        #Refresh
        self.on_pushButton_9_clicked()

        self.__options.load()
Ejemplo n.º 39
0
 def actionUpdateWalletUi(self, to):
     import update
     try:
         data = update.update()
         return self.response(to, data)
     except Exception, err:
         print "Update error: %s" % err
Ejemplo n.º 40
0
def train(X, Y, nn_architecture, epochs, learning_rate):
    params_values = init_layers(nn_architecture, 2)
    cost_history = []
    accuracy_history = []

    for i in range(epochs):
        Y_hat, cache = full_forward_propagation(X, params_values,
                                                nn_architecture)
        # Y_hat_copy = np.copy(Y_hat)
        # print("Y_hat in train: ")
        # print(Y_hat)
        cost = get_cost_value(Y_hat, Y)
        cost_history.append(cost)
        accuracy = get_accuracy_value(Y_hat, Y)
        accuracy_history.append(accuracy)

        # print("Y_hat in train: ")
        # print(Y_hat)
        # print("Y_hat_copy in train: ")
        # print(Y_hat_copy)
        grads_values = full_backward_propagation(Y_hat, Y, cache,
                                                 params_values,
                                                 nn_architecture)
        # print("grads_values: ")
        # print(grads_values)
        params_values = update(params_values, grads_values, nn_architecture,
                               learning_rate)
        print(params_values)
        print('Cost after iteration ' + str(i) + ' : ' + str(accuracy))
    return params_values, cost_history, accuracy_history
Ejemplo n.º 41
0
def start(game, inputs_record):
    pygame.init()

    screen = pygame.display.set_mode(
        (draw.screen_w, draw.screen_h)
    )
    pygame.display.set_caption("ice-hall")

    clock = pygame.time.Clock()
    millis = 1
    exit = False
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: exit = True
            else: inputs_record = collect.collect(inputs_record, event)

        if exit: break

        game = update.update(game, inputs_record, millis/1000)

        draw.draw(screen, game)

        pygame.display.flip()
        millis = clock.tick(60)

    pygame.quit()
Ejemplo n.º 42
0
    def menu(self):

        while self.dato:
            # chossing option to do CRUD operations
            selection = input(
                '\nSelect 1 to insert, 2 to update, 3 to read, 4 to delete\n')

            if selection == '1':
                insert.insert()
            elif selection == '2':
                update.update()
            elif selection == '3':
                read.read()
            elif selection == '4':
                delete.delete()
            else:
                print('\n INVALID SELECTION \n')
Ejemplo n.º 43
0
	def run(self):
		time.sleep(5)
	#	print self.name
		# 更新文件信息
		mp3 = update.update(self.Data,self.mylock)
		mp3.search()
	#	print self.Data[0] + '/' +self.Data[1] + '.mp3'
		self.data.get()
Ejemplo n.º 44
0
    def __init__(self):
        ShowBase.__init__(self)

        self.world = createWorld(self.render)
        self.player = spawnPlayer(self.render, 0)
        self.player_cam = cameraControl("reparent", self.render.find("player_node"))
        self.create_filter = filters()
        self.update = update(self.render)
 def testUpdate(self):
     for inp, outp in self.update_cases.iteritems():
         # convert integers into boolean arrays
         inp_arr = i2a(*inp)
         outp_arr = i2a(*outp)
         # run the input array
         test_out = update.update(inp_arr, n1_wrap, rules.wolfram(30))
         # compare to the output array
         assert(numpy.all(test_out == outp_arr))
Ejemplo n.º 46
0
def main():
    print "- Starting ZeroNet..."

    main = None
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))  # Imports relative to src
        import main
        main.start()
        if main.update_after_shutdown:  # Updater
            import gc
            import update
            # Try cleanup openssl
            try:
                if "lib.opensslVerify" in sys.modules:
                    sys.modules["lib.opensslVerify"].opensslVerify.closeLibrary()
            except Exception, err:
                print "Error closing openssl", err

            # Update
            update.update()

            # Close log files
            logger = sys.modules["main"].logging.getLogger()

            for handler in logger.handlers[:]:
                handler.flush()
                handler.close()
                logger.removeHandler(handler)

    except (Exception, ):  # Prevent closing
        import traceback
        traceback.print_exc()
        traceback.print_exc(file=open("log/error.log", "a"))

    if main and main.update_after_shutdown:  # Updater
        # Restart
        gc.collect()  # Garbage collect
        print "Restarting..."
        args = sys.argv[:]
        args.insert(0, sys.executable)
        if sys.platform == 'win32':
            args = ['"%s"' % arg for arg in args]
        os.execv(sys.executable, args)
        print "Bye."
Ejemplo n.º 47
0
Archivo: uri.py Proyecto: pravj/pyURI
	def update(self,key,value=None):
		uri_backup = self.uri
		Data = self.data
		
		result = update(key,value,Data)
		try:
			self.__init__(result)
			#print result
		except:
			self.uri = uri_backup
			self.data = Data
			raise Exception("syntax error in updating '%s' key"%(key))
Ejemplo n.º 48
0
	def _libInit (self):
		try:
			# Initialize the main plugin engine
			self.plug = plug (self)
			self.update = update (self)
			self.ui = ui (self)
			self.support = support (self)
		
			self.logger.threaddebug("Dynamic libraries complete")
			
		except Exception as e:
			self.logger.error (ext.getException(e))	
Ejemplo n.º 49
0
def main():
    if len(sys.argv) > 1:
        global outputdir
        update.outputdir = outputdir = sys.argv[1]

    for station, code in eismoinfo.EismoInfo.ids.items():
        print station
        text = requests.get(URL.format(code, 1500)).text
        data = json.loads(text.split('<!DOCTYPE')[0])
        data.sort(key=lambda d: d["surinkimo_data_unix"])
        for chunk in grouper(100, data):
            sys.stdout.write(".")
            sys.stdout.flush()
            maxes = []
            avgs = []
            dirs = []
            for item in chunk:
                if item is None:
                    break
                item["irenginys"] = station
                readout = eismoinfo.Station(item)
                maxes.append((readout.timestamp, readout.max))
                avgs.append((readout.timestamp, readout.avg))
                dirs.append((readout.timestamp, readout.dir))
            # TODO: bunch up updates into a single command
            update.update("%s-max.rrd" % station, maxes)
            update.update("%s-avg.rrd" % station, avgs)
            update.update("%s-dir.rrd" % station, dirs)
        print

    os.system("sh graph.sh %s > /dev/null 2>&1 " % outputdir)
Ejemplo n.º 50
0
def run():
	# Login and save the html file to gen
	logging.info('Login and saving notice board html to gen')
	tpo = TpoSession()
	tpo.login()

	# From the html file, extract and save the notices
	logging.info('Extracting notice from notice board html.')
	num = insert.insert()
	if num is None:
		logging.error("Error encountered during extraction. Exiting.")
		exit()
	logging.info("Inserted %d notices.", num)

	# Update the json files to include the notice details and attachments
	logging.info('Updating json files')
	update.update()

	# Send the unsent notices
	logging.info('Sending unsent notices.')
	send.send_unsent()

	logging.info("Finished running script.")
Ejemplo n.º 51
0
def action(confData=False):
    if confData:    conf = confData
    else:           conf = config.load()
    result = [] # [const.reply(), ...]
    if conf:
        ip = update.readIp()
        if ip:
            hosts = conf.host.replace(" ", "").split(",")
            if hosts[0]:
                for host in hosts:
                    conf.host = host
                    result.append( update.update(ip, conf) )
            else:
                conf.host = ""
                result.append( update.update(ip, conf) )
        else:
            rep = update.parseResult(const.REPLY_NOIP)
            rep.updatedHostname = conf.host
            result.append( rep )
    else:
        rep = update.parseResult(const.REPLY_NOCONF)
        result.append( rep )
    return(result)
Ejemplo n.º 52
0
def updateStops(route, convertId):
    size = len(route.stop)
    #print "updateDone" + bytes(size)
    i = -1
    for stop1 in route.stop:
        i += 1
        j = -1
        for stop2 in route.stop:
            j += 1
            if (stop1.isGetOn != True or stop2.isGetOn != False):
                continue
                #return
            object_id = int(convertId) * MAXBUSINDEX + i * size + j
            #print "UpdateDone",object_id,stop1.lng,stop1.lat,stop2.lng,stop2.lat

            #i += 1
            #logger.debug("UpdateDone",object_id,stop1.lng,stop1.lat,stop2.lng,stop2.lat)
            logger.debug("UpdateDone=%ld,%lf,%lf,%lf,%lf",object_id,stop1.lng,stop1.lat,stop2.lng,stop2.lat)
            
            try:
                update(ip,port,stop1.lng,stop1.lat,stop2.lng,stop2.lat,object_id)
#                update(ip,port,stop2.lng,stop2.lat,object_id)
            except Exception,e:
                logger.error("UpdateException=%s:e=%s:%ld,%lf,%lf,%lf,%lf",Exception,e,object_id,stop1.lng,stop1.lat,stop2.lng,stop2.lat)
Ejemplo n.º 53
0
def load_tool(argsworkflow, updateonly, strict, makeTool, debug, print_pre=False):
    (document_loader, avsc_names, schema_metadata) = process.get_schema()

    uri = "file://" + os.path.abspath(argsworkflow)
    fileuri, urifrag = urlparse.urldefrag(uri)
    workflowobj = document_loader.fetch(fileuri)
    if isinstance(workflowobj, list):
        workflowobj = {"cwlVersion": "https://w3id.org/cwl/cwl#draft-2",
                       "id": fileuri,
                       "@graph": workflowobj}
    workflowobj = update.update(workflowobj, document_loader, fileuri)
    document_loader.idx.clear()

    if updateonly:
        print json.dumps(workflowobj, indent=4)
        return 0

    try:
        processobj, metadata = schema_salad.schema.load_and_validate(document_loader, avsc_names, workflowobj, strict)
    except (schema_salad.validate.ValidationException, RuntimeError) as e:
        _logger.error("Tool definition failed validation:\n%s", e, exc_info=(e if debug else False))
        return 1

    if print_pre:
        print json.dumps(processobj, indent=4)
        return 0

    if urifrag:
        processobj, _ = document_loader.resolve_ref(uri)
    elif isinstance(processobj, list):
        processobj, _ = document_loader.resolve_ref(urlparse.urljoin(argsworkflow, "#main"))

    try:
        t = makeTool(processobj, strict=strict, makeTool=makeTool)
    except (schema_salad.validate.ValidationException) as e:
        _logger.error("Tool definition failed validation:\n%s", e, exc_info=(e if debug else False))
        return 1
    except (RuntimeError, workflow.WorkflowException) as e:
        _logger.error("Tool definition failed initialization:\n%s", e, exc_info=(e if debug else False))
        return 1

    return t
Ejemplo n.º 54
0
def CheckNewUpdate():
    global Status, StatusLabel, branch
    try:
        Status = update.update()
        if Status == 0:
            Status = "New update is installed. Restart to see changes"
            ac.log('EpicRace: ' + Status)
            ac.setText(StatusLabel, Status)
        if Status == 2:
            Status = "No new update."
            ac.log('EpicRace: ' + Status)
            ac.setText(StatusLabel, Status)
        else:
            Status = "There was an error while installing new update.\nError code: " + str(Status)
            ac.log('EpicRace: Error Update ' + Status)
            ac.setText(StatusLabel, Status)
    except:
        Status = "no internet connection"
        ac.log('EpicRace: Autoupdate ' + Status + traceback.format_exc())
        ac.setText(StatusLabel, Status)
Ejemplo n.º 55
0
    def setUp(self):
        # Create test directory
        self.test_dir = 'test_dir'
        try: os.mkdir(self.test_dir)
        except WindowsError: pass
        os.chdir(self.test_dir)
        
        # Copy config.ini
        shutil.copyfile(os.path.join('..', config.CONFIG_INI), config.CONFIG_INI)

        # Setup
        self.config = config.config()
        self.curlInstance = curl.curl(self.config)
        self.version_url = self.config.update[config.LOCATION]
        self.update_obj = update.update(self.config, self.curlInstance, True)

        # Load remote version.py
        version_data = self.curlInstance.get_web_data(string.join([self.version_url, update.APPSNAPLIB_DIR, 'version.py'], '/'))
        assert version_data != None
        try: exec(self.update_obj.remove_cr(version_data))
        except: assert 1 == 0

        # Create subdirs
        self.dirs = [update.APPSNAPLIB_DIR]
        for locale in LOCALES:
            self.dirs.append(os.path.join(update.LOCALE_DIR, locale, 'LC_MESSAGES'))
        for dir in self.dirs:
            try: os.makedirs(dir)
            except WindowsError: pass

        # Download release
        for file in FILES:
            self.curlInstance.download_web_data(string.join([self.version_url, update.APPSNAPLIB_DIR, file], '/'), os.path.join(update.APPSNAPLIB_DIR, file), '')

        for file in MISC:
            self.curlInstance.download_web_data(string.join([self.version_url, file], '/'), file, '')

        for locale in LOCALES:
            for file in ['appsnap.po', 'appsnap.mo']:
                self.curlInstance.download_web_data(string.join([self.version_url, update.LOCALE_DIR, locale, 'LC_MESSAGES', file], '/'), \
                    os.path.join(update.LOCALE_DIR, locale, 'LC_MESSAGES', file), '')
Ejemplo n.º 56
0
    def check_update(self):
        if self.configuration.update[config.STARTUP_CHECK] == 'True':
            # Disable GUI
            self.disable_gui()

            # Yield for section list to load
            self.resources['gui'].objects['application'].Yield(True)
            
            # Set statusbar text
            self.update_status_bar(strings.CHECKING_FOR_UPDATES, '')
            
            # Check for update
            update_obj = update.update(self.configuration, self.curl_instance, True)
            returned = update_obj.update_appsnap()
            
            # Notify user of changes
            if returned == update.CHANGED:
                self.update_status_bar(strings.UPDATES_AVAILABLE, strings.CLICK_FOR_UPDATE)
            else:
                self.update_status_bar('', '')

            # Disable GUI
            self.enable_gui()
Ejemplo n.º 57
0
 def testSearch(self):
     walk.walk(self.base_dir)
     update.update(self.base_dir, concurrency=2)
     print search.search(self.base_dir, "総務省/subdir", "xls")
Ejemplo n.º 58
0
# Script to update the XLLs delivered by the Launcher
# from files on the network

import update

SOURCE_TARGET_LIST = (
#    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/R000900-branch/xll", "Addins/01 Production", "QuantLibXLDynamic-vc80-mt-0_9_0.xll" ),
#    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/R000900-branch/xll", "Addins/01 Production", "ObjectHandler-xll-vc80-mt-0_9_0.xll" ),
#    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/R000900-branch/xll", "Addins/01 Production", "saohxll-vc80-mt-0_1_9.xll" ),
#    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/R000900-branch/xll", "Addins/01 Production", "PDGLib_candidate.xll" ),

    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/Rev14441/xll", "Addins/01 Production", "QuantLibXLDynamic-vc80-mt-0_9_5.xll" ),
    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/Rev14441/xll", "Addins/01 Production", "ObjectHandler-xll-vc80-mt-0_9_5.xll" ),
    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/Rev14441/xll", "Addins/01 Production", "PDGLib.xll" ),

    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/Rev14991/xll", "Addins/02 Pre-Production", "QuantLibXLDynamic-vc90-mt-0_9_5.xll" ),
    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/Rev14991/xll", "Addins/02 Pre-Production", "ObjectHandler-xll-vc90-mt-0_9_5.xll" ),
    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/Rev14991/xll", "Addins/02 Pre-Production", "PDGLib.xll" ),

    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/Rev15125/xll", "Addins/03 Testing", "QuantLibXLDynamic-vc80-mt-0_9_5.xll" ),
    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/Rev15125/xll", "Addins/03 Testing", "ObjectHandler-xll-vc80-mt-0_9_5.xll" ),
    ( "\\\\srv0001.caboto.it/risorse/Apps/Appsscript/CabotoXL/Rev15125/xll", "Addins/03 Testing", "PDGLib.xll" ),

)

update.update(SOURCE_TARGET_LIST)
 def new_window1(self):
     up.update()
Ejemplo n.º 60
0
def get_time():
    games_today = []
    games_file = open(STORAGE_FILE, 'r')
    game_data = games_file.readlines()
    games_file.close()

    for game in game_data:
        if get_date(game) == str(date.today().day):
            games_today.append(get_dur(game))

    total = 0
    for game in games_today:
        total += int(game)

    return total


while True:
    new_game = update(SUMMONER_NAME, lol_api_key, STORAGE_FILE)
    if new_game:
        time_left = SCREEN_TIME_SEC - get_time()
        if time_left < 0:
            exact = float(abs(time_left)) / float(60)
            seconds = int((exact - int(exact)) * 60)
            minutes = int(exact)
            text = "You are " + str(minutes) + " minutes and " + str(seconds) + " seconds over your " + str(SCREEN_TIME) + ' hour screen time.'
            message = client.sms.messages.create(body=text, to=YOUR_PHONE_NUMBER, from_=TWILIO_PHONE_NUMBER)
            print "Text sent!"

    time.sleep(2*60)