Exemplo n.º 1
0
    def api_batch_profile(self):
        res = dict(profiles={})
        # print self.request.arguments, type(self.request.arguments)

        def clb(dic):
            # print dic
            res["profiles"][dic["user"]] = dic

        arguments = tornado.escape.json_decode(self.get_argument("data"))
        for agent in arguments:

            if not db.user_exists(agent):
                print "*** user does not exist:", agent
                continue

            if self.request.method == "GET":
                p = profile(agent, [], self.request.path.split("/"), db.r, clb)
                p.get("")

            if self.request.method == "POST":
                p = profile(agent, arguments[agent].items(), db.r, clb)
                # print 'arguments', arguments[agent].items()
                p.post()

        self.finilize_call(res)
Exemplo n.º 2
0
def main():
    args = _parse_command_line_args()
    print(args)
    if args.mode == 'profile':
        profile.profile()
    else:
        test.test()
Exemplo n.º 3
0
def main(dex):
	#ret = opaque_id("/mnt/test/01_ControlFlow/01_High/sanity_cf.apk")
    ret = opaque_id.opaque_id(dex)
        
    if not ret :
        return
    profile(".stdout")
    ret = opaque_location.opaque_locations(dex)
    print("location : " + str(ret))  
#    if not ret :
#        return
    dexfile(dex)
Exemplo n.º 4
0
def main(dex):
    '''
    Entry Point of deobfuscator
    [dex] : APK's path
    '''
    ret = opaque_id.opaque_id(dex)

    if not ret :
        return

    profile(".stdout")
    ret = opaque_location.opaque_locations(dex)
    print("location : " + str(ret))  

    dexfile(dex)
Exemplo n.º 5
0
    def generate_masks_voronoi(self):
        with profile():
            print 'generate_masks_voronoi'

            centers = [
                c_hom(close.center())
                for c_hom, close in zip(self.c_homs, self.closes)
            ]
            self.c_voronoi_facets = voronoi(centers, self.establishing.system,
                                            self.establishing.dims)

            mask_template = (self.establishing.resize(
                scale=self.canvas_scale).pipe(lambda x: np.zeros(x.shape[:2])))
            homography_masks = [
                mask_template.fill_poly(clip(map(c_hom, close.corners()),
                                             mask_template.corners()),
                                        color=1).erode(3)
                for c_hom, close in zip(self.c_homs, self.closes)
            ]
            self.c_masks = [
                operate(
                    lambda x, y: x * y,
                    mask_template.fill_poly(clip(facet,
                                                 mask_template.corners()),
                                            color=1),
                    homography_mask) for facet, homography_mask in zip(
                        self.c_voronoi_facets, homography_masks)
            ]
Exemplo n.º 6
0
    def __init__(self,  filename=None, buffer=None, store_plaintext=False, 
            features=None, feature_overrides=None, algorithms=None):
        """Primary class for all hashing and profiling modules.

        Keyword Arguments:
        filename -- Filename to evaluate. If buffer is not defined, this will open the file,
            otherwise it will use this value when building the profile
        buffer -- Contents to evaluate. 
        store_plaintext -- Whether or not the plaintext should be included in the resulting output,
            this is useful for storing the content in a database. 
        features -- List of features to use, None for all. 
        feature_overrides -- Dictionary containing features and values to override the output of the module
        algorithms -- List of algorithms to use, None for all. 
        """
        self.buffer = buffer

        if filename and self.buffer is None:
            statinfo = os.stat(filename)
            size = statinfo.st_size

            with open(filename, 'rb') as f:
                self.buffer = f.read()

            if size >= MAX_SIZE:
                self.store_plaintext = False

        p = profile(filename=filename, buffer=self.buffer, store_plaintext=store_plaintext,
                modules=features, overrides=feature_overrides)
                
        self.result = p.profile.copy()

        h = hashes(buffer=self.buffer, modules=algorithms)
        self.result.update(h.__dict__)
Exemplo n.º 7
0
    def detail_transfer_stitch_pt_2(self, detail_transfer_blur_op,
                                    edge_blend_radius):
        with profile():
            print 'detail_transfer_stitch_pt_2'

            canvas = (self.establishing.white_balance().normalize().resize(
                scale=self.canvas_scale))
            images, full_masks, full_masks_blurred = zip(
                *self.detail_transfer_stitch_outputs)
            print 'computing outside mask'
            print 'step 1'
            outside_mask_blurred = sum_subimages(full_masks, canvas.system,
                                                 canvas.dims)
            print 'step 2'
            outside_mask_blurred = outside_mask_blurred.pipe(
                lambda x: (x == 0).astype(float))
            print 'step 3'
            outside_mask_blurred = outside_mask_blurred.blur(edge_blend_radius)
            print outside_mask_blurred.array.shape
            print full_masks_blurred[0].array.shape
            del full_masks  # to save some memory
            print 'blending'
            self.detail_transfer_stitch_output = blend_subimages(
                (canvas, ) + images,
                (outside_mask_blurred, ) + full_masks_blurred, canvas.system,
                canvas.dims)
            return self.detail_transfer_stitch_output
