Пример #1
0
def main():
    """Schedule and run strategy."""
    url, port, plantID, devID, ts_url, ts_port = functions.read_file(FILE)
    thread1 = SchedulingThread(1, "thread1")
    thread1.start()

    while True:
        url, port, plantID, devID, ts_url, ts_port = functions.read_file(FILE)
        string = ("http://" + url + ":" + port + "/info/" + plantID)
        data = json.loads(requests.get(string).text)
        hours = data["hours"]
        env = data["environment"]

        global TIME_LIST
        for h in hours:
            t = h["time"]
            delayed_hour = functions.delay_h(t, -300)
            entry = {
                "hour": t,
                "schedule_time": delayed_hour,
                # "schedule_time": "15:43",
                "env": env
            }
            TIME_LIST.append(entry)  # Fill timetable.
            print("Rain check at: %s - %s" % (delayed_hour, plantID))

        time.sleep(86400)  # One day
        TIME_LIST = []  # Reset timetable
Пример #2
0
def main():
    """Start all threads."""
    url, port, plantID, devID, ts_url, ts_port = functions.read_file(FILE)
    thread1 = SchedulingThread(1, "thread1")
    thread1.start()

    while True:
        url, port, plantID, devID, ts_url, ts_port = functions.read_file(FILE)
        string = ("http://" + url + ":" + port + "/info/" + plantID)
        data = json.loads(requests.get(string).text)
        hours = data["hours"]

        global TIME_LIST
        for h in hours:
            t = h["time"]
            s_t = h["time"]
            entry = {
                "hour": t,
                "schedule_time": s_t,
                "plantID": plantID,
                "devID": devID
            }
            TIME_LIST.append(entry)
            print("Schedule: %s - %s" % (t, plantID))

        time.sleep(86400)
        TIME_LIST = []
Пример #3
0
def main():
    config = {}
    execfile("./ignore_files/project.conf", config)
    # print config["value1"]

    my_file = "/Users/bethnakamura/Projects/html_data_scraper/ignore_files/ge-sr-software-capabilty.txt"
    print functions.read_file(my_file)
    print "Main function ran"
Пример #4
0
 def test_write_file(self):
     from os import remove
     empty_string = ""
     text = "123\n456\n"
     file_path = AuxiliaryTestMethods.create_temp_text_file(empty_string)
     self.assertEqual(functions.read_file(file_path), empty_string)
     self.assertNotEqual(functions.read_file(file_path), text)
     functions.write_file(file_path, text)
     self.assertEqual(functions.read_file(file_path), text)
     remove(file_path)
Пример #5
0
def test_save_file_should_create_a_students_file_with_one_name_given_a_single_student_name(
):
    # arrange

    # act
    functions.save_file("Kevin")
    functions.read_file()

    # assert
    assert len(functions.students) == 1
    assert functions.students[0]["student_name"] == "Kevin\n"
Пример #6
0
    def test_read_file(self):
        from sys import argv
        from os import remove
        text1 = functions.read_file(argv[0])
        text2 = functions.read_file(argv[0])
        self.assertEqual(text1, text2)
        self.assertTrue("def test_read_file(self):" in text1)

        string = "123\n456\n"
        file_path = AuxiliaryTestMethods.create_temp_text_file(string)
        text3 = functions.read_file(file_path)
        self.assertNotEqual(text1, text3)
        self.assertEqual(text3, string)
        remove(file_path)
Пример #7
0
 def _setup_for_new_branch(commit):
     """Create working files and rewrite index for the current branch."""
     new_content_index = ''
     content_snap = read_file(lgit_path +
                              '/.lgit/snapshots/%s' % commit).split('\n')
     for line_snap in content_snap:
         content = read_file(lgit_path + '/.lgit/objects/%s/%s' %
                             (line_snap[:2], line_snap[2:40]))
         file_name = content_snap[41:]
         _create_working_files(file_name, content)
         timestamp = format_mtime(file_name)
         new_content_index += (timestamp + (' ' + line_snap[:40]) * 3 + ' '
                               + file_name + '\n')
         write_file(lgit_path + '/.lgit/index', new_content_index)
