Exemplo n.º 1
0
def main():
    usage_msg = "Usage: python %s player_balance [ number_of_card_decks ]" % __file__
    num_argv = len(sys.argv)

    if num_argv not in (2, 3):
        print usage_msg
        sys.exit()

    else:

        is_valid, num = check_int(sys.argv[1])
        if is_valid:
            player_balance = num
        else:
            print "Invalid parameter: %s" % sys.argv[1]
            print usage_msg
            sys.exit()

        num_decks = None
        if num_argv == 3:
            is_valid, num = check_int(sys.argv[2])

            if is_valid:
                num_decks = num
            else:
                print "Invalid parameter: %s" % sys.argv[2]
                print usage_msg
                sys.exit()

    player = Player(player_balance)
    dealer = Dealer(num_decks) if num_decks else Dealer()
    game = Game(dealer, player)

    while game.run():
        pass
Exemplo n.º 2
0
def main():
    usage_msg = "Usage: python %s player_balance [ number_of_card_decks ]" % __file__
    num_argv = len(sys.argv)
    
    if num_argv not in (2, 3):
        print usage_msg; sys.exit()
    
    else:
        
        is_valid, num = check_int(sys.argv[1])
        if is_valid:
            player_balance = num
        else:
            print "Invalid parameter: %s" % sys.argv[1]
            print usage_msg; sys.exit()
        
        num_decks = None
        if num_argv == 3:
            is_valid, num = check_int(sys.argv[2])
            
            if is_valid:
                num_decks = num
            else:
                print "Invalid parameter: %s" % sys.argv[2]
                print usage_msg; sys.exit()
                
    player = Player(player_balance)
    dealer = Dealer(num_decks) if num_decks else Dealer()
    game = Game(dealer, player)
    
    while game.run():
        pass
Exemplo n.º 3
0
def pickle_data(folder_name, data=None, curr_time=None):
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)

    if data is None:
        random_millisec = ""
        while not utils.check_int(random_millisec):
            random_millisec = np.random.choice(os.listdir(folder_name))[:11]
        print random_millisec

        with open(folder_name + random_millisec + "_gp", 'rb') as f:
            gp = pickle.load(f)
        with open(folder_name + random_millisec + "_gplist", 'rb') as f:
            gp_list = pickle.load(f)
        with open(folder_name + random_millisec + "_slist", 'rb') as f:
            s_list = pickle.load(f)
        with open(folder_name + random_millisec + "_losslist", 'rb') as f:
            loss_list = pickle.load(f)
    else:
        with open(folder_name + str(curr_time) + "_gp", 'wb') as f:
            pickle.dump(data[0], f)
        with open(folder_name + str(curr_time) + "_gplist", 'wb') as f:
            pickle.dump(data[1], f)
        with open(folder_name + str(curr_time) + "_slist", 'wb') as f:
            pickle.dump(data[2], f)
        with open(folder_name + str(curr_time) + "_losslist", 'wb') as f:
            pickle.dump(data[3], f)

    if data is None:
        return (gp, gp_list, s_list, loss_list)
Exemplo n.º 4
0
 def from_json_dict(
     data: Any
 ) -> 'NewsItem':
     """Create news item from dictionary loaded from JSON."""
     if not isinstance(data, dict):
         raise TypeError(data)
     name = check_str(data['name'])
     title = check_str(data['title'])
     category_slug = check_str(data['category_slug'])
     category_id = check_int(data['category_id'])
     category_title: Optional[str] = None
     if 'category_title' in data:
         category_title = check_str(data['category_title'])
     date_str = check_str(data['date'])
     date = datetime.datetime.fromisoformat(date_str)
     url = check_optional_str(data['url'])
     url_ok: Optional[bool] = None
     if 'url_ok' in data:
         url_ok = check_bool(data['url_ok'])
     wikitext_paragraphs: Optional[List[str]] = None
     if 'wikitext_paragraphs' in data:
         wikitext_paragraphs = check_list_str(data['wikitext_paragraphs'])
     tag_titles: List[str] = []
     if 'tag_titles' in data:
         tag_titles = check_list_str(data['tag_titles'])
     author_name: Optional[str] = None
     if 'author_name' in data:
         author_name = check_str(data['author_name'])
     return NewsItem(
         name, title, category_id, category_slug, category_title, date,
         tag_titles, author_name, url, url_ok, wikitext_paragraphs
     )
