예제 #1
0
    def loadDemoMessage(self,pathToMessage,latest):
        with open(pathToMessage,"r") as f:
            try:
                self.response=json.load(f)
                if self.response["ok"] is True and self.response["latest"] > latest:
                    archive=sorted(self.response["messages"],key=it("ts"))
                    userList=set([msg["user"] for msg in archive])
                    return archive
                    # for msg in archive:
                        # print msg["user"],msg["ts"],msg["text"]

            except:
                print "Unexpected error:",sys.exc_info()[4]
예제 #2
0
 def get_relaxed_solution(self, model): 
   vars_names = model.get_variables_names()
   list_of_vars = []  
   obj = model.get_objective_coefficients()
   dvars = {"$1":0, "$2":0}
   
   for ii in range(len(vars_names)):
     list_of_vars.append([vars_names[ii], 0, 0]) # name, weight, times
     dvars[vars_names[ii]] = ii
     
   G = nx.DiGraph(self._tree)
   for node in dfs_preorder_nodes(G, self._tree.get_root()):   
     m = self._tree.get_model_by_name(node)
     kvars, coeffs, krhs, w = AddOnsMPM().to_knapsack(m) # function, 4 - Sobj/Scon
     con_sum, obj_sum = 0, 0
     for i in range(len(kvars)):
       k = dvars[kvars[i]] # dvars - dictionary: key - index
       obj_sum += obj[i]
       con_sum += coeffs[i]
       list_of_vars[k][1] += krhs*obj[k]/coeffs[i] #w*krhs*obj[k]/coeffs[i]
       list_of_vars[k][2] += 1
     
   for v in list_of_vars:
     v[1] /= v[2] # making weights of shared_vars comparable to other vars
   list_of_vars.sort(key = it(1), reverse = True)
   
   res_list = []
   mm = len(list_of_vars)
   num_rows = model.get_num_rows()
   lhs = [0]*num_rows
   mtrx = model.get_rows_coefficients().toarray()
   fbool = False
   for jj in range(mm):
     for ii in range(num_rows):
       lhs[ii] += mtrx[ii][dvars[list_of_vars[jj][0]]]
       if lhs[ii] > model.get_rows_rhs()[ii]:
         fbool = True
         break
     if fbool:
       break
     res_list.append(list_of_vars[jj][0])
   return res_list
예제 #3
0
from collections import defaultdict

t = input()
for a0 in xrange(1, t + 1):
    n, l1, r1, A, B, C1, C2, M = map(int, raw_input().split())

    marks = [(l1, r1, 1, 'start'), (r1, l1, 1, 'end')]
    xprev, yprev = l1, r1
    for i in xrange(2, n + 1):
        x, y = (A * xprev + B * yprev + C1) % M, (A * yprev + B * xprev +
                                                  C2) % M
        marks.append((min(x, y), max(x, y), i, 'start'))
        marks.append((max(x, y), min(x, y), i, 'end'))
        xprev, yprev = x, y

    marks.sort(key=it(0))

    s = set([marks[0]])
    prev = marks[0]
    total_area = 0
    interval_area = defaultdict(int)

    for i in xrange(1, 2 * n):
        if len(s) > 0:
            area = 0
            if marks[i][3] == 'start' and prev[3] == 'start':
                area = marks[i][0] - prev[0]
            elif marks[i][3] == 'start' and prev[3] == 'end':
                area = marks[i][0] - prev[0] - 1
            elif marks[i][3] == 'end' and prev[3] == 'start':
                area = marks[i][0] - prev[0] + 1

def push(st, n):
    for i in xrange(1, n):
        st[2 * i] += st[i]
        st[2 * i + 1] += st[i]
        st[i] = 0


def f(x, y):
    return int(x), y


n = input()
arr = map(f, raw_input().split(), [i for i in xrange(n)])
arr.sort(key=it(0))
st = [0] * (2 * n)
for i in xrange(n):
    st[i + n] = arr[i][0]

