Beispiel #1
0
    def post(self, request, *args, **kwargs):
        comment_service_helper = get_comment_helper(self.get_object().service)

        comment_service_helper.load_comments(self.get_object())
        if self.get_object().status == 'open':
            if self.get_object().get_api_data()['state'] == 'closed':
                issue = self.get_object()
                issue.status = 'in review'
                issue.save()
        if self.request.POST.get('take'):
            if self.request.user.is_authenticated():
                taker = Taker(issue=self.get_object(), user=self.request.user)
                taker.save()
                issue = self.get_object()
                issue.status = "taken"
                issue.save()
            else:
                return redirect('/accounts/login/?next=/issue/' +
                                str(self.get_object().id))
        if self.request.POST.get('solution'):
            if self.request.user.is_authenticated():
                solution = Solution(issue=self.get_object(),
                                    user=self.request.user,
                                    url=request.POST.get('solution'))
                solution.save()
                action.send(self.request.user,
                            verb='posted ',
                            action_object=solution,
                            target=self.get_object())

            else:
                return redirect('/accounts/login/?next=/issue/' +
                                str(self.get_object().id))

        return super(IssueDetailView, self).get(request, *args, **kwargs)
Beispiel #2
0
def resolve(size):
    solver = NQueensSolver(size)

    # calculate resolution time
    start_time = time.time()
    solver.run()
    end_time = time.time()

    # resolution time
    duration_seconds = end_time - start_time
    duration_milliseconds = duration_seconds * 1000
    duration_minutes = duration_milliseconds / 60000

    for solution in solver.get_all_solutions():
        print(solution)
        print(solver.get_board(solution))
        print()

        if Solution.findOne(size, solution) is None:
            Solution.createOne(size, solution)

    print("Board size : {}".format(size))
    print("Number of solutions: {}".format(solver.get_num_solutions()))
    print("Resolution time (milliseconds): {}".format(duration_milliseconds))
    print("Resolution time (seconds): {}".format(duration_seconds))
    print("Resolution time (minutes): {}".format(duration_minutes))
Beispiel #3
0
def generateNewRandSol(observationList, apList):

	# LDone = []
	# for obs in observationList:
	# 	if obs.gpsGranted:
	# 		LDone.append(obs)
	# CDone = []
	# O = []
	# if len(LDone) >= 5:
	# 	base = 5
	# else:
	# 	base = len(LDone)

	# l = base
	# ERSGA(LDone, CDone, O, l, base, observationList, apList)
	for ap in apList:
		ap.loss, ap.pi0, ap.latitude, ap.longitude = getRandAPParam()

	for obs in observationList:
		obs.latitude, obs.longitude = getRandObservationCoordinates()
		for apFingerprint in obs.apFingerprintList:
			for ap in apList:
				if apFingerprint.ap.name == ap.name:
					apFingerprint.ap = ap
					break

	return Solution(computeJEZ(copy.deepcopy(observationList)), copy.deepcopy(observationList), copy.deepcopy(apList))
Beispiel #4
0
def add():
    user = g.user
    factories = DepartmentType.query.all()
    if request.method != 'POST':
        return render_template('admin/addsolution.html',
                               title='Add Solution',
                               factories=factories,
                               user=user)

    p_factory_id = request.form.get('select_factory', None)
    #print p_factory_id
    if not int(p_factory_id):
        flash(u'请选择设备供应商')
        return render_template('admin/addsolution.html',
                               title='Add Solution',
                               factories=factories,
                               user=user)
    p_troublename = request.form.get('p_troublename', None)
    p_solution = request.form.get('p_solution', None)
    if p_troublename == 'describe trouble' or p_solution == 'make solution':
        flash(u'请输入有效内容')
    solution_obj = Solution(troublename=p_troublename,
                            solution=p_solution,
                            type_id=p_factory_id)
    db.session.add(solution_obj)
    db.session.commit()
    flash(u'添加成功')
    return render_template('admin/addsolution.html',
                           title='Add Solution',
                           factories=factories,
                           user=user)
 def post(self):
     """The POST handler for the /caesar endpoint
 
 Returns:
     dict -- A dict containing the result and the detected language
 """
     args = parser.parse_args()
     try:
         cipher = args['cipher']
         solution = Solution.query.filter_by(cipher=cipher).first()
         if solution:
             return {
                 'result': solution.solution,
                 'lang': solution.lang,
                 'cached': True
             }
         current_user = this_user()
         deciphered, language = decrypt(cipher, args['lang'])
         new_solution = Solution(cipher, language, deciphered,
                                 current_user['id'], current_user['org_id'])
         db.session.add(new_solution)
         db.session.commit()
         return {'result': deciphered, 'lang': language}
     except Exception as e:
         traceback.print_exc()
         return generic_400(str(e))