def print_hi(name):

    option = int(
        input(
            "Introdueix què vols fer amb el fitxer: 1)Crear   2)Mostrar contingut 3)modificar contingut  4)sortir"
        ))

    if option == 1:
        fc.create_file_content()
    elif option == 2:
        fc.read_file()
    elif option == 3:
        fc.append_text()
    elif option == 4:
        print("Has sortit del programa")
Пример #9
0
def main():
    arguments = sys.argv

    if arguments[1] == "--read":
        functions.read_file(arguments[2])
    elif arguments[1] == "--write":
        functions.write_file(arguments[2])
    elif arguments[1] == "--append":
        functions.append_file(arguments[2])
    elif arguments[1] == "--read-remote":
        functions.read_remote_file()
    elif arguments[1] == "--help":
        print(
            "To read a file use --read followed by a file name, to read a file on a remote server use --read-remote, to write a new file use --write followed by a file name, and to edit a file already exisiting use --append followed by the file name."
        )
Пример #10
0
def signUp():
    name = request.json['name']
    email = request.json['email']
    password = request.json['password']
    users = read_file()
    userFound = False
    idx = 1
    if users:
        for user in users:
            if user['email'] == email:
                userFound = True
                break
        idx = users[-1]['id']
    if userFound:
        return json.dumps({'message': 'User already exists!!!', 'error': True})
    else:
        salt = generate_salt()
        password_hash = generate_hash(password, salt)
        users.append({
            'id': idx,
            'name': name,
            'email': email,
            'salt': salt,
            'password_hash': password_hash
        })
        write_file(users)
        return json.dumps({
            'message': 'User created Successfully!!!',
            'error': False
        })
Пример #11
0
def login():
    email = request.json['email']
    password = request.json['password']
    userFound = False
    users = read_file()
    idx = 0
    for i, user in enumerate(users):
        if user['email'] == email:
            userFound = True
            idx = i
            break
    if not userFound:
        return json.dumps({
            'message': "User does not exists!!!",
            'error': True
        })
    else:
        salt = users[idx]['salt']
        password_hash = generate_hash(password, salt)
        if password_hash == users[idx]['password_hash']:
            return json.dumps({
                'message': 'User login Successful!!!',
                'error': False
            })
        else:
            return json.dumps({
                'message': 'Wrong Password Entered!!!',
                'error': True
            })
Пример #12
0
def show_main_page():
    st.title('Задача про покриття множини')

    input_type = st.radio('Оберіть вид вводу даних', ('Завантаження даних з файлу', 'Генерація даних'))
    if input_type == 'Завантаження даних з файлу':
        file = st.file_uploader('Завантажте файл:')
        candidates = read_file(file)

    elif input_type == 'Генерація даних':
        st.subheader('Оберіть параметри')
        num_of_candidates = st.slider('Кількість кандидатів:', 2, 100, 10)
        num_of_groups = st.slider('Кількість груп:', 1, 10, 5)

        subgroups = [3]*num_of_groups
        st.subheader('Оберіть кількість підгруп в кожній групі')
        for group in range(num_of_groups):
            subgroups[group] = st.slider(f'Кількість підгруп в групі {group+1}', 2, 6, 3)

        candidates = get_data(num_of_candidates, subgroups)

    if isinstance(candidates, bool):
        st.header('Перевірте обрані параметри, будь ласка')
    else:
        if st.button('Показати дані'):
            st.dataframe(pd.DataFrame(candidates))

        algorithms = st.multiselect('Оберіть алгоритм', ('Жадібний алгоритм #1','Жадібний алгоритм #2','Жадібний алгоритм #3','Генетичний алгоритм #1','Генетичний алгоритм #2'))

        if 'Генетичний алгоритм #1' in algorithms or 'Генетичний алгоритм #2' in algorithms:
            st.subheader('Оберіть параметри для генетичного алгоритму')
            population_size = st.slider('Розмір популяції:', 0, 100, 10)
            alpha = st.slider('Альфа:', 0.0, 1.0, 0.5)
            iter_num = st.slider('Кількість ітерацій:', 1, 100, 20)

        if st.button('Розв\'язати задачу!'):
            st.header('Відповідь')
            for algorithm in algorithms:
                args = [candidates]

                if algorithm == 'Жадібний алгоритм #1':
                    fn = first_greedy_algorithm
                    args.append([0])
                elif algorithm  == 'Жадібний алгоритм #2':
                    fn = second_greedy_algorithm
                elif algorithm  == 'Жадібний алгоритм #3':
                    fn = third_greedy_algorithm
                elif algorithm  == 'Генетичний алгоритм #1' or algorithm  == 'Генетичний алгоритм #2':
                    args.append(population_size)
                    args.append(alpha)
                    args.append(iter_num)
                    if algorithm  == 'Генетичний алгоритм #1':
                        fn = first_genetic_algorithm
                    else:
                        fn = second_genetic_algorithm

                result = fn(*args)
                st.subheader(f'Метод розв\'язання - {algorithm}')
                st.write(f'Значення цільової функції: {len(result)}')
                st.write(f'Комітет складається з наступних кандидатів: {str(result)}')
                st.altair_chart(create_chart(candidates, result), use_container_width=True)