m = input()
for a0 in xrange(m):
    val = input()
    index = bs(st, val, n)
    if index != n:
        modify(st, index, n - 1, -1, n)

push(st, n)

out = [0] * n
for i in xrange(n):
예제 #5
0
    for a1 in xrange(m):
        u, v = map(int, raw_input().split())
        edges.append((u, v))
        graph[u].add(v)
        graph[v].add(u)
    degree = [0] * (n + 1)
    # calculating degree
    for i in xrange(1, n + 1):
        degree[i] = len(graph[i])
    #print degree
    e_degree = [0] * m
    ec_degree = [0] * n

    for i in xrange(m):
        e_degree[i] = edges[i], min(degree[edges[i][0]], degree[edges[i][1]])
    e_degree.sort(key=it(1), reverse=True)
    #print e_degree
    parent = [i for i in xrange(n + 1)]
    rank = [1 for i in xrange(n + 1)]

    for edge in e_degree:
        if union(parent, rank, *edge[0]):
            ec_degree[edge[1]] += 1

    for i in xrange(1, n + 1):
        if rank[i] != 0:
            ec_degree[0] += 1

    ec_degree[0] -= 1
    #print ec_degree
    prefix_ec_degree = [0] * n
예제 #6
0

t = input()
for a0 in xrange(1, t + 1):
    #initialization
    n = input()
    old_n = n
    tree = defaultdict(dict)
    edges = []
    for a1 in xrange(n - 1):
        u, v, w = map(int, raw_input().split())
        tree[u][v] = w
        tree[v][u] = w
    #preprocessing
    occur = euler_tour(tree, edges, n)
    edges.sort(key=it(1))
    n = 2 * (n - 1)
    seg_tree = [0] * (2 * n)

    m = input()
    queries = []
    for a1 in xrange(1, m + 1):
        u, v, k = map(int, raw_input().split())
        queries.append((u, v, k, a1))
    queries.sort(key=it(2))
    #offline query answering
    answers = [0] * (m + 1)
    prev_p = -1
    for q in queries:
        u, v, k, a1 = q
        p = bs_floor(edges, -1, len(edges), k)