Exemplo n.º 8
0
def do_insert():
    m = Monary()
    num_docs = NUM_BATCHES * BATCH_SIZE
    params = [MonaryParam(
        ma.masked_array(nprand.uniform(0, i + 1, num_docs),
                        np.zeros(num_docs)), "x%d" % i) for i in range(5)]
    wc = WriteConcern(w=MONARY_W_DEFAULT)
    with profile("monary insert"):
        m.insert("monary_test", "collection", params, write_concern=wc)
Exemplo n.º 9
0
    def signup(self):
        system("clear")
        print("@@@ SnapQuick Registration page! ")

        connection = sqlite3.connect("../main/data_base.db")
        crsr = connection.cursor()
        crsr.execute("SELECT * FROM user")
        ans = crsr.fetchall()

        check = 0
        t = 0
        while not check:
            user_id = input("choose a user Id: ")
            for j in ans:
                if j[0] == user_id:
                    print("Already Taken")
                    t = 1
                    break
            if t:
                t = 0
            else:
                check = 1
                print("Available!")

        set_password = input("Enter Password: "******"First Name: ")
        lname = input("Last Name: ")
        gender = input("Gender: ")
        email_id = input("Email Id: ")
        phone_number = int(input("Phone Number: "))

        sql_command = """INSERT INTO user VALUES (?,?,?,?,?,?,?);"""
        crsr.execute(sql_command, (
            user_id,
            fname,
            lname,
            gender,
            email_id,
            phone_number,
            set_password,
        ))
        connection.commit()
        print("account succesfully Created !")
        profile().show_profile(entered_id)
Exemplo n.º 10
0
def do_insert():
    m = Monary()
    num_docs = NUM_BATCHES * BATCH_SIZE
    params = [
        MonaryParam(
            ma.masked_array(nprand.uniform(0, i + 1, num_docs),
                            np.zeros(num_docs)), "x%d" % i) for i in range(5)
    ]
    wc = WriteConcern(w=MONARY_W_DEFAULT)
    with profile("monary insert"):
        m.insert("monary_test", "collection", params, write_concern=wc)
Exemplo n.º 11
0
def createprofile(name):
    print name.text
    try:
        profiles = cPickle.load(open('profilelist', 'r'))
        print profiles
    except:
        profiles = []
        #print "did not load profiles"
        pass
    current = profile(name.text)
    load(current)
    profiles.append(current)
    cPickle.dump(profiles, open('profilelist', 'w'))
Exemplo n.º 12
0
def do_monary_query():
    with Monary("127.0.0.1") as m:
        with profile("monary query"):
            arrays = m.query(
                "monary_test",  # database name
                "collection",  # collection name
                {},  # query spec
                ["x1", "x2", "x3", "x4", "x5"],  # field names
                ["float64"] * 5  # field types
            )

    # prove that we did something...
    print(numpy.mean(arrays, axis=-1))
Exemplo n.º 13
0
def do_monary_query():
    with Monary("127.0.0.1") as m:
        with profile("monary query"):
            arrays = m.query(
                "monary_test",                  # database name
                "collection",                   # collection name
                {},                             # query spec
                ["x1", "x2", "x3", "x4", "x5"], # field names
                ["float64"] * 5                 # field types
            )

    # prove that we did something...
    print(numpy.mean(arrays, axis=-1))
Exemplo n.º 14
0
def do_pymongo_query():

    c = pymongo.MongoClient()
    collection = c.monary_test.collection

    with profile("pymongo query"):
        num = collection.count()
        arrays = [ numpy.zeros(num) for i in range(5) ]
        fields = [ "x1", "x2", "x3", "x4", "x5" ]
        arrays_fields = list(zip(arrays, fields))

        for i, record in enumerate(collection.find()):
            for array, field in arrays_fields:
                array[i] = record[field]

    # prove that we did something...
    print(numpy.mean(arrays, axis=-1))
Exemplo n.º 15
0
    def detail_transfer_stitch_pt_1(self, detail_transfer_blur_op,
                                    edge_blend_radius):
        with profile():
            print 'detail_transfer_stitch_pt_1'

            canvas = (self.establishing.white_balance().normalize().resize(
                scale=self.canvas_scale))
            canvas_blurred = detail_transfer_blur_op(canvas.astype(np.float32))
            # TODO: not being used
            # pool = multiprocessing.dummy.Pool()
            self.detail_transfer_stitch_outputs = map(
                self._detail_transfer_stitch_step,
                zip(
                    repeat((canvas, canvas_blurred, detail_transfer_blur_op,
                            edge_blend_radius)), self.closes, self.c_homs,
                    self.c_masks))
            print 'all details are transferred'
Exemplo n.º 16
0
def do_pymongo_query():

    c = pymongo.Connection("localhost")
    collection = c.monary_test.collection

    with profile("pymongo query"):
        num = collection.count()
        arrays = [numpy.zeros(num) for i in range(5)]
        fields = ["x1", "x2", "x3", "x4", "x5"]
        arrays_fields = zip(arrays, fields)

        for i, record in enumerate(collection.find()):
            for array, field in arrays_fields:
                array[i] = record[field]

    # prove that we did something...
    print numpy.mean(arrays, axis=-1)