Пример #13
0
 def _display_commit(file):
     """Display each commit."""
     content = read_file(lgit_path + '/.lgit/commits/%s' % file).split('\n')
     print('commit ' + file)
     print('Author: ' + content[0])
     print('Date: ' + get_readable_date(file), end='\n\n')
     print('    %s\n' % content[3])
Пример #14
0
def get_result(env, hour):
    """Get data from ThingSpeak adaptor and decide.

    Get the last entries on rain field and decides if it is necessary or not
    to irrigate.
    """
    url, port, plantID, devID, ts_url, ts_port = functions.read_file(FILE)
    resource = "rain"
    time = "minutes"
    tval = str(5 * 60)  # Check if it has rained in previous hours
    string = ("http://" + ts_url + ":" + ts_port + "/data/" + plantID + "/" +
              resource + "?time=" + time + "&tval=" + tval + "&plantID=" +
              plantID + "&devID=" + devID)
    print(string)
    data = json.loads(requests.get(string).text)
    data = data["data"]

    # Rain strategy.
    if data != []:
        m = np.mean(data)
        if m >= 0.6:  # Rain for at least 60% of the time
            duration = -900000  # Do not irrigate

        elif (m >= 0.4) and (m < 0.6):  # Rain from 40-60% of the time
            duration = -200  # Remove 200 seconds

        else:  # Almost no rain
            duration = None  # No modifications

        if duration is not None:
            functions.post_mod(plantID, hour, duration, 0, url, port)
def add_new_story():
    '''
    Writes the new story to the file, based on the user inputs.
    '''
    if functions.valid_value(
            request.form['business_value']) and functions.valid_time(
                request.form['estimation_time']):
        with open('result.txt', 'a') as file:
            file.write(
                str(int(functions.read_file('result.txt')[-1][0]) + 1) + ',')
            file.write(
                str(functions.convert_string(request.form['story_title'])) +
                ',')
            file.write(
                str(functions.convert_string(request.form['user_story'])) +
                ',')
            file.write(
                str(
                    functions.convert_string(
                        request.form['acceptance_criteria'])) + ',')
            file.write(str(int(request.form['business_value'])) + ',')
            file.write(
                str(functions.correct_time(request.form['estimation_time'])) +
                ',')
            file.write(str(request.form['status']) + '\n')
        return redirect('/list')
    else:
        return render_template('error.html')