Exemplo n.º 5
0
def process_categories(
    input_from_js_file: TextIO, input_bonus_file: TextIO,
    input_colors_file: TextIO, output_file: TextIO,
) -> None:
    """Build categories_by_slug list from file."""
    categories_data_from_js = json.load(input_from_js_file)
    categories_data_bonus = json.load(input_bonus_file)
    categories_data_colors = json.load(input_colors_file)

    categories_by_slug: Dict[str, str] = {}
    for category_url_data in load_category_urls(categories_data_from_js):
        category_url = check_str(category_url_data)
        category_slug = category_url.split('/')[-1]
        categories_by_slug[category_slug] = '/'.join(
            category_url.split('/')[2:]
        )
    for category_url_data in categories_data_bonus:
        category_url = check_str(category_url_data)
        category_slug = category_url.split('/')[-1]
        categories_by_slug[category_slug] = category_url

    categories_by_id_data: Dict[int, str] = {}
    for category_color_data, category_ids in categories_data_colors.items():
        category_color = check_str(category_color_data)
        for category_id_data in category_ids:
            category_id = check_int(category_id_data)
            categories_by_id_data[category_id] = category_color

    data = {
        'categories_by_id': categories_by_id_data,
        'categories_by_slug': categories_by_slug
    }
    json.dump(data, output_file, indent=4)
Exemplo n.º 6
0
    def _check_params(self):
        """Check PHATE parameters

        This allows us to fail early - otherwise certain unacceptable
        parameter choices, such as mds='mmds', would only fail after
        minutes of runtime.

        Raises
        ------
        ValueError : unacceptable choice of parameters
        """
        utils.check_positive(n_components=self.n_components, k=self.knn)
        utils.check_int(n_components=self.n_components,
                        k=self.knn,
                        n_jobs=self.n_jobs)
        utils.check_between(-1, 1, gamma=self.gamma)
        utils.check_if_not(None, utils.check_positive, a=self.decay)
        utils.check_if_not(None,
                           utils.check_positive,
                           utils.check_int,
                           n_landmark=self.n_landmark,
                           n_pca=self.n_pca)
        utils.check_if_not('auto',
                           utils.check_positive,
                           utils.check_int,
                           t=self.t)
        if not callable(self.knn_dist):
            utils.check_in([
                'euclidean', 'precomputed', 'cosine', 'correlation',
                'cityblock', 'l1', 'l2', 'manhattan', 'braycurtis', 'canberra',
                'chebyshev', 'dice', 'hamming', 'jaccard', 'kulsinski',
                'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
                'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath',
                'sqeuclidean', 'yule', 'precomputed_affinity',
                'precomputed_distance'
            ],
                           knn_dist=self.knn_dist)
        if not callable(self.mds_dist):
            utils.check_in([
                'euclidean', 'cosine', 'correlation', 'braycurtis', 'canberra',
                'chebyshev', 'cityblock', 'dice', 'hamming', 'jaccard',
                'kulsinski', 'mahalanobis', 'matching', 'minkowski',
                'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener',
                'sokalsneath', 'sqeuclidean', 'yule'
            ],
                           mds_dist=self.mds_dist)
        utils.check_in(['classic', 'metric', 'nonmetric'], mds=self.mds)