Beispiel #6
0
 def save(self, solution):
     session = create_session()
     new = Solution(nqueen=self.size, solution=str(solution))
     session.add(new)
     try:
         session.commit()
     except Exception as e:
         print("Commiting the solution: {}".format(e))
         session.rollback()
     session.close()
Beispiel #7
0
def initialize(size_of_population):
    population = []

    for x in range(size_of_population):
        random_solution = tools.generate_TSP_solution()
        random_strategy = random.choice(tools.KNP_greedy_strategies)
        #t_cost = tools.get_travel_cost(random_solution,random_strategy)

        population.append(Solution(random_solution, random_strategy ))
    return population
Beispiel #8
0
def user_profile(username):
    solutions_by_user = Solution.select().where(Solution.username == username)
    user_info = org_github.get(f"/users/{username}")
    user_status = "Student"
    if org_github.is_member(username):
        user_status = "Mentor"

    print(user_info)
    return render_template("profile.html", user=username,
                           solutions=solutions_by_user,
                           user_info=user_info, user_status=user_status)
Beispiel #9
0
    def post(self, request, *args, **kwargs):
        comment_service_helper = get_comment_helper(self.get_object().service)

        comment_service_helper.load_comments(self.get_object())
        if self.get_object().status in ('open', 'in review'):
            if self.get_object().get_api_data()['state'] == 'closed':
                issue = self.get_object()
                if Solution.objects.filter(issue=issue):
                    # process the payment here and mark it as paid if the solution was accepted
                    issue.status = 'in review'
                else:
                    issue.status = 'closed'
                issue.save()
        if self.request.POST.get('take'):
            if self.request.user.is_authenticated():
                taker = Taker(issue=self.get_object(), user=self.request.user)
                taker.save()
                issue = self.get_object()
                issue.status = "taken"
                issue.save()
                #"yippie kay yay - someone took your coderbounty issue #1234 - they will have 4 hours before "
            else:
                return redirect('/accounts/login/?next=/issue/' +
                                str(self.get_object().id))
        if self.request.POST.get('solution'):
            if self.request.user.is_authenticated():
                solution = Solution(issue=self.get_object(),
                                    user=self.request.user,
                                    url=request.POST.get('solution'))
                solution.save()
                action.send(self.request.user,
                            verb='posted ',
                            action_object=solution,
                            target=self.get_object())

            else:
                return redirect('/accounts/login/?next=/issue/' +
                                str(self.get_object().id))

        return super(IssueDetailView, self).get(request, *args, **kwargs)
Beispiel #10
0
def webhook():
    request_json = request.get_json()
    f = open("webhook.json", "w")
    json.dump(request_json, f)
    f.close()

    action = request_json.get("action")
    if action == "closed":
        issue = request_json.get("issue")
        pull_request = request_json.get("pull_request")
        if issue:
            user = issue["user"]
            _username = user["login"]

            repo_link = issue["title"]
            username, repo = get_username_and_repo(repo_link)

            if _username == ADMIN:
                comments_url = issue["comments_url"]
                comments = get_comments(comments_url, usernames=[ADMIN],
                                        body=["ACCEPTED!", "REJECTED!"])

                for comment in comments:
                    if comment.body == "ACCEPTED!":
                        org_github.create_fork(username, repo)
                        break
                    elif comment.body == "REJECTED!":
                        break
        elif pull_request:
            labels = pull_request["labels"]
            for label in labels:
                if label["name"] == "solution":
                    head_url = pull_request["head"]["repo"]["html_url"]
                    username, repo = get_username_and_repo(head_url)
                    head_sha = pull_request["head"]["sha"]
                    _url = reduce(urljoin, [f"{head_url}/", "tree/", head_sha])
                    Solution.create(url=_url, username=username)

    return ""