Пример #16
0
def upload_file():
    print("Uploading CSV... ")
    error = ''
    #    os.remove('Output.zip')
    try:
        if request.method == 'POST':
            f = request.files['file']
            f.save(secure_filename(f.filename))
            df = read_file(f.filename)
            df_out = model_run(df)
            print("Out from model_run")
            #df.to_csv('predictoutput.zip',sep=',',index=False)
            #os.remove(f.filename)
            #return render_template("view.html",tables=[df1.to_html()], titles = ['Predicted O/P'])
            return render_template(
                "formout.html",
                tables=[df, df_out],
                titles=['Inputs Given', 'O/p Predicted by different Models'])
            #return render_template("view.html",name='Predicted O/P', tables=[df_summ.to_html(),df1.to_html()], titles = ['Error Metrics','Predicted O/P'])
            #jsonfiles = json.loads(df.head().to_json(orient='records'))
            #return render_template('view.html', ctrsuccess=jsonfiles)
            #tables=[df.to_html(classes='dataframe')], titles = ['na', 'Predicted O/P'])
            #flash("File uploaded")
        error = "File Not uploaded"
        return render_template("dashboard.html", error=error)
    except Exception as e:
        #flash(e)
        print(e)
        return render_template("dashboard.html", error=error)
def modify_story(story_id):
    '''
    Saves the changes to the file, based on the user inputs.
    '''
    if functions.valid_value(
            request.form['business_value']) and functions.valid_time(
                request.form['estimation_time']):
        story_list = functions.read_file('result.txt')
        for story in story_list:
            if int(story[0]) == int(story_id):
                story[1] = str(
                    functions.convert_string(request.form['story_title']))
                story[2] = str(
                    functions.convert_string(request.form['user_story']))
                story[3] = str(
                    functions.convert_string(
                        request.form['acceptance_criteria']))
                story[4] = str(int(request.form['business_value']))
                story[5] = str(
                    functions.correct_time(request.form['estimation_time']))
                story[6] = str(request.form['status'])
                break
        functions.write_file('result.txt', story_list)
        return redirect('/list')
    else:
        return render_template('error.html')
Пример #18
0
def models(model):
    try:
        models = functions.read_file('models/model_list.json',
                                     json_format=True)['models']
        filepath = 'models/{modelname}.json'.format(
            modelname=models[model.lower()]['modelName'])
        model = functions.read_file(filepath, json_format=True)
        model = functions.build_full_model(model)
        example = functions.build_example_json(model)
        return functions.render_view(
            'model.html', {
                'model': model,
                'example': json.dumps(example, indent=4, sort_keys=True)
            })
    except:
        return "404"
Пример #19
0
def get_result(env, hour):
    """Get data from ThingSpeak adaptor and decide.

    Get the last entries on humidity field and decides if it is necessary or
    not to modify duration of irrigation.
    """
    url, port, plantID, devID, ts_url, ts_port = functions.read_file(FILE)
    resource = "humidity"
    time = "minutes"
    tval = str(5 * 60)  # Check humidity trending in previous hours
    string = ("http://" + ts_url + ":" + ts_port + "/data/" + plantID + "/" +
              resource + "?time=" + time + "&tval=" + tval + "&plantID=" +
              plantID + "&devID=" + devID)
    print(string)
    data = json.loads(requests.get(string).text)
    data = data["data"]

    # Humidity strategy.
    if data != []:
        m = np.mean(data)

        diff = np.abs(env["humidity"] - m)
        duration = 100 * np.arctan(0.05 * diff)  # Add 300 seconds.
        duration = round(duration)
    else:
        duration = None

    if duration is not None:
        functions.post_mod(plantID, hour, duration, 0, url, port)