Exemplo n.º 17
0
def do_pymongo_query():

    c = pymongo.Connection("localhost")
    collection = c.monary_test.collection

    with profile("pymongo query"):
        num = collection.count()
        arrays = [ numpy.zeros(num) for i in range(5) ]
        fields = [ "x1", "x2", "x3", "x4", "x5" ]
        arrays_fields = zip(arrays, fields)

        for i, record in enumerate(collection.find()):
            for array, field in arrays_fields:
                array[i] = record[field]

    for array in arrays: # prove that we did something...
        print numpy.mean(array) 
Exemplo n.º 18
0
def do_monary_block_query():
    count = 0
    sums = numpy.zeros((5, ))
    with Monary("127.0.0.1") as m:
        with profile("monary block query"):
            for arrays in m.block_query(
                    "monary_test",  # database name
                    "collection",  # collection name
                {},  # query spec
                ["x1", "x2", "x3", "x4", "x5"],  # field names
                ["float64"] * 5,  # field types
                    block_size=32 * 1024,
            ):
                count += len(arrays[0])
                sums += [numpy.sum(arr) for arr in arrays]

    print "visited %i items" % count
    print sums / count  # prove that we did something...
Exemplo n.º 19
0
def do_insert():
    c = pymongo.MongoClient("localhost")
    collection = c.monary_test.collection

    num_docs = NUM_BATCHES * BATCH_SIZE
    arrays = [nprand.uniform(0, i + 1, num_docs) for i in xrange(5)]
    with profile("pymongo insert"):
        for i in xrange(NUM_BATCHES):
            stuff = []
            for j in xrange(BATCH_SIZE):
                idx = i * BATCH_SIZE + j
                record = {"x1": arrays[0][idx],
                          "x2": arrays[1][idx],
                          "x3": arrays[2][idx],
                          "x4": arrays[3][idx],
                          "x5": arrays[4][idx]}
                stuff.append(record)
            collection.insert(stuff)
def do_monary_block_query():
    count = 0
    sums = numpy.zeros((5,))
    with Monary("127.0.0.1") as m:
        with profile("monary block query"):
            for arrays in m.block_query(
                "monary_test",                  # database name
                "collection",                   # collection name
                {},                             # query spec
                ["x1", "x2", "x3", "x4", "x5"], # field names
                ["float64"] * 5,                # field types
                block_size=32 * 1024,
            ):
                count += len(arrays[0])
                sums += [ numpy.sum(arr) for arr in arrays ]

    print "visited %i items" % count
    print sums / count                          # prove that we did something...
Exemplo n.º 21
0
def do_insert():

    NUM_BATCHES = 3500
    BATCH_SIZE = 1000
    # 3500 batches * 1000 per batch = 3.5 million records

    c = pymongo.Connection("localhost")
    collection = c.monary_test.collection

    with profile("insert"):
        for i in xrange(NUM_BATCHES):
            stuff = []
            for j in xrange(BATCH_SIZE):
                record = dict(x1=random.uniform(0, 1),
                              x2=random.uniform(0, 2),
                              x3=random.uniform(0, 3),
                              x4=random.uniform(0, 4),
                              x5=random.uniform(0, 5))
                stuff.append(record)
            collection.insert(stuff)
Exemplo n.º 22
0
def do_insert():
    c = pymongo.MongoClient("localhost")
    collection = c.monary_test.collection

    num_docs = NUM_BATCHES * BATCH_SIZE
    arrays = [nprand.uniform(0, i + 1, num_docs) for i in xrange(5)]
    with profile("pymongo insert"):
        for i in xrange(NUM_BATCHES):
            stuff = []
            for j in xrange(BATCH_SIZE):
                idx = i * BATCH_SIZE + j
                record = {
                    "x1": arrays[0][idx],
                    "x2": arrays[1][idx],
                    "x3": arrays[2][idx],
                    "x4": arrays[3][idx],
                    "x5": arrays[4][idx]
                }
                stuff.append(record)
            collection.insert(stuff)
Exemplo n.º 23
0
def do_insert():

    NUM_BATCHES = 3500
    BATCH_SIZE = 1000
    # 3500 batches * 1000 per batch = 3.5 million records

    c = pymongo.Connection("localhost")
    collection = c.monary_test.collection

    with profile("insert"):
        for i in xrange(NUM_BATCHES):
            stuff = [ ]
            for j in xrange(BATCH_SIZE):
                record = dict(x1=random.uniform(0, 1),
                              x2=random.uniform(0, 2),
                              x3=random.uniform(0, 3),
                              x4=random.uniform(0, 4),
                              x5=random.uniform(0, 5)
                         )
                stuff.append(record)
            collection.insert(stuff)
Exemplo n.º 24
0
def do_insert():

    NUM_BATCHES = 4500
    BATCH_SIZE = 1000
    # 4500 batches * 1000 per batch = 4.5 million records

    c = pymongo.MongoClient()
    collection = c.monary_test.collection

    with profile("insert"):
        for i in xrange(NUM_BATCHES):
            stuff = []
            for j in xrange(BATCH_SIZE):
                record = dict(x1=random.uniform(0, 1),
                              x2=random.uniform(0, 2),
                              x3=random.uniform(0, 3),
                              x4=random.uniform(0, 4),
                              x5=random.uniform(0, 5))
                stuff.append(record)
            collection.insert(stuff)
    print "Inserted %d records." % (NUM_BATCHES * BATCH_SIZE)