Beispiel #11
0
    def test_Solution(self):
        """Test the top-level Solution object, which holds the data and reports on it.
        """
        s = Solution()

        assert type(s) == Solution, "Solution is a Solution"

        for zmetho in [
                'add_data', 'report_amount_settled_every_day',
                'report_rank_entities'
        ]:
            assert getattr(s, zmetho, None) is not None, \
                "Solution has the {} attribute/method".format(zmetho)
Beispiel #12
0
    def post(self, request, *args, **kwargs):
        comment_service_helper = get_comment_helper(self.get_object().service)

        comment_service_helper.load_comments(self.get_object())
        if self.get_object().status in ('open', 'in review'):
            if self.get_object().get_api_data()['state'] == 'closed':
                issue = self.get_object()
                if Solution.objects.filter(issue=issue):
                    # process the payment here and mark it as paid if the solution was accepted
                    issue.status = 'in review'
                else:
                    issue.status = 'closed'
                issue.save()
        if self.request.POST.get('take'):
            if self.request.user.is_authenticated():
                taker = Taker(issue=self.get_object(), user=self.request.user)
                taker.save()
                issue = self.get_object()
                issue.status = "taken"
                issue.save()
                #"yippie kay yay - someone took your coderbounty issue #1234 - they will have 4 hours before "
            else:
                return redirect('/accounts/login/?next=/issue/' + str(self.get_object().id))
        if self.request.POST.get('solution'):
            if self.request.user.is_authenticated():
                solution = Solution(
                    issue=self.get_object(),
                    user=self.request.user,
                    url=request.POST.get('solution'))
                solution.save()
                action.send(self.request.user, verb='posted ', action_object=solution, target=self.get_object())

            else:
                return redirect('/accounts/login/?next=/issue/' + str(self.get_object().id))

        return super(IssueDetailView, self).get(request, *args, **kwargs)
Beispiel #13
0
def submit():
    """
    Action for solution submit
    """
    if request.method == 'POST':
        from models import Solution
        from lib.database import db_session
        file = request.files['file']
        if not file:
            return redirect(request.referrer)

        lang_id = get_lang_id(file.filename)
        if lang_id:
            # Create solution in database
            team_id = session['team_id']
            problem_id = request.form['problem_id']
            solution = Solution(problem_id, team_id, lang_id)
            db_session.add(solution)
            db_session.commit()

            # Store solution file
            path = solution.get_solution_path()
            solution_file = solution.get_solution_file()
            if not os.path.exists(path):
                os.makedirs(path)
            file.save(solution_file)


            tester_module = import_module('lib.testers.{tester_name}'.format(tester_name = solution.language.tester_name))
            tester = tester_module.Tester(solution, tester_semaphore)
            tester.start()

        else:
            flash(u'Неверное расширение файла!', 'alert-error')
            return redirect(request.referrer)
    return redirect(url_for('status'))
Beispiel #14
0
def search(query):
    result = "["
    solutions_by_user = Solution.select().where(Solution.username.contains(query))
    mentors = Mentor.select().where(
        (Mentor.username.contains(query)) &
        (Mentor.status == "accepted"))
    for solution in solutions_by_user:
        result += "{" + f"'solution_url': '{solution.url}'," \
            f"'username': '******'" + "}"

    for mentor in mentors:
        result += "{" + f"'username': '******'," \
            f"'profile_url': '{mentor.profile_link}'" + "}"
    result += "]"
    return json.dumps(result)
Beispiel #15
0
def add():
    data = request.get_json()
    n = data['n']
    # use nQueens function to produce list of solution boards based on input value for n
    # After its already been run once, nQueens does not run with an empty array for results unless specified here at calltime
    results = nQueens(int(n), [], [])
    # gather amount of solutions generated for this value of n
    total = len(results)
    # for each board(list) in results list, add it as a new entry (instance of Solution class from models) into db,
    # with its corresponding n and total amount of solutions for that n
    for result in results:
        entry = Solution(board=str(result), n=n, total=total)
        db.session.add(entry)
    # commit all additions to db
    db.session.commit()
    return json.dumps("Solutions Added"), 200
Beispiel #16
0
def main():
    """Process the data provided on standard input and print reports of
    the results to standard output.
    """

    sol = Solution()
    sol.add_data(stdin)

    print("=========================================================")
    print(sol.report_amount_settled_every_day())
    print("=========================================================")
    print(sol.report_rank_entities('incoming'))
    print("=========================================================")
    print(sol.report_rank_entities('outgoing'))