Пример #20
0
def get_result(env, hour, type):
    """Get data from ThingSpeak adaptor and decide.

    Get the last entries on light field and decides if it is necessary or
    not to modify duration of irrigation.
    """
    url, port, plantID, devID, ts_url, ts_port = functions.read_file(FILE)
    resource = "light"
    time = "minutes"
    tval = str(2 * 60)  # Check light trending in previous hours
    string = ("http://" + ts_url + ":" + ts_port + "/data/" + plantID + "/" +
              resource + "?time=" + time + "&tval=" + tval + "&plantID=" +
              plantID + "&devID=" + devID)
    print(string)
    data = json.loads(requests.get(string).text)
    data = data["data"]

    # Light strategy.
    delay = 0
    if data != []:
        m = np.mean(data)
        print("Resistance: %d" % m)

        if type == 'evening':
            print("Checking evening light condition...")
            if (m >= 140) and (m < 160):  # Very dark
                delay = -1800  # Anticipation of 30 minutes

            elif (m >= 110) and (m < 140):  # Dark
                delay = -900  # Anticipation of 15 minutes

            elif (m >= 90 and m < 110):  # Ideal
                delay = 0  # Ideal time, no delay

            elif (m >= 70 and m < 90):  # Bright
                delay = 1800  # Posticipation of 30 minutes

            elif (m < 70):  # Very bright
                delay = 3600  # Posticipation of 60 minutes

        elif type == 'morning':
            print("Checking morning light condition...")
            if (m >= 140) and (m < 160):  # Very dark
                delay = 3600  # Posticipation of 60 minutes

            elif (m >= 110) and (m < 140):  # Dark
                delay = 1800  # Posticipation of 30 minutes

            elif (m >= 90 and m < 110):  # Ideal
                delay = 0  # Ideal time, no delay

            elif (m >= 70 and m < 90):  # Bright
                delay = -900  # Anticipation of 15 minutes

            elif (m < 70):  # Very bright
                delay = -1800  # Anticipation of 30 minutes

        if delay != 0:
            functions.post_mod(plantID, hour, 0, delay, url, port)
Пример #21
0
def list_lgit_files(args, lgit_path):
    """Show information about files in the index and the working tree."""
    content_index = read_file(lgit_path + '/.lgit/index').split('\n')
    list_files = []
    for line in content_index:
        list_files.append(line[138:])
    for file in sorted(list_files):
        if file != '':
            print(file)
Пример #22
0
def get_result(env, hour):
    """Get data from ThingSpeak adaptor and decide.

    Get the last entries on wind field and decides if it is necessary or
    not to modify duration of irrigation.
    """
    url, port, plantID, devID, ts_url, ts_port = functions.read_file(FILE)
    resource = "wind"
    time = "minutes"

    # Check wind trending in previous minutes (short term).
    tval = str(10)
    string = ("http://" + ts_url + ":" + ts_port + "/data/" + plantID + "/" +
              resource + "?time=" + time + "&tval=" + tval + "&plantID=" +
              plantID + "&devID=" + devID)
    print(string)
    data = json.loads(requests.get(string).text)
    data_short = data["data"]

    # Check wind trending in previous hours (long term).
    tval = str(10 * 60)
    string = ("http://" + ts_url + ":" + ts_port + "/data/" + plantID + "/" +
              resource + "?time=" + time + "&tval=" + tval + "&plantID=" +
              plantID + "&devID=" + devID)
    print(string)
    data = json.loads(requests.get(string).text)
    data_long = data["data"]

    # Wind strategy.

    val1 = 0
    val2 = 0

    # During an extended period of time.
    if data_long != []:
        m2 = np.mean(data_long)
        if (m2 >= 3) and (m2 <= 10):  # Light wind
            val2 = 60  # Augment duration by 60 seconds
        elif m2 > 10:  # Strong wind
            val2 = 120  # Augment duration by 120 seconds
        else:  # No wind
            val2 = 0  # No modification

    # In real time.
    if data_short != []:
        m1 = np.mean(data_short)
        if (m1 >= 3) and (m1 <= 10):  # Light wind
            val1 = 90  # Augment duration by 90 seconds
        elif m1 > 10:  # Strong wind
            val1 = 150  # Augment duration by 150 seconds
        else:  # No wind
            val1 = 0  # No modification

    duration = val1 + val2
    if duration is not None:
        functions.post_mod(plantID, hour, duration, 0, url, port)
Пример #23
0
def content_handler(view='index'):
    view = view.lower()
    if view in constants.content_items:
        try:
            filepath = 'content/{view}.md'.format(view=view)
            view_contents = functions.read_file(filepath, json_format=False)
            title = view_contents.split('---')[0]
            content = Markup(markdown.markdown(view_contents.split('---')[1]))
        except:
            filepath = 'content/{view}.html'.format(view=view)
            view_contents = functions.read_file(filepath, json_format=False)
            title = view_contents.split('---')[0]
            content = view_contents.split('---')[1]
        return functions.render_view('content.html', {
            'title': title,
            'content': content
        })
    else:
        return "404"