Exemplo n.º 7
0
def on_arduino():
    global lv, rv, dist
    t = threading.currentThread()
    while getattr(t, 'do_run', True):
        s = arduino.readline()
        if s and check_int(s):
            lv, rv, dist = decode(int(s))
            print 'arduino: ', lv, ' ', rv, ' ', dist
def plot_experiment(params, output_path):
    folder_name = get_folder_name(params, output_path)
    all_experiments = set([f[:11] for f in os.listdir(folder_name) if utils.check_int(f[:11])])
    all_experiments = sorted(all_experiments)
    for experiment in all_experiments:
        gp, gp_list, s_list = pickle_data(folder_name, file_prefix=experiment)

        data, X_range, X, Y, Z, is_us, goal_func = datasets.load_data(params["data_name"], True)

        print X_range.shape
        h, w = X_range.shape
        for i in range(len(gp_list)):

            gpi = gp_list[i]
            X_new, Y_new = s_list[i]
            print X_new.shape
            mean = np.zeros((X_range.shape[0], 1))
            var = np.zeros((X_range.shape[0], 1))
            for j in range(X_range.shape[0]):
                mean[j], var[j] = gpi.predict(X_range[j, :][np.newaxis, :])
            print gpi.Xtrain.shape
            print gpi.Ytrain.shape
            print Z.shape, is_us.shape, mean.flatten().shape, var.flatten().shape
            Z[is_us] = mean.flatten()
            p.contourf(X, Y, Z)  # GP mean
            p.colorbar()
            p.scatter(gpi.Xtrain[:, 0], gpi.Xtrain[:, 1], color='green', marker='x', s=50)  # training data
            p.scatter(X_new[:, 0], X_new[:, 1], color='purple', marker='*', s=100)  # test data
            p.show()
            Z[is_us] = var.flatten() ** 0.5
            p.contourf(X, Y, Z)  # GP mean
            p.colorbar()
            p.scatter(gpi.Xtrain[:, 0], gpi.Xtrain[:, 1], color='green', marker='x', s=50)  # training data
            p.scatter(X_new[:, 0], X_new[:, 1], color='purple', marker='*', s=100)  # test data
            p.show()
            Z[is_us] = data.flatten()
            p.contourf(X, Y, Z)  # GP mean
            p.colorbar()
            p.scatter(gpi.Xtrain[:, 0], gpi.Xtrain[:, 1], color='green', marker='x', s=50)  # training data
            p.scatter(X_new[:, 0], X_new[:, 1], color='purple', marker='*', s=100)  # test data
            p.show()

            Z[is_us] = mean.flatten()
            fig = p.figure()
            ax = fig.gca(projection='3d')
            # surf = ax.plot_surface(X,Y,Z, rstride=1, cstride=1, cmap=cm.coolwarm,
            #                   linewidth=0, antialiased=False)
            ax.contourf(X, Y, Z)
            # fig.colorbar(surf, shrink=0.5, aspect=5)
            ax.set_zlim(-15, 90)
            # p.colorbar()
            ax.scatter(gpi.Xtrain[:, 0], gpi.Xtrain[:, 1], gpi.Ytrain_original, color='green', marker='x',
                       s=50)  # training data
            # p.scatter(X_new[:,0],X_new[:,1],color='purple',marker='*', s=100)   # test data
            p.show()
            print X_new, Y_new