Exemplo n.º 25
0
def do_insert():

    NUM_BATCHES = 4500
    BATCH_SIZE = 1000
    # 4500 batches * 1000 per batch = 4.5 million records

    c = pymongo.MongoClient()
    collection = c.monary_test.collection

    with profile("insert"):
        for i in xrange(NUM_BATCHES):
            stuff = [ ]
            for j in xrange(BATCH_SIZE):
                record = dict(x1=random.uniform(0, 1),
                              x2=random.uniform(0, 2),
                              x3=random.uniform(0, 3),
                              x4=random.uniform(0, 4),
                              x5=random.uniform(0, 5)
                         )
                stuff.append(record)
            collection.insert(stuff)
    print "Inserted %d records." % (NUM_BATCHES * BATCH_SIZE)
Exemplo n.º 26
0
    def simple_stitch(self):
        with profile():
            print 'simple_stitch'

            canvas = self.establishing.resize(scale=self.canvas_scale)

            def process(inputs):
                close, c_hom = inputs
                foreground, homography_mask = apply_homography(
                    close, c_hom, canvas.system, canvas.dims)
                print 'processed'
                return foreground

            pool = multiprocessing.dummy.Pool()
            self.simple_stitch_outputs = pool.map(
                process, zip(self.closes, self.c_homs))

            for foreground, mask in zip(self.simple_stitch_outputs,
                                        self.c_masks):
                composite(canvas, foreground, mask, inplace=True)

            self.simple_stitch_output = canvas
            return self.simple_stitch_output
Exemplo n.º 27
0
    def find_homographies(self, downsample_scale=0.5, num_threads=None):
        with profile():
            print 'find_homographies'
            # This uses a thread pool (a dummy multiprocessing pool) to pipeline the
            # OpenCV work and take better advantage of multicore machines.
            pool = multiprocessing.dummy.Pool(processes=num_threads)

            self.e_features = find_features(self.establishing)
            c_features_results = [
                pool.apply_async(
                    lambda c: find_features(
                        c.resize(scale=downsample_scale)
                        if downsample_scale < 1 else c), (c, ))
                for c in self.closes
            ]
            self.c_homs = pool.map(
                lambda c_features_result: find_homography(
                    c_features_result.get(), self.e_features),
                c_features_results)
            print self.c_homs
            self.c_features = [
                c_features_result.get()
                for c_features_result in c_features_results
            ]
Exemplo n.º 28
0
    def generate_masks_stacked(self):
        with profile():
            print 'generate_masks_stacked'

            self.calculate_areas()
            area_order = sorted(range(len(self.areas)),
                                key=lambda i: self.areas[i])

            mask_template = (self.establishing.resize(
                scale=self.canvas_scale).pipe(lambda x: np.zeros(x.shape[:2])))
            available = mask_template.pipe(lambda x: x + 1)
            self.c_masks = [None] * len(self.closes)
            for i in area_order:
                c_hom, close = self.c_homs[i], self.closes[i]
                homography_boundary = map(c_hom, close.corners())
                clipped_homography_boundary = clip(homography_boundary,
                                                   mask_template.corners())
                c_mask = (mask_template.fill_poly(clipped_homography_boundary,
                                                  color=1).erode(3))
                c_mask.array *= available.array
                c_mask = c_mask
                self.c_masks[i] = c_mask

                available.array -= c_mask.array
Exemplo n.º 29
0
sim_mo_i=sim_Em+sim_Im+sim_noise_EIm #mock noisy data for collecting infected mosquitoes
#pl.figure()
#pl.plot(sim_Em+sim_Im, '-b', label='infected_m')
#pl.plot(sim_noise_EIm,'g', label='noise')
#pl.plot(sim_mo_i,'r', label='data_model_noise_weekly')
#pl.legend()
#pl.show()

sim_adultm=sim_Sm+sim_Em+sim_Im #mock data for collecting adult mosquitoes
sim_iem=sim_Im+sim_Em #mock data for collecting infected mosquitoes


'''==============================calculate parmameter likelihood surface =============================='''

#making range list for parameter profiling
dengue_profile=profile(opt_dengue.model, opt_param, opt_ini, time_step, 15, 80) 
param_name=['beta', 'repH', 'x', 'pi_mua', 'beta_m', 'mu_m']


#profile likelihood:
########################

for i in range(len(opt_param)):
	proflog={}
	param_adj_ls, param_fix_temp, param_test_ind = dengue_profile.fit_fix(i,0)
	#iterate through fixed parameter list if there are any
	for fix_ind in param_fix_temp:
		proflog_temp={}
		param_fix=[dengue_profile.param[x] for x in fix_ind]
		fit_ind=list(set(param_test_ind)-set(fix_ind))
		#param_fit=[dengue_profile.param[p_f] for p_f in fit_ind]
Exemplo n.º 30
0
def pf():
    return str(make_page(user, logo, profile(user)))