def delete_story(story_id):
    '''
    Deletes the chosen story from the file.
    '''
    story_list = functions.read_file('result.txt')
    for story in story_list:
        if int(story[0]) == int(story_id):
            story_list.remove(story)
    functions.write_file('result.txt', story_list)
    return redirect('/list')
Пример #25
0
def main():

    try:

        functions.read_file(sys.argv[1])
        functions.get_app_num_pub_filing_date()

        if data.values[0] and data.values[1] != "":  # to check if the page is a patent or not
            functions.get_title()
            functions.get_abstract()
            functions.get_name_of_applicant()
            functions.get_name_of_inventor()
            functions.get_int_class_priorty_doc_num()
            functions.get_int_app_pub_num()
            functions.print_data()
        else:
            print "Not a patent"

    except:
        print "Error in extracting"
def show_story(story_id):
    '''
    Redirects to a page where the user can change the elements of the chosen story.
    '''
    story_list = functions.restore_comma(functions.read_file('result.txt'))
    selected_story = ''
    for story in story_list:
        if int(story[0]) == int(story_id):
            selected_story = story
            break
    return render_template('form.html',
                           story=selected_story,
                           story_id=story_id)
Пример #27
0
def main(nqubits, instance, T, chainstrength, numruns, greedy, inspect):
    """

    Args:
        nqubits (int): number of qubits for the file that contains the
            information of an Exact Cover instance.
        instance (int): intance used for the desired number of qubits.
        T (float): 
        

    Returns:
        
    """
    control, solution, clauses = functions.read_file(nqubits, instance)
    nqubits = int(control[0])
    times = functions.times(nqubits, clauses)
    sh, smap = functions.h_problem(nqubits, clauses)
    Q, constant = functions.symbolic_to_dwave(sh, smap)
    

    model = dimod.BinaryQuadraticModel.from_qubo(Q, offset = 0.0)
    if not chainstrength:
        chainstrength = dwave.embedding.chain_strength.uniform_torque_compensation(model)
        print(f'Automatic chain strength: {chainstrength}\n')
    else:
        print(f'Chosen chain strength: {chainstrength}\n')

    if solution:
        print(f'Target solution that solves the problem: {" ".join(solution)}\n')

    sampler = EmbeddingComposite(DWaveSampler())
    if greedy:
        solver_greedy = SteepestDescentSolver()
        sampleset = sampler.sample(model, chain_strength=chainstrength, num_reads=numruns, annealing_time=T, answer_mode='raw')
        response = solver_greedy.sample(model, initial_states=sampleset)
    else:
        response = sampler.sample(model, chain_strength=chainstrength, num_reads=numruns, annealing_time=T, answer_mode='histogram')
    
    
    best_sample = response.record.sample[0]
    best_energy = response.record.energy[0]
    print(f'Best result found: {best_sample}\n')
    print(f'With energy: {best_energy+constant}\n')
    good_samples = response.record.sample[:min(len(response.record.sample), nqubits)]
    good_energies = response.record.energy[:min(len(response.record.energy), nqubits)]
    print(f'The best {len(good_samples)} samples found in the evolution are:\n')
    for i in range(len(good_samples)):
        print(f'Sample: {good_samples[i]}    with energy: {good_energies[i]+constant}\n')

    if inspect:
        dwave.inspector.show(response)
Пример #28
0
def models_home():
    filepath = 'models/model_list.json'
    model_list = functions.read_file(filepath, json_format=True)
    models = model_list['models_order']
    event_core = model_list['event_core']
    event_elements = model_list['event_elements']
    event_booking = model_list['event_booking']
    return functions.render_view(
        'models.html', {
            'models': models,
            'event_core': event_core,
            'event_elements': event_elements,
            'event_booking': event_booking
        })