Beispiel #17
0
def refill(solution_ranking,size_of_population):
    solution_ranking.reset_index(drop=True, inplace=True)
    solutions = []
    score_list = []

    while ( solution_ranking.__len__() + solutions.__len__()  <  size_of_population):  # generating solutions till num of pop

        child_route = tools.generate_TSP_solution()
        random_strategy = random.choice(tools.KNP_greedy_strategies)
        solution = Solution( child_route, random_strategy)
        solutions.append(solution)
        score_list.append(0)  # eval later on

    new_solutions = pd.DataFrame()
    new_solutions['solutions'] = solutions
    new_solutions['score'] = score_list
    new_solutions.index = np.arange(solution_ranking.__len__(),solution_ranking.__len__() + new_solutions.__len__())  # reindexing new solutions


    return (pd.concat([solution_ranking,new_solutions])).reset_index(drop=True)
Beispiel #18
0
def run(nr_of_objects, default_sack, weight_limit, given_runtimes):

    solutions = []
    while given_runtimes:
        random_solution = randint(0, 2**nr_of_objects)
        binary = '{0:b}'.format(random_solution)
        binary_solution = (default_sack.nr_of_objects -
                           len(binary)) * '0' + binary
        weight = 0
        quality = 0

        for obj_index in range(default_sack.nr_of_objects):
            if binary_solution[obj_index] == '1':
                weight += default_sack.list_of_objects[obj_index].weight
                quality += default_sack.list_of_objects[obj_index].value

        if weight <= weight_limit:
            given_runtimes -= 1
            solutions.append(Solution(binary_solution, weight, quality))
            print(binary_solution, weight, quality)

    return solutions
Beispiel #19
0
def solve(board, col, size, solutions, store=False, dbsession=None):
    """
    Implements backtrack to search all the possible solutions
    - we put a queen first corner 
    - then we start to place queen in 
    the follow rows in such a way they don't attack each other 
    - if N queens have been placed stores the solution
    then we remove the queen from the previous step and try to increment the row of the queen in the column before
    - if the queen can't be placed increment the row of the queen in the previous column
    - continue until we are in row N
    
    
    
    Arguments:
        board {[type]} -- [description]
        col {[type]} -- [description]
        size {[type]} -- [description]
        solutions {[type]} -- [description]
    """
    # we finished
    if col >= size:
        return

    for i in range(size):
        if check_tile(board, i, col, size):
            #a queen could be placed
            board[i][col] = 1
            if col == size - 1:
                #we found a solution
                if (store):
                    dbsession.add(Solution(n=size, result=board))
                solutions.append(copy.deepcopy(board))
                board[i][col] = 0
                return
            #backtrack step
            solve(board, col + 1, size, solutions)
            board[i][col] = 0
    if (store):
        dbsession.commit()
Beispiel #20
0
def store_solutions(size, solutions):

    Base.metadata.create_all(engine)
    session = Session()
    n_queen = size

    try:

        for solution in solutions:

            queen_positions = Solution(n_queen, solution)
            session.add(queen_positions)
            session.commit()

        print('Queen number {} solutions added to database.'.format(n_queen))

    except exc.IntegrityError as e:

        session.rollback()
        print('Queen number {} solutions already exists in database.'.format(
            n_queen))

    session.close()
Beispiel #21
0
def crossing_over(solution_ranking, percenate_of_cross):
    solution_ranking.reset_index(drop=True,inplace=True)

    solutions_to_cross = list(solution_ranking.index.values)

    for parent_index_1 in solutions_to_cross:
        if(random.random() < percenate_of_cross):
            parent_index_2 = tools.getDiff( parent_index_1, solution_ranking.__len__() - 1)

            child_route = tools.crossover_new_route(solution_ranking['solutions'][parent_index_1].route,solution_ranking['solutions'][parent_index_2].route)
            random_strategy = random.choice([solution_ranking['solutions'][parent_index_1].strategy,solution_ranking['solutions'][parent_index_2].strategy])

            solution_ranking['score'][parent_index_1] = 0
            solution_ranking['solutions'][parent_index_1] = Solution(child_route, random_strategy)

    '''
    solution_ranking.drop(solutions_to_cross,inplace=True)                                                              #remove parents

    new_solutions = pd.DataFrame()
    new_solutions['solutions'] = solutions_children
    new_solutions['score'] = score_list
    new_solutions.index = np.arange(solution_ranking.__len__(), solution_ranking.__len__() +new_solutions.__len__())    #reindexing new solutions
    '''
    return solution_ranking                                                                  #return merged old and new solutions
Beispiel #22
0
            aIndex = aIndex + 2
            obsIndex = obsIndex + 1
            for fingerprint in obs.apFingerprintList:
                for newAp in combinedApList:
                    if fingerprint.ap.name == newAp.name:
                        fingerprint.ap = newAp
                        break
            combinedObsList.append(
                DeviceObservation(obs.timestamp, copy.deepcopy(newLatitude),
                                  copy.deepcopy(newLongitude), obs.gpsGranted,
                                  copy.deepcopy(obs.apFingerprintList)))

        newSolutionObsList = copy.deepcopy(combinedObsList)
        newSolutionApList = copy.deepcopy(combinedApList)
        combinedSolList.append(
            Solution(computeJEZ(newSolutionObsList), newSolutionObsList,
                     newSolutionApList))

    combinedSolList = copy.deepcopy(
        gradientDescent(copy.deepcopy(combinedSolList)))
    newSolutions = newSolutions + combinedSolList

    combinedSolList = []
    for i in xrange(0, int(TWENTY_PERCENT * SOLUTIONS_PER_GENERATION)):
        SRand = copy.deepcopy(random.choice(oldSolutions))

        SApList = copy.deepcopy(SRand.getApList())
        SObsList = copy.deepcopy(SRand.getObservationList())

        randApList = []
        for ap in SApList:
            randApList.append(
Beispiel #23
0
def add_solution(task_id):
    description = request.form['description']
    solution = Solution(task_id=task_id, description=description)
    db.session.add(solution)
    db.session.commit()
    return redirect('/tasks/{}'.format(task_id))
Beispiel #24
0
    def post(self, request, *args, **kwargs):
        comment_service_helper = get_comment_helper(self.get_object().service)

        comment_service_helper.load_comments(self.get_object())
        if self.get_object().status in ('open', 'in review'):
            if self.get_object().get_api_data()['state'] == 'closed':
                issue = self.get_object()
                if Solution.objects.filter(issue=issue):
                    # process the payment here and mark it as paid if the solution was accepted
                    issue.status = 'in review'
                else:
                    issue.status = 'closed'
                issue.save()
        if self.request.POST.get('take'):
            if self.request.user.is_authenticated():
                taker = Taker(issue=self.get_object(), user=self.request.user)
                taker.save()
                issue = self.get_object()
                issue.status = "taken"
                issue.save()
                action.send(self.request.user,
                            verb='has taken ',
                            target=self.get_object())
                msg_plain = render_to_string(
                    'email/issue_taken.txt', {
                        'user': self.request.user,
                        'issue': self.get_object(),
                        'time_remaining': taker.time_remaining
                    })
                msg_html = render_to_string(
                    'email/issue_taken.txt', {
                        'user': self.request.user,
                        'issue': self.get_object(),
                        'time_remaining': taker.time_remaining
                    })

                send_mail(
                    'You have taken issue: ' + self.get_object().project +
                    " issue #" + str(self.get_object().number),
                    msg_plain,
                    '*****@*****.**',
                    [self.request.user.email],
                    html_message=msg_html,
                )
            else:
                return redirect('/accounts/login/?next=/issue/' +
                                str(self.get_object().id))
        if self.request.POST.get('solution'):
            if self.get_object().status not in ('closed', 'in review'):

                if self.request.user.is_authenticated():
                    solution = Solution(issue=self.get_object(),
                                        user=self.request.user,
                                        url=request.POST.get('solution'))
                    solution.save()
                    issue = self.get_object()
                    issue.status = "in review"
                    issue.save()
                    action.send(self.request.user,
                                verb='posted ',
                                action_object=solution,
                                target=self.get_object())

                    bounty_poster = Bounty.objects.filter(
                        issue=self.get_object())[:1].get()

                    msg_plain = render_to_string('email/solution_posted.txt', {
                        'user': bounty_poster.user,
                        'issue': self.get_object()
                    })
                    msg_html = render_to_string('email/solution_posted.txt', {
                        'user': bounty_poster.user,
                        'issue': self.get_object()
                    })

                    send_mail(
                        'Coderbounty solution posted on ' +
                        self.get_object().project + " issue #" +
                        str(self.get_object().number),
                        msg_plain,
                        '*****@*****.**',
                        [bounty_poster.user.email],
                        html_message=msg_html,
                    )

                else:
                    return redirect('/accounts/login/?next=/issue/' +
                                    str(self.get_object().id))

        return super(IssueDetailView, self).get(request, *args, **kwargs)
Beispiel #25
0
    def post(self, request, *args, **kwargs):
        comment_service_helper = get_comment_helper(self.get_object().service)

        comment_service_helper.load_comments(self.get_object())
        if self.get_object().status in ("open", "in review"):
            if self.get_object().get_api_data()["state"] == "closed":
                issue = self.get_object()
                if Solution.objects.filter(issue=issue):
                    # process the payment here and mark it as paid if the solution was accepted
                    issue.status = "in review"
                else:
                    issue.status = "closed"
                issue.save()
        if self.request.POST.get("take"):
            if self.request.user.is_authenticated():
                taker = Taker(issue=self.get_object(), user=self.request.user)
                taker.save()
                issue = self.get_object()
                issue.status = "taken"
                issue.save()
                action.send(self.request.user, verb="has taken ", target=self.get_object())
                msg_plain = render_to_string(
                    "email/issue_taken.txt",
                    {"user": self.request.user, "issue": self.get_object(), "time_remaining": taker.time_remaining},
                )
                msg_html = render_to_string(
                    "email/issue_taken.txt",
                    {"user": self.request.user, "issue": self.get_object(), "time_remaining": taker.time_remaining},
                )

                send_mail(
                    "You have taken issue: " + self.get_object().project + " issue #" + str(self.get_object().number),
                    msg_plain,
                    "*****@*****.**",
                    [self.request.user.email],
                    html_message=msg_html,
                )
            else:
                return redirect("/accounts/login/?next=/issue/" + str(self.get_object().id))
        if self.request.POST.get("solution"):
            if self.get_object().status not in ("closed", "in review"):

                if self.request.user.is_authenticated():
                    solution = Solution(
                        issue=self.get_object(), user=self.request.user, url=request.POST.get("solution")
                    )
                    solution.save()
                    issue = self.get_object()
                    issue.status = "in review"
                    issue.save()
                    action.send(self.request.user, verb="posted ", action_object=solution, target=self.get_object())

                    bounty_poster = Bounty.objects.filter(issue=self.get_object())[:1].get()

                    msg_plain = render_to_string(
                        "email/solution_posted.txt", {"user": bounty_poster.user, "issue": self.get_object()}
                    )
                    msg_html = render_to_string(
                        "email/solution_posted.txt", {"user": bounty_poster.user, "issue": self.get_object()}
                    )

                    send_mail(
                        "Coderbounty solution posted on "
                        + self.get_object().project
                        + " issue #"
                        + str(self.get_object().number),
                        msg_plain,
                        "*****@*****.**",
                        [bounty_poster.user.email],
                        html_message=msg_html,
                    )

                else:
                    return redirect("/accounts/login/?next=/issue/" + str(self.get_object().id))

        return super(IssueDetailView, self).get(request, *args, **kwargs)
Beispiel #26
0
def main_algorithm(problem):
    logger = logging.getLogger('main_logger')

    logger.critical('Problem %i' % problem.question_number)
    # pb = problems[no]

    graph = Graph(problem)
    graph.sort_edges()
    solution_edges = set()

    logger.info('Generating Dijkstra Routes')
    pb_robots = copy.deepcopy(problem.robots)
    sol_robots = list()
    print(len(pb_robots))
    # Special for the first robot
    r_f = pb_robots.pop(0)
    r_f.awaken = True

    pb_robots = sorted(
        pb_robots,
        key=lambda robot: Edge(r_f.vertices, robot.vertices, None).weight)
    v = list()

    v.append(pb_robots[0].vertices)
    edges = dijkstra_path(v_1=r_f.vertices,
                          v_2=pb_robots[0].vertices,
                          vertices=graph.vertices,
                          edges=graph.edges)
    r_f.track.extend(edges)
    sol_robots.append(r_f)

    solution_edges = solution_edges.union(set(edges))
    r_p = r_f  # Previous Robot
    pb_robots[0].awaken = True
    awake = 2
    while len(pb_robots) > 0:
        logger.info('Generating Dijkstra, remaining: %i' % len(pb_robots))
        r_i = pb_robots.pop(0)

        dist, prev = find_path(v_1=r_i.vertices,
                               vertices=graph.vertices,
                               edges=graph.edges)

        pb_robots = sorted(pb_robots, key=lambda robot: dist[robot.vertices])

        robots = list()
        # Select Destination robots that have not been reached. They should not be a destination.
        for i in range(0, len(pb_robots)):
            if pb_robots[i].awaken:
                continue
            robots.append(pb_robots[i])

            if len(robots) is 2:
                break

        for r in robots:
            edges = set(
                dijkstra_path(r_i.vertices, r.vertices, graph.vertices,
                              graph.edges, dist,
                              prev))  # Generated by Dijkstra

            found = False
            for edge in edges:

                for sol_edge in solution_edges:

                    if edge.start == sol_edge.start and edge.end == sol_edge.end:
                        found = True
                        break

                    if edge.start == sol_edge.end and edge.end == sol_edge.start:
                        found = True
                        break

            if found:
                r.awaken = False
                continue

            if r_i not in sol_robots:
                sol_robots.append(r_i)
                r_i.track.extend(edges)

            else:  # Second Path
                r_p.track.extend(edges)

            solution_edges = solution_edges.union(edges)
            r.awaken = True
            awake += 1

        r_p = r_i  # Previous Robot

    # logger.info('Generating Dijkstra Routes Complete')
    # logger.info('Visualizing the solution')

    for robot in sol_robots:
        robot.sort_track()
        # print("Robot: %s" % (robot.vertices,))
        # for t in robot.track:
        #     print('%s -> %s' % (t.start, t.end))

    solution = Solution(question_number=problem.question_number,
                        robots=sol_robots)
    logger.critical('Finished Writing Solution for %i')

    logger.info('%i Robots Awake' % awake)
    writer.write_solution([solution])
    print(solution.list_of_coordinates)
    # Visualize is using process (non blocking)
    Process(target=visualization.draw(
        problem, mst_edges=list(solution_edges), edges=graph.edges)).start()
Beispiel #27
0
def multiprocessingGradientDescent(solution):
    global newSolutionList

    newObservationList = []
    newApList = []

    for observation in solution.observationList:
        xobsLat = obsLat = observation.latitude
        xobsLong = obsLong = observation.longitude

        newAPFingerprintList = []
        for apFingerprint in observation.apFingerprintList:
            apExists = False
            for ap in newApList:
                if ap.name == apFingerprint.ap.name:
                    apExists = True
                    break
            if not apExists:
                newApList.append(apFingerprint.ap)

            Pij = apFingerprint.Pij
            xPi0 = Pi0 = apFingerprint.ap.Pi0
            xloss = loss = apFingerprint.ap.loss
            xapLat = apLat = apFingerprint.ap.latitude
            xapLong = apLong = apFingerprint.ap.longitude
            while True:
                g = (xPi0 - 10 * xloss * log(
                    sqrt((-xapLat + xobsLat)**2 +
                         (-xapLong + xobsLong)**2)) / log(10) - Pij) * sqrt(
                             (-xPi0 + 10 * xloss * log(
                                 sqrt((-xapLat + xobsLat)**2 +
                                      (-xapLong + xobsLong)**2)) / log(10) +
                              Pij)**2) / (-xPi0 + 10 * xloss * log(
                                  sqrt((-xapLat + xobsLat)**2 +
                                       (-xapLong + xobsLong)**2)) / log(10) +
                                          Pij)**2
                Pi0 = Pi0 - alpha * g
                s = g * g

                g = 10 * sqrt((-xPi0 + 10 * xloss * log(
                    sqrt((-xapLat + xobsLat)**2 +
                         (-xapLong + xobsLong)**2)) / log(10) + Pij)**2) * log(
                             sqrt((-xapLat + xobsLat)**2 +
                                  (-xapLong + xobsLong)**2)) / (
                                      (-xPi0 + 10 * xloss * log(
                                          sqrt((-xapLat + xobsLat)**2 +
                                               (-xapLong + xobsLong)**2)) /
                                       log(10) + Pij) * log(10))
                loss = loss - alpha * g
                s = s + g * g

                g = 10 * xloss * (-xapLat + xobsLat) * sqrt(
                    (-xPi0 + 10 * xloss * log(
                        sqrt((-xapLat + xobsLat)**2 +
                             (-xapLong + xobsLong)**2)) / log(10) + Pij)**
                    2) / (
                        ((-xapLat + xobsLat)**2 +
                         (-xapLong + xobsLong)**2) * (-xPi0 + 10 * xloss * log(
                             sqrt((-xapLat + xobsLat)**2 +
                                  (-xapLong + xobsLong)**2)) / log(10) + Pij) *
                        log(10))
                apLat = apLat - alpha * g
                s = s + g * g

                g = 10 * xloss * (-xapLong + xobsLong) * sqrt(
                    (-xPi0 + 10 * xloss * log(
                        sqrt((-xapLat + xobsLat)**2 +
                             (-xapLong + xobsLong)**2)) / log(10) + Pij)**
                    2) / (
                        ((-xapLat + xobsLat)**2 +
                         (-xapLong + xobsLong)**2) * (-xPi0 + 10 * xloss * log(
                             sqrt((-xapLat + xobsLat)**2 +
                                  (-xapLong + xobsLong)**2)) / log(10) + Pij) *
                        log(10))
                apLong = apLong - alpha * g
                s = s + g * g

                if not observation.gpsGranted:
                    g = 10 * xloss * (xapLat - xobsLat) * sqrt(
                        (-xPi0 + 10 * xloss * log(
                            sqrt((-xapLat + xobsLat)**2 +
                                 (-xapLong + xobsLong)**2)) / log(10) + Pij)**
                        2) / (((-xapLat + xobsLat)**2 +
                               (-xapLong + xobsLong)**2) *
                              (-xPi0 + 10 * xloss * log(
                                  sqrt((-xapLat + xobsLat)**2 +
                                       (-xapLong + xobsLong)**2)) / log(10) +
                               Pij) * log(10))
                    obsLat = obsLat - alpha * g
                    s = s + g * g

                    g = 10 * xloss * (xapLong - xobsLong) * sqrt(
                        (-xPi0 + 10 * xloss * log(
                            sqrt((-xapLat + xobsLat)**2 +
                                 (-xapLong + xobsLong)**2)) / log(10) + Pij)**
                        2) / (((-xapLat + xobsLat)**2 +
                               (-xapLong + xobsLong)**2) *
                              (-xPi0 + 10 * xloss * log(
                                  sqrt((-xapLat + xobsLat)**2 +
                                       (-xapLong + xobsLong)**2)) / log(10) +
                               Pij) * log(10))
                    obsLong = obsLong - alpha * g
                    s = s + g * g

                norm = sqrt(s)
                if alpha * norm <= epsilon:
                    break

                xPi0 = Pi0
                xloss = loss
                xapLat = apLat
                xapLong = apLong
                xobsLat = obsLat
                xobsLong = obsLong

            # apFingerprint.ap.Pi0 = Pi0
            # apFingerprint.ap.loss = loss
            # apFingerprint.ap.latitude = apLat
            # apFingerprint.ap.longitude = apLong

            newAPFingerprintList.append(
                APFingerprint(
                    AccessPoint(apFingerprint.ap.name, loss, Pi0, apLat,
                                apLong, apFingerprint.ap.numberOfObservations),
                    Pij))

        newObservationList.append(
            DeviceObservation(observation.timestamp, obsLat, obsLong,
                              observation.gpsGranted, newAPFingerprintList))

    newSolutionList.append(
        Solution(computeJEZ(copy.deepcopy(newObservationList)),
                 copy.deepcopy(newObservationList), copy.deepcopy(newApList)))
Beispiel #28
0
 def post(self, request, *args, **kwargs):
     solution = Solution()
     solution.user = UserProfile.objects.get(id=request.user.id);
     solution.problem = Problem.objects.get(id=request.POST.get("problem"))
     solution.language = Language.objects.get(id=request.POST.get("language"))
     solution.contest = request.POST.get("contest")
     solution.source_code = request.POST.get("source_code")
     solution.result = 0;
     solution.judger = None
     solution.save()
     return HttpResponseRedirect("/soultion/")