Exemplo n.º 31
0
def task():
    profile.profile()
    shoppingMalls.shop()
    icon.icon()
Exemplo n.º 32
0
def login(data_base):

    name=sign_in(data_base)
    id=data_base[name][0]

    if name==0:
        print(" ")
    else:
        start=time.time()
        while True:

           os.system('clear')
           print("\n===============================")
           print("    Welcome back: ",name)
           print("===============================\n")
           print("""Select from given options:
           1. Profile
           2. Bank Account
           3. Games
           4. Events
           5. Memories
           6. Settings
           7. Help & Support
           8. Log out""")

           choice=input()

           if choice in ['1','profile','Profile','PROFILE']:
               profile(data_base,name)

           elif choice in ['2','bankaccount','BankAccount','Bank Account','bank account','BANKACCOUNT']:
                bank_account(data_base,name)

           elif choice in ['3','games','Games','GAMES']:
                os.system('clear')
                user_game(data_base,id)

           elif choice in ['4','Events','events','EVENTS']:
                print('events')

           elif choice in ['5','memories','Memories','MEMORIES']:
                print('memories')

           elif choice in ['6','settings','Settings','SETTINGS']:
                name=change_detail(data_base,name)
                if name==0:
                    break

           elif choice in ['7','Help&Support','help&support','Help & Support','help&support']:
                print('help')

           elif choice in ['8','Log out','Logout','logout','LOGOUT','log out']:
                os.system('clear')
                stop=time.time()
                t=stop-start
                db=pymysql.connect('localhost','nayan','1234','user_database')
                cursor=db.cursor()
                check=data_base[name][2]

                if check==None:
                    data_base[name][2]=t
                    cursor.execute('update data set usage_time=%s where username=%s',(t,name))
                else:
                    total_usage=t+check
                    data_base[name][2]=total_usage
                    cursor.execute('UPDATE data SET usage_time=%s WHERE username=%s',(total_usage,name))

                db.commit()
                db.close()
                print('You have been successfully logged out')
                print('Login duration:',int(t),' seconds')
                break

           else:
                print("chose a valid option")