Exemplo n.º 9
0
    def __getitem_part__(self, item, num):
        """
        returns an inter block value or in-block...
        :param item: [1.5, 3.5], not [1.5][3.5]
        :return:
        """
        # major case - tuple
        if (type(item) == tuple) & (len(item) == 2):
            i, j = item
            # bound
            if i < 0:
                return self.k[num][0, j]
            if i >= self.shape[0] - 0.6:
                return self.k[num][self.shape[0] - 1, j]
            if j < 0:
                return self.k[num][i, 0]
            if j >= self.shape[1] - 0.6:
                return self.k[num][i, self.shape[1] - 1]

            if u.check_int(i) & u.check_half(j):
                out = self.dy[floor(j)] / self.k[num][floor(i), floor(j)]
                out += self.dy[ceil(j)] / self.k[num][floor(i), ceil(j)]
                out = 1 / out
                out *= self.dy[floor(j)] + self.dy[ceil(j)]
                return out

            if u.check_half(i) & u.check_int(j):
                out = self.dx[floor(i)] / self.k[num][floor(i), floor(j)]
                out += self.dx[ceil(i)] / self.k[num][ceil(i), floor(j)]
                out = 1 / out
                out *= self.dx[floor(i)] + self.dx[ceil(i)]
                return out
            # if for bound condition reason not inter cell condition
            if u.check_int(i) & u.check_int(j):
                return self.k[num][item]

        elif type(item) == int:
            return self.k[num][item]
Exemplo n.º 10
0
    def __getitem__(self, item):
        """
        returns an inter block value or in-block...
        :param item: [1.5, 3.5], not [1.5][3.5]
        :return:
        """
        # simplest case
        if u.check_if_numerical(self.__d):
            return self.__d
        # major case - tuple
        if (type(item) == tuple) & (len(item) == 2):
            i, j = item
            # bound
            if i == -0.5:
                return self.__d[0, j]
            if i == self.__d.shape[0] - 0.5:
                return self.__d[self.__d.shape[0] - 1, j]
            if j == -0.5:
                return self.__d[i, 0]
            if j == self.__d.shape[1] - 0.5:
                return self.__d[i, self.__d.shape[1] - 1]

            if u.check_int(i) & u.check_half(j):
                out = self.__d[floor(i), floor(j)] + self.__d[floor(i), ceil(j)]
                out *= 0.5
                return out

            if u.check_half(i) & u.check_int(j):
                out = self.__d[floor(i), floor(j)] + self.__d[ceil(i), floor(j)]
                out *= 0.5
                return out
            # if for some reason not boundary condition
            if u.check_int(i) & u.check_int(j):
                return self.__d[item]

        elif type(item) == int:
            return self.__d[item]
Exemplo n.º 11
0
    def inner(*args, **kwargs):
        tag_category = utils.request.form.get("category")
        if not utils.check_int(tag_category):
            return utils.generate_error_msg(utils.ERR_INVALID_ARGUMENTS,
                                            "category")

        tag_name = utils.request.form.get("name")
        if not utils.check_str(tag_name):
            return utils.generate_error_msg(utils.ERR_INVALID_ARGUMENTS,
                                            "name")

        def curry(model_arguments, *args_in, **kwargs_in):
            return func(tag_category=int(tag_category),
                        tag_name=tag_name,
                        tag_property=generate_property(int(tag_category),
                                                       **model_arguments),
                        *args_in,
                        **kwargs_in)

        return check_model_arguments(int(tag_category))(curry)(*args, **kwargs)