Пример #29
0
 def _create_commit_object(message):
     """Create the commit object when commit the changes."""
     # Get the author name for the commits:
     author = read_file(lgit_path + '/.lgit/config').strip('\n')
     # If the config file is empty:
     if not author:
         exit()
     try:
         with open(lgit_path + '/.lgit/commits/%s' % ms_timestamp_now,
                   'w') as commit:
             # Write file in the commits directory:
             commit.write('%s\n%s\n\n%s\n\n' %
                          (author, timestamp_now, message))
     except PermissionError:
         pass
Пример #30
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', help='input help')
    args = parser.parse_args()

    filename = args.input
    # read the url 
    #url=" http://claritytrec.ucd.ie/~alawlor/comp30670/input_assign3.txt" 
    #data=urllib.request.urlopen(url).read()
    #buffer=data.decode('UTF-8')  
    
    buffer=read_file(filename=filename)
    content=buffer.splitlines()
    #print(content)
    '''catch the key number and words'''
    size= int(content[0])
    list1=listcreate(size)
    x1=0
    x2=0
    y1=0
    y2=0
    
    for line in content[1:]:
        value=line.split()
        #print(line)
        #print(value)
        number=re.findall("[-+]?\d+[\.]?\d*[eE]?[-+]?\d*", line)
        #print(re.findall("[-+]?\d+[\.]?\d*[eE]?[-+]?\d*", line))
    
        '''get the key number from file and assigned them to x1, x2, y1, y2'''    
        x1=int(number[0])
        y1=int(number[1])
        x2=int(number[2])
        y2=int(number[3])    
        '''get the key word of command and exctue the right funcion'''
                #print(value,x1,x2,y1,y2)
        if value[0]=='turn' and value[1]=='on':
            turnon(list1,x1,x2,y1,y2)
        elif value[0]=='turn' and value[1]=='off':
            turnoff(list1,x1,x2,y1,y2)
        elif value[0]=='switch':
            switch(list1,x1,x2,y1,y2)
        else:
            continue       

    result=countlight(list1)
    list2=[filename,result]
    return list2
Пример #31
0
def add(paths):
    """Adiciona os paths ao .git/index."""
    paths = [p.replace('\\', '/') for p in paths]
    all_entries = read_index()
    entries = [e for e in all_entries if e.path not in paths]
    for path in paths:
        sha1 = hash_object(read_file(path), 'blob')
        st = os.stat(path)
        flags = len(path.encode())
        assert flags < (1 << 12)
        entry = IndexEntry(int(st.st_ctime), 0, int(st.st_mtime), 0, st.st_dev,
                           st.st_ino, st.st_mode, st.st_uid, st.st_gid,
                           st.st_size, bytes.fromhex(sha1), flags, path)
        entries.append(entry)
    entries.sort(key=operator.attrgetter('path'))
    write_index(entries)
Пример #32
0
    def _remove_file_index(a_file):
        """Remove the information of the tracked a_file.

        Args:
            a_file: The tracked file.

        Returns:
            True/False: if a_file exist in the index file.

        """
        content_index = read_file(lgit_path + '/.lgit/index').split('\n')
        had_file = False
        for line in content_index:
            if line.endswith(a_file):
                # Remove the index of file:
                content_index.remove(line)
                had_file = True
        write_file(lgit_path + '/.lgit/index', '\n'.join(content_index))
        return had_file
Пример #33
0
def get_xml_elements(f_file_name, element_name):
    return parseString(f.read_file(f_file_name)).getElementsByTagName(element_name)
Пример #34
0
def get_used_space(top_directory):
  subprocess.call('du -c ' +top_directory+ '| grep total > du_tmp/used.du',shell=True)
  return int(fun.read_file('du_tmp/used.du','r').split('\t')[0])
Пример #35
0
 def test_reads_file_properly(self):
     expected = self.test_file_content
     self.assertEqual(expected, f.read_file(self.infile))
Пример #36
0
 def test_write_file_to_html(self):
     f.write_file_to_html(self.infile, '../', self.test_file_content)
     expected = self.test_file_content
     self.assertEqual(expected, f.read_file(self.infile))
Пример #37
0
def get_item_space(item):
  subprocess.call('du ' +item+ ' > du_tmp/item.du',shell=True)
  return int(fun.read_file('du_tmp/item.du','r').split('\t')[0])