예제 #7
0
def dashboard_carrer():

    with open('.data/test.csv', 'rb') as f:
        result = chardet.detect(f.read())

    p_test = pd.read_csv(".data/test.csv", encoding=result['encoding'])
    #Encoding
    p_test = p_test.replace('Enjoy', 5)
    p_test = p_test.replace('Slightly Enjoy', 4)
    p_test = p_test.replace('Neutral', 3)
    p_test = p_test.replace('Slightly Disagree', 2)
    p_test = p_test.replace('Strongly Disagree', 1)

    #Realistic Questions
    realistic = p_test[[
        'I like to work on cars', 'I like to build things',
        'I like to take care of animals',
        'I like putting things together or assembling things',
        'I like to cook', 'I am a practical person', 'I like working outdoors'
    ]]
    #Investigative Questions
    investigative = p_test[[
        'I like to do puzzles', 'I like to do experiments', 'I enjoy science',
        'I enjoy trying to figure out how things work',
        'I like to analyze things (problems/situations)',
        'I like working with numbers  or charts', 'I am good at math'
    ]]
    #Artistic Questions
    artistic = p_test[[
        'I am good at working independently',
        'I like to read about art and music', 'I enjoy creative writing',
        'I am a creative person', 'I like to play instruments or sing',
        'I like acting in plays', 'I like to draw'
    ]]
    #Social Questions
    social = p_test[[
        'I like to work in teams', 'I like to teach or train people',
        'I like trying to help people solve their problems',
        'I am interested in healing people',
        'I enjoy learning about other cultures',
        'I like to get into discussions about issues around me',
        'I like helping people'
    ]]
    #Enterprising Questions
    enterprising = p_test[[
        'I am an ambitious person who set goals for myself',
        'I like to try to influence or persuade people',
        'I like selling things', 'I am quick to take on new responsibilities',
        'I would like to start my own business', 'I like to give speeches',
        'I like to lead'
    ]]
    #Conventional Questions
    conventional = p_test[[
        'I like to organize things',
        'I wouldn’t mind working 8 hours per day in an office',
        'I pay attention to details', 'I like to do filing or typing',
        'I am good at keeping records of my work',
        'I would like to work in an office'
    ]]

    #Summing Up
    realistic['R'] = realistic.sum(axis=1)
    investigative['I'] = investigative.sum(axis=1)
    artistic['A'] = artistic.sum(axis=1)
    social['S'] = social.sum(axis=1)
    enterprising['E'] = enterprising.sum(axis=1)
    conventional['C'] = conventional.sum(axis=1)

    code = realistic['R']
    code = code.to_frame()
    code['I'] = investigative['I']
    code['A'] = artistic['A']
    code['S'] = social['S']
    code['E'] = enterprising['E']
    code['C'] = conventional['C']

    n = 3

    new_d = [
        list(map(it(0),
                 (row[1:].sort_values(ascending=False)[:n].iteritems())))
        for _, row in code.iterrows()
    ]

    std = pd.DataFrame(new_d)

    std['code'] = std[0] + std[1] + std[2]

    #std has the test code
    std = std.drop([0, 1, 2], axis=1)

    #Read the course data
    course = pd.read_csv(".data/course.csv")

    df = pd.MultiIndex.from_product(
        [std["code"], course["course_code"], course["Course_short"]],
        names=["code", "course_code", "course"]).to_frame(index=False)

    df = df.dropna()

    #Cosine Similarity
    cosine = Cosine(2)
    df["p0"] = df["code"].apply(lambda s: cosine.get_profile(s))
    df["p1"] = df["course_code"].apply(lambda s: cosine.get_profile(s))
    df["cosine_sim"] = [
        cosine.similarity_profiles(p0, p1)
        for p0, p1 in zip(df["p0"], df["p1"])
    ]
    df.drop(["p0", "p1"], axis=1, inplace=True)

    #Sorting the Values
    top_n = df.sort_values(['cosine_sim'],
                           ascending=False).groupby(df['code'].values).head(3)

    options = top_n["course"].to_numpy()

    # selecting rows based on condition
    rec = course.loc[course['Course_short'].isin(options)]

    recommendations = json.loads(rec.to_json(orient='records'))

    return render_template('./dashboard_carrer.html',
                           title='Dashboard - Carrer',
                           std=std,
                           recommendations=recommendations)
예제 #8
0
def union(p, rank, x, y, w):
    root_x = root(p, x)
    root_y = root(p, y)
    if root_x != root_y:
        if rank[root_x] > rank[root_y]:
            p[root_y] = root_x
            rank[root_x] += rank[root_y]
        else:
            p[root_x] = root_y
            rank[root_y] += rank[root_x]
        return 1
    return 0


n, m = map(int, raw_input().split())

p = [i for i in xrange(n + 1)]
rank = [1 for i in xrange(n + 1)]
edges = []
for a0 in xrange(m):
    x, y, w = map(int, raw_input().split())
    edges.append((x, y, w))

edges.sort(key=it(2))
w = 0
for edge in edges:
    w += union(p, rank, *edge) * edge[2]

print w
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 20 21:01:22 2019

@author: BHASKAR NEOGI
"""
                 # Level - 3 *

from operator import itemgetter as it
p = []
print("Follow The Format : Name,Age,Height ; Make Each Option With Same Number of Values(ex : 03 for 3) :")
while True :
    
    s = input()
    if not s :
        break
    
    p.append(tuple(s.split(",")))
print ("Sorted In Order Name,Age,Height : ",'''
''',sorted(p,key = it(0,1,2)))

print('''
''',">->->->  Sorted By Name  <-<-<-< : ",'''
''',sorted(p,key = it(0)),'''
''',">->->->  Sorted By Age  <-<-<-< : ",'''
''',sorted(p,key = it(1)),'''
''',">->->->  Sorted By Height  <-<-<-< :",'''
''',sorted(p,key = it(2)))