Exemplo n.º 12
0
def main():
    ciphers = 'caesar (c), railfence (r), playfair (p)\
               substitution (su), beale (b), straddle (st)'

    while True:
        cmd = input('encrypt, decrypt, or exit (en, de, ex)? ')
        # ENCRYPT
        while cmd == 'en':
            enc = input('select cipher: \n \
                        caesar (c), railfence (r), playfair (p) \n \
                        substitution (su), beale (b), straddle (st): \n')
            # caesar
            if enc == 'c':
                t = input('enter plain text: ')
                if t != '' and utils.check_latin(t):
                    pass
                else:
                    print('text can only consist of latin letters')
                    break
                k = input('enter integer key: ')
                if utils.check_int(k):
                    print(caesar.encrypt(t, int(k)))
                    cmd = ''
                else:
                    cmd = ''
            # railfence
            elif enc == 'r':
                t = input('enter plain text: ')
                k = input('enter integer key: ')
                if utils.check_int(k):
                    if int(k) > 1:
                        print(railfence.encrypt(t, int(k)))
                        cmd = ''
                    else:
                        print('key must be at least 2')
                        cmd = ''
                else:
                    cmd = ''
            # playfair
            elif enc == 'p':
                t = input('enter plain text: ')
                if t != '' and utils.check_latin(t):
                    pass
                else:
                    print('text can only consist of latin letters')
                    break
                k = input('enter string key: ')
                if k != '' and utils.check_latin(k):
                    print(playfair.encrypt(t, k))
                    pass
                else:
                    print('key can only consist of latin letters')
                    break
                cmd = ''
            # substitution
            elif enc == 'su':
                t = input('enter plain text: ')
                if t != '' and utils.check_latin(t):
                    pass
                else:
                    print('text can only consist of latin letters')
                    break
                k = input('enter string key: ')
                if k != '' and utils.check_latin(k):
                    try:
                        utils.check_full(k)
                    except ValueError:
                        print('key should bee full alphabet')
                        break
                    try:
                        print(substitution.encrypt(t, k))
                    except ValueError:
                        print('check errors for parameter issues')
                    pass
                else:
                    print('key can only consist of latin letters')
                    break
                cmd = ''
            # beale
            elif enc == 'b':
                t = input('enter plain text: ')
                if t != '' and utils.check_latin(t):
                    pass
                else:
                    print('text can have letters + punctuation')
                    break
                k = input('enter file name key: ')
                if k != '':
                    pass
                s = input('enter an integer seed: ')
                if s != '':
                    try:
                        s = int(s)
                    except ValueError:
                        print('seed must be integer')
                        break
                    try:
                        print(beale.encrypt(t, k, s))
                    except ValueError:
                        print('make sure your file is correct')
                    pass
                else:
                    print('text cannot be empty')
                    break
                cmd = ''
            # straddle
            elif enc == 'st':
                t = input('enter plain text: ')
                warn = 0
                for x in t:
                    if (t not in string.ascii_letters and t != '0' and t != '1'
                            and t != ' '):
                        warn += 1
                if warn > 0:
                    print('warning: text should include only letters, 0, or 1')
                if t != '':
                    pass
                else:
                    print('text cannot be empty')
                    break
                alk = input('enter alpha key: ')
                if alk != '':
                    pass
                else:
                    print('alpha_key cannot be empty')
                    break
                try:
                    utils.check_full(alk)
                except ValueError:
                    print('alpha_key must be full alphabet')
                    break
                nk = input('enter 2 digit numeric key: ')
                if nk != '':
                    pass
                if (len(nk) != 2 or not nk[0].isnumeric()
                        or not nk[1].isnumeric() or '0' in nk):
                    print('num_key must be a 2 digit int with unique digits')
                    print('cannot contain 0')
                    break
                adk = input('enter adding key:')
                if adk != '':
                    try:
                        print(straddle.encrypt(t, alk, nk, adk))
                    except ValueError:
                        print('make sure your add key is an integer')
                    pass
                else:
                    print('input cannot be empty')
                    break
                cmd = ''
            else:
                print('Please enter a valid input for a cipher.')
        # DECRYPT
        while cmd == 'de':
            dec = input('select cipher: \n \
                        caesar (c), railfence (r), playfair (p) \n \
                        substitution (su), beale (b), straddle (st): \n')
            # caesar
            if dec == 'c':
                t = input('enter cipher text: ')
                if t != '' and utils.check_latin(t):
                    pass
                else:
                    print('text can only consist of latin letters')
                    break
                k = input('enter integer key: ')
                if utils.check_int(k):
                    print(caesar.decrypt(t, int(k)))
                    cmd = ''
                else:
                    cmd = ''
            # railfence
            elif dec == 'r':
                t = input('enter cipher text: ')
                k = input('enter integer key: ')
                if utils.check_int(k):
                    if int(k) > 1:
                        print(railfence.decrypt(t, int(k)))
                        cmd = ''
                    else:
                        print('key must be at least 2')
                        cmd = ''
                else:
                    cmd = ''
            # playfair
            elif dec == 'p':
                t = input('enter cipher text: ')
                if t != '' and utils.check_latin(t):
                    pass
                else:
                    print('text can only consist of latin letters')
                    break
                k = input('enter string key: ')
                if k != '' and utils.check_latin(k):
                    print(playfair.decrypt(t, k))
                    pass
                else:
                    print('text can only consist of latin letters')
                    break
                cmd = ''
            # substitution
            elif dec == 'su':
                t = input('enter cipher text: ')
                if t != '' and utils.check_latin(t):
                    pass
                else:
                    print('text can only consist of latin letters')
                    break
                k = input('enter string key: ')
                if k != '' and utils.check_latin(k):
                    try:
                        utils.check_full(k)
                    except ValueError:
                        print('key should be full alphabet')
                        break
                    try:
                        print(substitution.decrypt(t, k))
                    except ValueError:
                        print('check errors for parameter issues')
                    pass
                else:
                    print('key can only consist of latin letters')
                    break
                cmd = ''
            # beale
            elif dec == 'b':
                t = input('enter cipher text: ')
                for x in t:
                    if x != ' ':
                        if not x.isnumeric():
                            print('text should consist of int literals')
                            break
                if t != '':
                    pass
                else:
                    print('warning: text should only consist of integers')
                    break
                k = input('enter file name key: ')
                if k != '':
                    try:
                        print(beale.decrypt(t, k))
                    except ValueError:
                        print('check that your text file is correct')
                    pass
                else:
                    print('text cannot be empty')
                    break
                cmd = ''
            # straddle
            elif dec == 'st':
                t = input('enter cipher text: ')
                warn = 0
                for x in t:
                    if (t not in string.ascii_letters and t != '0' and t != '1'
                            and t != ' '):
                        warn += 1
                if warn > 0:
                    print('warning: text should include only letters, 0, or 1')
                if t != '':
                    pass
                else:
                    print('text cannot be empty')
                    break
                alk = input('enter alpha key: ')
                if alk != '':
                    pass
                else:
                    print('alpha_key cannot be empty')
                    break
                try:
                    utils.check_full(alk)
                except ValueError:
                    print('alpha_key must be full alphabet')
                    break
                nk = input('enter 2 digit numeric key: ')
                if nk != '':
                    pass
                if (len(nk) != 2 or not nk[0].isnumeric()
                        or not nk[1].isnumeric() or '0' in nk):
                    print('num_key must be a 2 digit int with unique digits')
                    print('cannot contain 0')
                    break
                adk = input('enter adding key:')
                if adk != '':
                    try:
                        print(straddle.decrypt(t, alk, nk, adk))
                    except ValueError:
                        print('make sure your add key is an integer')
                    pass
                else:
                    print('text cannot be empty')
                    break
                cmd = ''
            else:
                print('Please enter a valid input for a cipher.')
        if cmd == 'ex':
            print('exit')
            return False
        elif cmd == '' or cmd == 'en' or cmd == 'de':
            pass
        else:
            print('Please enter a valid input of en, de, or ex.')
Exemplo n.º 13
0
              intuitive_theory, inference_params)

# Create a directory to save the plots in
directory = os.path.join(os.getcwd(), 'plots')
# Check whether directory exists, if not create it
if not os.path.exists(directory):
    os.makedirs(directory)

print(
    'This is supposed to be an interactive guide to setting up and running an experiment'
)

name_experiment = input('What is the name of your experiment? (string): ')
num_conditions = input(
    'How many conditions does the experiment have? (0-10): ')
num_conditions = check_int(num_conditions, 0, 10)

variables_input = input(
    'What variables should be manipulated? Enter their abbreviations (in brackets) with spaces inbetween. A possible list follows\n'
    'success - (success)\n'
    'task importance - (TI)\n'
    'self-awareness - (SA)\n'
    'probability of improvement - (PI)\n'
    'number of samples in experiment - (L)\n'
    'skill - (skill)\n'
    'effort - (effort)\n'
    'external - (external)\n'
    'luck - (luck)\n'
    'E.g. SI TI PI'
    'Any variable that is not set is sampled from a default distribution\n'
    'The possible values for the variables will be displayed at choosing time\n'
def evaluate_experiment(params, output_path):
    folder_name = get_folder_name(params, output_path)
    all_experiments = set([f[:11] for f in os.listdir(folder_name) if utils.check_int(f[:11])])
    all_experiments = sorted(all_experiments)

    print "Starting EVALUATION for", folder_name

    data, X_range, X, Y, Z, is_us, goal_func = datasets.load_data(params["data_name"], True, noise=False)

    all_gap_m = []
    all_closeness_m = []
    all_dist_m = []

    k = 0

    for experiment in all_experiments:
        gp, gp_list, s_list = pickle_data(folder_name, file_prefix=experiment)

        gap_measure = []
        closeness_measure = []
        dist_m = []
        dist = 0

        y_opt = data[np.argmax(data)]
        x_opt = X_range[np.argmax(data), :]

        for i in range(len(gp_list)):
            gpi = gp_list[i]
            if i % 5 == 0 or i == (len(gp_list) - 1):
                mean = np.zeros((X_range.shape[0], 1))
                var = np.zeros((X_range.shape[0], 1))
                for j in range(X_range.shape[0]):
                    mean[j], var[j] = gpi.predict(X_range[j, :][np.newaxis, :])

                x_best = X_range[np.argmax(mean), :]
                x_first = gpi.Xtrain[0, :]

                gap_measure.append(utils.gap_measure(goal_func, x_first, x_best, y_opt))
                closeness_measure.append(utils.closeness_measure(x_best, x_opt))

                #print "Gap measure:", utils.gap_measure(goal_func, x_first, x_best, y_opt)
                #print "Closeness measure:", utils.closeness_measure(x_best, x_opt)
            if params["data_name"] == "ozone" or params["data_name"] == "population":
                dist += utils.haversine(gpi.Xtrain[-1,0], gpi.Xtrain[-1,1], gpi.Xtrain[-2,0], gpi.Xtrain[-2,1])
            else:
                dist += np.linalg.norm(gpi.Xtrain[-1,:] - gpi.Xtrain[-2,:])
            dist_m.append(dist)

        all_gap_m.append(gap_measure)
        all_closeness_m.append(closeness_measure)
        all_dist_m.append(dist_m)

        k += 1
        print "Evaluation", k, "of", len(all_experiments), "done"


    with open(folder_name + "evaluation_gap_mtx", 'wb') as f:
        pickle.dump(np.matrix(all_gap_m), f)
    with open(folder_name + "evaluation_closeness_mtx", 'wb') as f:
        pickle.dump(np.matrix(all_closeness_m), f)
    with open(folder_name + "evaluation_distance_mtx", 'wb') as f:
        pickle.dump(np.matrix(all_dist_m), f)
Exemplo n.º 15
0
def validate_arguments(args):
    if "length" not in args or not (utils.check_int(args["length"]) or utils.ARG_VEC_TABLE[float](args["length"])):
        return False
    return True
Exemplo n.º 16
0
def validate_arguments(args):
    if "amount" not in args or not utils.check_int(args["amount"]):
        return False
    return True
Exemplo n.º 17
0
            print_search_result(service, index)
            index += 1
        print horizontal_bar
    except shodan.APIError, e:
        print 'Encountered error: %s' % e
        validate_still_logged_in()

    print 'Look up host from results? ',
    while (1):
        user_input = raw_input('Enter host index number (<num>/no): ')
        if any(user_input == answer for answer in utils.negative_answers):
            user_input = raw_input('Perform another search? (ENTER/no): ')
            if any(user_input == answer for answer in utils.negative_answers):
                print 'ShodanCLI shutting down.'
                sys.exit(1)
            else:
                break

        # Looking up host from results.
        val = check_int(user_input)
        if val < 0 or val > (index - 1):
            print 'Invalid index, try again.',
            continue
        host_ip = results['matches'][val]['ip_str']
        try:
            host = api.host(host_ip)
            print_host_result(host)
        except shodan.APIError, e:
            print 'Encountered error: %s' % e
            continue
Exemplo n.º 18
0
    def __getitem__(self, item):
        """
        returns an inter block value or in-block...
        :param item: [1.5, 3.5], not [1.5][3.5]
        :return:
        """
        # simplest case
        # major case - tuple
        if (type(item) == tuple) & (len(item) == 2):
            i, j = item
            nx, ny = self.shape
            # here are bounds
            if self.__boundary_condition == 'const_pressure':
                if (i == -0.5) & (j <= ny - 1) & (0 <= j) & u.check_int(j):
                    i = 0
                    out = self.__d_matrix[i, j] * self.__dy_matrix[floor(i)] * self.__k_matrix[i, j]
                    out /= self.__dx_matrix[j]
                    return 2 * out
                    # return 0
                # one of bound
                if (i == nx - 0.5) & (j <= ny - 1) & (0 <= j) & u.check_int(j):
                    i = nx - 1
                    out = self.__d_matrix[i, j] * self.__dy_matrix[j] * self.__k_matrix[i, j]
                    out /= self.__dx_matrix[i]
                    return 2 * out
                    # return 0

                # other 2 line bounds
                if (j == -0.5) & (i <= nx - 1) & (0 <= i) & u.check_int(i):
                    j = 0
                    out = self.__d_matrix[i, j] * self.__dx_matrix[i] * self.__k_matrix[i, j]
                    out /= self.__dy_matrix[j]
                    return 2 * out
                    # return 0
                # bound
                if (j == ny - 0.5) & (i <= nx - 1) & (0 <= i) & u.check_int(i):
                    j = ny - 1
                    out = self.__d_matrix[i, j] * self.__dx_matrix[i] * self.__k_matrix[i, j]
                    out /= self.__dy_matrix[j]
                    return 2 * out
                    # return 0
            elif self.__boundary_condition == 'no_flux':
                if (i == -0.5) & (j <= ny - 1) & (0 <= j) & u.check_int(j):
                    return 0
                # one of bound
                if (i == nx - 0.5) & (j <= ny - 1) & (0 <= j) & u.check_int(j):
                    return 0

                # other 2 line bounds
                if (j == -0.5) & (i <= nx - 1) & (0 <= i) & u.check_int(i):
                    return 0
                # bound
                if (j == ny - 0.5) & (i <= nx - 1) & (0 <= i) & u.check_int(i):
                    return 0

            # major cases
            if u.check_int(i) & u.check_half(j):
                out = self.__d_matrix[i, j] * self.__dx_matrix[floor(i)] * self.__k_matrix[i, j]
                out /= (self.__dy_matrix[floor(j)] + self.__dy_matrix[ceil(j)]) / 2
                return out

            elif u.check_half(i) & u.check_int(j):
                out = self.__d_matrix[i, j] * self.__dy_matrix[floor(j)] * self.__k_matrix[i, j]
                out /= (self.__dx_matrix[floor(i)] + self.__dx_matrix[ceil(i)]) / 2
                return out
            else:
                assert False, "wrong index, not int + int and a half-like int"
Exemplo n.º 19
0
def validate_arguments(args):
    if "socket" not in args or not utils.check_int(args["socket"]) or\
            int(args["socket"]) < SOCKET_TYPE_MIN or int(args["socket"]) > SOCKET_TYPE_MAX:
        return False
    return True