Exemplo n.º 33
0
pl.figure()
#pl.plot(opt_res[:,0],'b', label='SH')
#pl.plot(opt_res[:,1],'r', label='EH')
#pl.plot(opt_res[:,2],'g', label='IH')
pl.plot(opt_res[:,3],'m', label='A')
pl.plot(opt_res[:,4],'y', label='Sm')
#pl.plot(opt_res[:,5],'k', label='Em')
#pl.plot(opt_res[:,6],'c', label='Im')
pl.legend()
pl.show()
#pl.savefig('temp_fig')
'''

'''==============================calculate paried param likelihood surface =============================='''

dengue_profile=profile(opt_temp.model, opt_param, opt_ini, time_step, 10, 60)
param_name=['beta', 'repH', 'x', 'pi_mua', 'beta_m', 'mu_m']
templs=dengue_profile.pert_level

temp_ee=[(a,b) for a in range(len(opt_param)) for b in range(len(opt_param))]
temp_ee2=[]

for j,k in temp_ee: #drawing pairs
	temp_ele1=(j,k)
	temp_ele2=(k,j)
	if temp_ele2 not in temp_ee2 and j!=k:
		temp_ee2.append(temp_ele1)
#print temp_ee2

for q,r in temp_ee2:
Exemplo n.º 34
0
from BeautifulSoup import BeautifulSoup
from urllib2 import urlopen
from profile import profile
import csv

csv_file = open("email_list.csv", "w+")

url = 'https://scrapebook22.appspot.com'
response = urlopen(url).read()
soup = BeautifulSoup(response)


for link in soup.findAll("a"):
    if link.string == "See full profile":
        person_html = urlopen(url + link["href"]).read()
        person_soup = BeautifulSoup(person_html)
        profileData = person_soup.findAll("li")

        email = person_soup.find("span", attrs={"class": "email"}).string
        name = person_soup.find("div", attrs={"class": "col-md-8"}).h1.string
        city = person_soup.find("span", attrs={"data-city": True}).string

        profil = profile(email, name, city)

        csv_file.write(profil.to_csv() + "\n")


csv_file.close()
Exemplo n.º 35
0
async def profile_command(ctx, *args):
    response = profile.profile(ctx, args)
    if type(response) is discord.embeds.Embed:
        await ctx.send(" ", embed=response)
    elif type(response) is str:
        await ctx.send(response)
Exemplo n.º 36
0
        num_sync = log_sync(signature, db_path + "profile/")
        config["num_sync"] = num_sync

        # feel free to customize the repo name you want
        name = kernel["tvm_func_name"].replace("_kernel0", "")
        operator_path = db_path + op_type + "_db/"
        if not os.path.isdir(operator_path):
            os.mkdir(operator_path)
        with open(operator_path + name + ".json", "w+") as f:
            json.dump(config, f)
        with open(operator_path + name + ".cu", "w+") as f:
            f.write(new_code)

        default_tags = ""
        if (op_type == "Dot"):
            # Todo: move the transpose information into identifier
            default_tags += kernel["parameters"]["transpose_A"] * \
                ",transA" + kernel["parameters"]["transpose_B"]*",transB"

        # apply rules that every 32 threads will be formed as a warp
        resource = math.ceil(prod(config["blockDim"]) / 32) * 32 * prod(
            config["gridDim"])

        prepare_file(signature, kernel["code"], config, db_path + "profile/")
        profile_info = profile(signature, db_path + "profile/")
        print(profile_info, resource, config["num_sync"])
        insert_db(operator_path + name,
                  resource,
                  tags=default_tags,
                  profile=profile_info)
Exemplo n.º 37
0
    print(
        "Welcome to Aarush's Basketball Simulator, created in collaboration with Maanav Singh."
    )
    print(
        "This simulator procedurally generates player profiles with statistics, which you can then pit together"
    )
    print(
        "in 1v1 scenarios to determine who is the better basketball player. When you input 2, you will be asked how many players"
    )
    print("you wish to generate. Any number can be inputted.")
elif userInput == 2:
    print("How many players would you like to generate profiles for?")
    userInput = int(input())
    playerArray = []
    for _ in range(userInput):
        playerArray.append(profile())
    printStats(playerArray)
while (True):
    print(
        "Would you like to simulate next year? Respond 1 for yes and 2 for no")
    userInput = int(input())

    if userInput == 1:
        for i in playerArray:
            i.incrementAge()
            i.updateStats()
            for k, v in i.getStats().items():
                print(k, v)
            print("\n")
    else:
        break
        model = pickle.load(f_un)

    with open("../data/cols.pkl") as f_un:
        events = pickle.load(f_un)

    df0 = pd.DataFrame(columns=events)
    s_mission = set(sign.columns)

    # find common model events in current mission 

    for i in ['_std', '_md', '_min', '_max', '_cnt']:
        event_base = [ e.replace(i,'') for e in events if e.endswith(i)]

    mission_events = list(set(event_base) & s_mission)

    s1 = profile(sign, mission_events, os.sys.argv[1])

    mission_events = list(set(events) & set(s1.columns))

    sign =  pd.concat([s1[mission_events],df0])

    agg_filename = "../data/" + os.sys.argv[1] + "_agg.csv"
    sign.to_csv(agg_filename)

    X = sign[events].fillna(-9999999.)
    X = X.values

    preds = np.clip(np.round(model.predict(X)), 1, 5)

    print
    print
Exemplo n.º 39
0
    def MessageStatus(self, msg, status):
        if status == Skype4Py.cmsReceived or status == Skype4Py.cmsSent:
            # I have no idea what this line does other than it makes the bot respond to its own messages, and it only works in private chat
            #if not msg.Sender.Handle in self.blacklist:
            if msg.Body[0] == "!" and msg.Sender.Handle != "everythingbot":
                print "[" + str(datetime.now())[:-7] + "] " + msg.Sender.Handle + ": " + msg.Body

            # !help
            if re.match("!help(?!\S)", msg.Body):
                msg.Chat.SendMessage(help())

            # !ping
            elif re.match("!ping(?!\S)", msg.Body):
                msg.Chat.SendMessage(ping())

            # !members
            elif re.match("!members(?!\S)", msg.Body):
                msg.Chat.SendMessage(members(msg.Chat.Members))

            # !profile
            elif re.match("!profile(?!\S)", msg.Body):
                try:
                    skypeName = msg.Body[9:]
                    msg.Chat.SendMessage(profile(skypeName, msg.Chat.Members))
                except IndexError:
                    msg.Chat.SendMessage("Skype username required for profile lookup.")

            # !orangecrush
            # If you're reading this on the Github repo, congratulations on being the first to figure out that it's been public all along.
            elif re.match("!orangecrush(?!\S)", msg.Body):
                msg.Chat.SendMessage("!orangecrush")

            # !lenny
            elif re.match("!lenny(?!\S)", msg.Body):
                msg.Chat.SendMessage(self._lenny)

            # !friendcodes
            elif re.match("!friendcodes(?!\S)", msg.Body) or re.match("!fc(?!\S)", msg.Body):
                msg.Chat.SendMessage(friendcodes())

            # !gostats
            elif re.match("!gostats(?!\S)", msg.Body):
                msg.Chat.SendMessage("http://csgo-stats.com/" + msg.Body[9:])

            # !tableflip
            elif re.match("!tableflip(?!\S)", msg.Body):
                msg.Chat.SendMessage(self._tableflip)

            # !tableset
            elif re.match("!tableset(?!\S)", msg.Body):
                msg.Chat.SendMessage(self._tableset)

            # !coinflip
            elif re.match("!coinflip(?!\S)", msg.Body):
                msg.Chat.SendMessage(coinflip())

            # URL titles

            # This is the opt-into title code.
            #elif re.match("!title(?!\S)", msg.Body):
            #    if re.match('!title http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE):
            #        url = re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE)
            #        msg.Chat.SendMessage(url_get(url.group(0)))
            #    else:
            #        msg.Chat.SendMessage("Invalid URL.")

            # This is the opt-out of title code.
            elif re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE) and not re.search("!nt(?!\S)", msg.Body) and msg.Sender.Handle != "everythingbot":
                url = re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE)
                msg.Chat.SendMessage(url_get(url.group(0)))

            # !removebot
            elif re.match("!removebot(?!\S)", msg.Body):
                if removebot(msg.Sender.Handle):
                    msg.Chat.Leave()

            # !restartbot
            elif re.match("!restartbot(?!\S)", msg.Body):
                if removebot(msg.Sender.Handle):
                    msg.Chat.SendMessage("Restarting bot.")
                    execfile("~halbrdbot.py")
                    sys.exit()

            # !twitch (channel)
            # !gostats
            elif re.match("!twitch(?!\S)", msg.Body):
               # msg.Chat.SendMessage("http://twitch.tv/" + msg.Body[8:])
                msg.Chat.SendMessage(twitch(msg.Body[8:]))

            # !requestfunction (string)
            #elif re.match("!requestfunction(?!\S)", msg.Body):
            #    msg.Chat.SendMessage(requestfunction(msg.Sender.Handle, msg.Body[17:]))

            #elif msg.Body == "!chatname":
            #    msg.Chat.SendMessage(msg.Chat.Name)

            # !hug
            elif re.match("!hug(?!\S)", msg.Body) and msg.Sender.Handle != "everythingbot":
                msg.Chat.SendMessage(hug(msg.Sender.FullName, msg.Body[5:]))

            # !bothug
            elif re.match("!bothug(?!\S)", msg.Body):
                msg.Chat.SendMessage(bothug(msg.Body[8:]))

            # !blacklist
            #elif re.match("!blacklist(?!\S)", msg.Body):
            #    msg.Chat.SendMessage(blacklist(msg.Sender.Handle, msg.Body[11:]))

            # !strats
            elif re.match("!strats(?!\S)", msg.Body):
                msg.Chat.SendMessage(strats(msg.Body[8:]))

            # !lwc
            elif re.match("!lwc(?!\S)", msg.Body):
                msg.Chat.SendMessage("Literally who cares.\nhttp://lynq.me/lwc.mp4")





            # lmao
            # Keep this as the last thing that gets checked
            elif re.search("l+ *m+ *a+ *o+", msg.Body, re.IGNORECASE) and msg.Sender.Handle != "everythingbot":
                msg.Chat.SendMessage("ayyy")
Exemplo n.º 40
0
 def to_profile(self):
     """Converts the alignment to profile format"""
     prf = profile.profile(self.env)
     _modeller.mod_profile_from_aln(aln=self.modpt, prf=prf.modpt,
                                    libs=self.env.libs.modpt)
     return prf
Exemplo n.º 41
0
    return count


def ones_mem(num):
    nib = 0
    if num == 0:
        return INT_BITS_NIBBLE[0]
    nib = num & 0xf
    return INT_BITS_NIBBLE[nib] + ones_mem(num >> 4)


if __name__ == '__main__':
    num = int(sys.argv[1])
    try:
        itr = int(sys.argv[2])
    except IndexError:
        itr = 1

    try:
        method = int(sys.argv[3])
    except IndexError:
        method = ones_1

    if method == 1:
        method = ones_1
    if method == 2:
        method = ones_mem

    for _ in xrange(itr):
        print "1s using : ", profile(method)(num)
Exemplo n.º 42
0
    def initUi(self):
        pf = profile.profile(self.parent)

        #로그아웃 버튼
        logoutbtn = QPushButton()
        logoutbtn.setMaximumHeight(32)
        logoutbtn.setMaximumWidth(42)
        logoutbtn.setStyleSheet(''' QPushButton{image:url(./icon/logout.png); border: 0px; width:32px; height:42px}        
                                        QPushButton:hover{background:rgba(0,0,0,0); border:0px}
                                        ''')

        alarm_groupbox = QGroupBox('안내설명')
        alarm_groupbox.setStyleSheet('font:9pt 나눔스퀘어라운드 Regular;')
        alarm_groupbox.setMinimumSize(300,170)

        empty = QLabel("   ")

        #강의 목록 그리기
        setting_label = QLabel('개인 설정')
        setting_label.setStyleSheet("font: 16pt 나눔스퀘어라운드 Regular;background:#eef5f6;color:#42808a")
        #horizon_line = QLabel('─────────────────────')
        #구분선
        horizon_line = QLabel()
        horizon_img = QPixmap('./ui/afterlogin_ui/horizon_line.png')
        horizon_img = horizon_img.scaled(310,12,QtCore.Qt.KeepAspectRatio,QtCore.Qt.FastTransformation)
        horizon_line.setPixmap(horizon_img)
        horizon_line.setAlignment(Qt.AlignTop)

        #사용 설명
        self.use_explanation = QGridLayout()
        #useicon_list = QListWidget()
        # lecture = QLabel()
        # lecture_img = QPixmap('./ui/afterlogin_ui/list.png')
        # lecture_img = lecture_img.scaled(100,100 , QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)
        # lecture.setPixmap(lecture_img)
        lecture = QPushButton()
        lecture.setStyleSheet('''
                QPushButton{image:url(./ui/afterlogin_ui/list.png); border:0px; width:40px; height:40px}
                QPushButton:hover{background:#cce5e8; border:0px}   
                ''')
        lecture.setFocusPolicy(Qt.NoFocus)
        lecture.clicked.connect(lambda: self.use_explain(0))
    
        alarm = QPushButton()
        alarm.setStyleSheet('''
                QPushButton{image:url(./ui/afterlogin_ui/alarm.png); border:0px; width:40px; height:40px}
                QPushButton:hover{background:#cce5e8; border:0px}   
                ''')
        alarm.setFocusPolicy(Qt.NoFocus)
        alarm.clicked.connect(lambda:self.use_explain(1))

        rank = QPushButton()
        rank.setStyleSheet('''
                QPushButton{image:url(./ui/afterlogin_ui/trophy.png); border:0px; width:40px; height:40px}
                QPushButton:hover{background:#cce5e8; border:0px}   
                ''')
        rank.setFocusPolicy(Qt.NoFocus)
        rank.clicked.connect(lambda:self.use_explain(2))

        setting = QPushButton()
        setting.setStyleSheet('''
                QPushButton{image:url(./ui/afterlogin_ui/setting.png); border:0px; width:40px; height:40px}
                QPushButton:hover{background:#cce5e8; border:0px}   
                ''')
        setting.setFocusPolicy(Qt.NoFocus)
        setting.clicked.connect(lambda:self.use_explain(3))

        self.use_explanation.addWidget(lecture,0,0)
        self.use_explanation.addWidget(alarm,0,1)
        self.use_explanation.addWidget(rank,1,0)
        self.use_explanation.addWidget(setting,1,1)



        alarm_widget_label = QLabel('알림 위젯')
        alarm_widget_label.setStyleSheet('font:9pt 나눔스퀘어라운드 Regular;')

        alarm_sound_label = QLabel('소리 기능')
        alarm_sound_label.setStyleSheet('font:9pt 나눔스퀘어라운드 Regular;')
        alarm_sound_label.setAlignment(Qt.AlignLeft)

        # 위젯 on/off 버튼
        self.widget_on_off_button = QPushButton()
        self.widget_on_off_button.setMinimumHeight(50)
        self.widget_on_off_button.setMinimumWidth(50)
        self.widget_on_off_button.setFocusPolicy(Qt.NoFocus)
        self.widget_on_off_button.setStyleSheet('''
                                QPushButton{image:url(./icon/alarm_on.png); border:0px; width:50px; height:50px;}
                                ''')
        self.widget_on_off_button_status = True
        self.widget_on_off_button.clicked.connect(self.widget_button_toggle)

        # 소리 on/off 버튼
        self.sound_on_off_button = QPushButton()
        self.sound_on_off_button.setMinimumHeight(50)
        self.sound_on_off_button.setMinimumWidth(50)
        self.sound_on_off_button.setFocusPolicy(Qt.NoFocus)
        self.sound_on_off_button.setStyleSheet('''
                                QPushButton{image:url(./icon/alarm_on.png); border:0px; width:50px; height:50px;}
                                ''')
        self.sound_on_off_button.setCheckable(True)
        self.sound_on_off_button_status = True
        self.sound_on_off_button.clicked.connect(self.sound_button_toggle)


        self.title.addWidget(setting_label)
        #self.title.addWidget(logoutbtn)

        # self.line.addWidget(alarm_widget_label)
        # self.line.addWidget(self.widget_on_off_button,alignment=(QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop))
        # self.line.addWidget(alarm_sound_label)
        # self.line.addWidget(self.sound_on_off_button,alignment=(QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop))
        # #self.line.addWidget(useicon_list)
        # self.line.addStretch(1)

        #alarm_groupbox.setLayout(self.line)
        alarm_groupbox.setLayout(self.use_explanation)
        self.mainLayout.addLayout(self.title)
        self.mainLayout.addWidget(horizon_line)
        self.mainLayout.addWidget(pf, alignment=QtCore.Qt.AlignCenter)
        self.mainLayout.addWidget(alarm_groupbox)
        self.mainLayout.addWidget(empty)
        self.mainLayout.addWidget(empty)
        self.mainLayout.addStretch(1)
Exemplo n.º 43
0
    for f in glob(os.path.join(os.path.dirname(__file__), 'mechmap_archive', options.archive, '*')):
        shutil.copy(f, outdir)

    

from both import geos
from profile import profile
from mech import mechnml, mechinc, mechext
from map import map, trymap
if options.extfiles:
    mech = mechext
else:
    mech = mechnml
go = geos(tracerpath,
          smvpath)
po = profile(profilepath)

if not os.path.exists(convpath):
    if os.path.exists(os.path.join(os.path.dirname(__file__), convpath + '.csv')):
        convpath = os.path.join(os.path.dirname(__file__), convpath + '.csv')
    elif 'Y' == raw_input("Conversion path does not exist; type Y to create it or any other key to abort\n"):
        trymap(mech(mechpath), convpath, go)
    else:
        exit()
mech_info = mechinc(mech(mechpath), convpath)
cspec_info = go.cspec_info()
tracer_info = go.tracer_info()
profile_info = po.profile_info()
try: 
    mappings, nprof = map(mech(mechpath), convpath, go, po)
except TypeError, err: