Exemple #1
0
    def get_cover_page():
        im_path = input()[0]
        vid_path = input()[1]
        style_layer = ["conv1_1", "conv2_1", "conv3_1", "conv4_1", "conv5_1"]
        #intializing output directory
        output_dir = "./output"
        fest = get_fest()
        image_for_style = "./" + fest + ".jpg"
        content_image = im_path

        image_width = 800
        image_height = 600
        color_channels = 3

        beta = 5  #less content ratio
        alpha = 200  #or else try 200
        l = 1e4

        mean_values = np.array([123.68, 116.779, 103.939]).reshape(
            (1, 1, 1, 3))
        vgg = scipy.io.loadmat("vgg.mat")
        layers = vgg['layers']  # 0 l 0 0 2 0 0
        """
        automate text_retreival
        """
        main()
        superimpose()
def test_once(filename):
  """Eval CIFAR-10 for a number of steps."""
  with tf.Graph().as_default() as g:
    # Get loss.
    # Create placeholder.
    
    images = tf.placeholder(tf.float32, shape=(FLAGS.batch_size, IMAGE_SIZE, IMAGE_SIZE, 3))

    loss_label, loss_domain = cifar10.inference(images)
    

    # Restore the moving average version of the learned variables for eval.
    variable_averages = tf.train.ExponentialMovingAverage(cifar10.MOVING_AVERAGE_DECAY)
    variables_to_restore = variable_averages.variables_to_restore()

    saver = tf.train.Saver(variables_to_restore)
   
    _, _, _, _, _, _, \
            x, y, domain= input.input()

    # Supplement the number of examples to multiplier of 25.
    num_of_examples = np.shape(x)[0]

    remainder = FLAGS.batch_size - int(math.ceil(num_of_examples/FLAGS.batch_size))
    index = range(num_of_examples) + [0] * remainder

    with tf.Session() as sess:
       #need to modify for test
       saver.restore(sess, filename) 
       global_step = int(filename.split('-')[1])


       # Allocate results in a list.
       losses_label = []
       losses_domain = []

       # Start the queue runners.
       step = 0
       while step + FLAGS.batch_size <= len(index):
           
           label_loss_value, domain_loss_value = sess.run([loss_label, loss_domain], feed_dict = {images:x[index[step:step+FLAGS.batch_size], :]})

           losses_label.append(label_loss_value)
           losses_domain.append(domain_loss_value)
           step = step + FLAGS.batch_size


       # Convert list of lists to numpy array.
       losses_label = np.asarray(losses_label)
       losses_domain = np.asarray(losses_domain)

       losses_label = losses_label.reshape((-1, 21))
       losses_domain = losses_domain.reshape((-1, 2))

       losses_label = losses_label[:num_of_examples, :]
       losses_domain = losses_domain[:num_of_examples, :]

  sp.savez('test.npz', losses_label = losses_label, losses_domain = losses_domain, y = y, domain = domain)

  return losses_label, losses_domain, y, domain
def eval_once(filename):
  """Eval CIFAR-10 for a number of steps."""
  with tf.Graph().as_default() as g:
    # Get loss.
    # Create placeholder.
    
    images = tf.placeholder(tf.float32, shape=(FLAGS.batch_size, IMAGE_SIZE, IMAGE_SIZE, 3))
    labels = tf.placeholder(tf.int32, shape = (FLAGS.batch_size,))
    domain_labels = tf.placeholder(tf.int32, shape = (FLAGS.batch_size,))

    #loss_label, loss_domain = cifar10.inference(images) 

    
    logits1, logits2= cifar10.inference(images)
    loss_label = cifar10.loss_without_decay(logits1, labels)
    loss_domain = cifar10.loss_without_decay(logits2, domain_labels)
    

    # Restore the moving average version of the learned variables for eval.
    variable_averages = tf.train.ExponentialMovingAverage(cifar10.MOVING_AVERAGE_DECAY)
    variables_to_restore = variable_averages.variables_to_restore()

    saver = tf.train.Saver(variables_to_restore)
  
    x_tr, y_tr, d_tr, nl_x_v, nl_y_v, nl_d_v, l_x_te, l_y_te, l_d_te = input.input()

    # Calculate losses of training, non-lifelog validation, and lifelog test.
    y_tr_loss, d_tr_loss = eval_a_dataset(saver, filename, x_tr, y_tr, d_tr, images, labels, domain_labels, loss_label, loss_domain)
    y_nl_loss, d_nl_loss = eval_a_dataset(saver, filename, nl_x_v, nl_y_v, nl_d_v, images, labels, domain_labels, loss_label, loss_domain)
    y_l_loss, d_l_loss = eval_a_dataset(saver, filename, l_x_te, l_y_te, l_d_te, images, labels, domain_labels, loss_label, loss_domain)


  return y_tr_loss, d_tr_loss, y_nl_loss, d_nl_loss, y_l_loss, d_l_loss
Exemple #4
0
def main():
    #this varibale stores all the kingdoms to a dictionary with Kingdom_name: kingdom_object pair
    all_kingdom_dictionary = get_all_kingdom_list()

    #this variable stores the sender of message
    sender = get_sender()

    # below two lines get the message list from this file
    inp = input()
    message_list = inp.read_input()

    #Here we create a list of communication object
    communication_list = []
    for destination, message in message_list:
        communication_object = communication(
            message, all_kingdom_dictionary[destination])
        communication_list.append(communication_object)

    #here we create the list of all allies
    senders_ally = []
    for communication_object in communication_list:
        if (communication_object.is_valid_message()
            ) and communication_object.getname() not in senders_ally:
            senders_ally.append(communication_object.getname())

    if len(senders_ally) >= 3:
        print(sender, end=" ")
        for ally in senders_ally:
            print(ally, end=" ")
    else:
        print("NONE")
Exemple #5
0
def search_filter(gui):
    rex = input.input(gui.cfg, "Search Filter")
    if not rex:
        return gui.set_filter(None)
    elif rex.startswith("rgx:"):
        rex = rex[4:]
    else:
        rex = "(?i).*" + re.escape(rex) + ".*"

    return gui.set_filter(only_with(rex, regex=True))
Exemple #6
0
 def __init__(self):
     self.fav = [None] * 10
     self.map = Graph("graph.gml")
     self.tts = tts.tts()
     self.gps = imu_gps.imu_gps()
     self.stop_dev = True
     self.input = input.input()
     self.key = -1
     self.out_of_path = False
     self.selfile = None
     self.attributesfile = None
     self.attr = {}
Exemple #7
0
def on_state_change(name, id, state, value):
    #logging.debug("Input %s %d state change", name, id)

    if (name, id) not in inputs_per_id:
        #logging.debug("Input not known, creating")
        i = input.input(name + "_" + str(id), name, id)
        inputs_per_id[(name, id)] = i
        inputs[i.name] = i
        iomap.Iomap[i.name] = i
        i.on_state_change(state, value)
    else:
        #logging.debug("Input known")
        inputs_per_id[(name, id)].on_state_change(state, value)
Exemple #8
0
def init():
    logging.debug("Inputs init")

    # timer is always defined input
    itimer = mytimer.timer()
    inputs_per_id[("", "Timer")] = itimer
    inputs["Timer"] = itimer

    #defined inputs in configuration
    for i in configuration.defined_inputs:
        iobj = input.input(i['name'], i['service'], i['id'])
        inputs_per_id[(i['service'], i['id'])] = iobj
        inputs[i['name']] = iobj
        iomap.Iomap[i['name']] = iobj
Exemple #9
0
    def goto(self):
        term = input(self.cfg, "Goto")
        if not term:
            return
        
        links = []
        terms = term.split(',')

        for t in terms:
            try:
                links.append(int(t))
            except:
                if t.count('-') == 1:
                    d = t.index('-')
                    a = t[:d]
                    b = t[(d+1):]
                    try:
                        a = int(a)
                        b = int(b)
                    except:
                        self.cfg.log("Unable to interpret range!")
                        return
                    for l in xrange(a,b + 1):
                        links.append(l)
                else:
                    self.cfg.log("Unable to interpret link!")
                    return

        out = "Going to link"
        if len(links) != 1:
            out += "s "
            for n in links[:-1]:
                out += "%d, " % n
            out += "and %d" % links[-1]
        else:
            out += " %d" % links[0]
        self.cfg.log(out)

        for l in links:
            self.dogoto(l)
Exemple #10
0
    def goto(self):
        term = input(self.cfg, "Goto")
        if not term:
            return

        links = []
        terms = term.split(',')

        for t in terms:
            try:
                links.append(int(t))
            except:
                if t.count('-') == 1:
                    d = t.index('-')
                    a = t[:d]
                    b = t[(d + 1):]
                    try:
                        a = int(a)
                        b = int(b)
                    except:
                        self.cfg.log("Unable to interpret range!")
                        return
                    for l in xrange(a, b + 1):
                        links.append(l)
                else:
                    self.cfg.log("Unable to interpret link!")
                    return

        out = "Going to link"
        if len(links) != 1:
            out += "s "
            for n in links[:-1]:
                out += "%d, " % n
            out += "and %d" % links[-1]
        else:
            out += " %d" % links[0]
        self.cfg.log(out)

        for l in links:
            self.dogoto(l)
def predict_once(filename):
  """Eval CIFAR-10 for a number of steps."""
  with tf.Graph().as_default() as g:
    # Get loss.
    # Create placeholder.
    
    images = tf.placeholder(tf.float32, shape=(FLAGS.batch_size, IMAGE_SIZE, IMAGE_SIZE, 3))
    labels = tf.placeholder(tf.int32, shape = (FLAGS.batch_size,))
    domain_labels = tf.placeholder(tf.int32, shape = (FLAGS.batch_size,))

    loss_label, loss_domain = cifar10.inference(images) 

    
    # Restore the moving average version of the learned variables for eval.
    variable_averages = tf.train.ExponentialMovingAverage(cifar10.MOVING_AVERAGE_DECAY)
    variables_to_restore = variable_averages.variables_to_restore()

    saver = tf.train.Saver(variables_to_restore)
  
    x_tr, y_tr, d_tr, nl_x_v, nl_y_v, nl_d_v, l_x_te, l_y_te, l_d_te = input.input()

    # Calculate predictions of training, non-lifelog validation, and lifelog test.
    tr_y_p, tr_d_p = predict_a_dataset(saver, filename, x_tr, y_tr, d_tr, images, labels, domain_labels, loss_label, loss_domain)
    nl_y_p, nl_d_p = predict_a_dataset(saver, filename, nl_x_v, nl_y_v, nl_d_v, images, labels, domain_labels, loss_label, loss_domain)
    l_y_p, l_d_p = predict_a_dataset(saver, filename, l_x_te, l_y_te, l_d_te, images, labels, domain_labels, loss_label, loss_domain)

    # Get lengths of results.
    L1 = len(tr_y_p)
    L2 = len(nl_y_p)
    L3 = len(l_y_p)

    y_tr=y_tr[:L1]
    d_tr=d_tr[:L1]
    nl_y_v=nl_y_v[:L2]
    nl_d_v=nl_d_v[:L2]
    l_y_te=l_y_te[:L3]
    l_d_te=l_d_te[:L3]

    return tr_y_p, tr_d_p, nl_y_p, nl_d_p, l_y_p, l_d_p, y_tr, d_tr, nl_y_v, nl_d_v, l_y_te, l_d_te
# 4x4

w_fc1 = tf.Variable(tf.truncated_normal(shape=[4 * 4 * 128, 512], stddev=5e-2))
b_fc1 = tf.Variable(tf.constant(0.1, shape=[512]))

h_conv5_flat = tf.reshape(Pool4, [-1, 4 * 4 * 128])
h_fc1 = tf.nn.relu(tf.matmul(h_conv5_flat, w_fc1) + b_fc1)

h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

w_fc2 = tf.Variable(tf.truncated_normal(shape=[512, 3], stddev=5e-2))
b_fc2 = tf.Variable(tf.constant(0.1, shape=[3]))
logits = tf.matmul(h_fc1_drop, w_fc2) + b_fc2
y_pred = tf.nn.softmax(logits)

x_train, y_train = input.input('train', 5000)
x_test, y_test = input.input('eval', 1000)

y_train_one_hot = tf.squeeze(tf.one_hot(y_train, 3), axis=1)
y_test_one_hot = tf.squeeze(tf.one_hot(y_test, 3), axis=1)

loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=Y_Label, logits=logits))
train_step = tf.train.RMSPropOptimizer(1e-3).minimize(loss)

correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(Y_Label, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
Exemple #13
0
import msvcrt
import time
from input import input
i = input()

def test():
    print("DOwn")

def test2():
    print("Up")

i.addKeyBinding("UP", "whileKeyDown", [test])
i.addKeyBinding("UP", "whileKeyDown", [test2])


while(True):
    #print(msvcrt.kbhit())
    #if(msvcrt.kbhit()):
    #    msvcrt.getch()
    time.sleep(0.1)
    i.update()
Exemple #14
0
import input
import regex

real = input.input(2, 2020)
sample = input.input("""1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc""")


def parse(s):
    lo, hi, char, pwd = regex.search(r"(\d+)-(\d+) (\w): (.*)", s).groups()
    lo = int(lo)
    hi = int(hi)
    # part 1
    # return letters >= lo and letters <= hi
    return (pwd[lo - 1] == char) + (pwd[hi - 1] == char) == 1


count = 0
for pwd in real:
    if parse(pwd):
        count += 1
    print(parse(pwd))
print(count)
Exemple #15
0
def main(unused_argv):
    train_dataset, validate_dataset, test_dataset = input.input(
        shuffle_files=False)
    #Text information
    info = tf.constant([
        "Batch size = %s" % f.FLAGS.batch_size,
        "Epochs = %s" % f.FLAGS.num_epochs,
        "Learning rate = %s" % f.FLAGS.learning_rate,
        "Batch normalization = No",
        "Window size = %s" % f.FLAGS.window_size, "Shuffle Files = No",
        "CNN model = %s" % f.FLAGS.cnn_model, "Shuffle Samples = YES"
    ])
    with tf.name_scope('input'):
        x = tf.placeholder(tf.float32, [
            None, input.SAMPLE_DEPTH, input.SAMPLE_HEIGHT, input.SAMPLE_WIDTH
        ])
        y_ = tf.placeholder(tf.float32, [None, 2])
        dropout_rate = tf.placeholder(tf.float32)
        is_training = tf.placeholder(tf.bool)

    with tf.name_scope('logits'):
        if f.FLAGS.cnn_model == "lenet5":
            logits = lenet5.model_fn(sample_input=x,
                                     is_training=is_training,
                                     summaries=summaries)

    with tf.name_scope('loss'):
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                                logits=logits)
        mean_cross_entropy_loss = tf.reduce_mean(cross_entropy)

        loss_summ = tf.summary.scalar('Mean_cross_entropy_loss',
                                      mean_cross_entropy_loss)
        summaries['train'].append(loss_summ)
        #summaries['validate'].append(loss_summ)

    with tf.name_scope('adam_optimizer'):
        optimizer = tf.train.AdamOptimizer(
            f.FLAGS.learning_rate).minimize(mean_cross_entropy_loss)

    with tf.name_scope('accuracy'):
        preds = tf.argmax(logits, 1)
        correct_preds = tf.argmax(y_, 1)
        equal = tf.equal(preds, correct_preds)
        training_accuracy_op = tf.reduce_mean(tf.cast(equal, tf.float32))
        summaries['train'].append(
            tf.summary.scalar('Training_Accuracy', training_accuracy_op))

    with tf.name_scope('Evaluation_Metrics'):
        tp_op = evaluate.tp(logits=logits, labels=y_)
        fp_op = evaluate.fp(logits=logits, labels=y_)
        tn_op = evaluate.tn(logits=logits, labels=y_)
        fn_op = evaluate.fn(logits=logits, labels=y_)

        tp_sum = tf.placeholder(tf.float32)
        tn_sum = tf.placeholder(tf.float32)
        fp_sum = tf.placeholder(tf.float32)
        fn_sum = tf.placeholder(tf.float32)

        precision_op = evaluate.precision(tp=tp_sum,
                                          fp=fp_sum,
                                          tn=tn_sum,
                                          fn=fn_sum)
        accuracy_op = evaluate.accuracy(tp=tp_sum,
                                        fp=fp_sum,
                                        tn=tn_sum,
                                        fn=fn_sum)
        recall_op = evaluate.recall(tp=tp_sum, fp=fp_sum, tn=tn_sum, fn=fn_sum)
        fscore_op = evaluate.fscore(tp=tp_sum, fp=fp_sum, tn=tn_sum, fn=fn_sum)

        precision_summ = tf.summary.scalar('Precision', precision_op)
        accuracy_summ = tf.summary.scalar('Accuracy', accuracy_op)
        recall_summ = tf.summary.scalar('Recall', recall_op)
        fscore_summ = tf.summary.scalar('Fscore', fscore_op)

        summaries['validate'].append(accuracy_summ)
        summaries['validate'].append(precision_summ)
        summaries['validate'].append(recall_summ)
        summaries['validate'].append(fscore_summ)

        summaries['test'].append(accuracy_summ)
        summaries['test'].append(precision_summ)
        summaries['test'].append(recall_summ)
        summaries['test'].append(fscore_summ)

    print("Saving graph to %s" % f.FLAGS.log_dir)
    train_writer = tf.summary.FileWriter(f.FLAGS.log_dir + "/train")
    validate_writer = tf.summary.FileWriter(f.FLAGS.log_dir + "/validate")
    test_writer = tf.summary.FileWriter(f.FLAGS.log_dir + "/test")
    train_writer.add_graph(tf.get_default_graph())

    train_summaries = tf.summary.merge(summaries['train'])
    validate_summaries = tf.summary.merge(summaries['validate'])
    test_summaries = tf.summary.merge(summaries['test'])

    with tf.Session() as sess:
        train_writer.add_summary(sess.run(tf.summary.text("Information",
                                                          info)))
        train_iter = train_dataset.make_initializable_iterator()
        train_next_elem = train_iter.get_next()
        sess.run(tf.global_variables_initializer())
        global_step = 0
        display_freq = 10
        validate_freq = 50
        test_freq = 50
        for epoch in range(1, f.FLAGS.num_epochs + 1):
            sess.run(train_iter.initializer)
            step_time = 0.0
            fetch_time = 0.0
            while True:
                try:
                    a = time.time()
                    global_step += 1
                    sample, label = sess.run(train_next_elem)
                    fetch_time += time.time() - a
                    #print (sample.shape, label.shape)
                    #print (label)
                    #for s in sample[0][0]:
                    #      print (s)
                    a = time.time()
                    _, summ = sess.run([optimizer, train_summaries],
                                       feed_dict={
                                           x: sample,
                                           y_: label,
                                           dropout_rate: 0.5,
                                           is_training: True
                                       })
                    train_writer.add_summary(summ, global_step)
                    step_time += time.time() - a
                except tf.errors.OutOfRangeError:
                    break

                if global_step % display_freq == 0:
                    batch_loss, batch_accuracy = sess.run(
                        [mean_cross_entropy_loss, training_accuracy_op],
                        feed_dict={
                            x: sample,
                            y_: label,
                            dropout_rate: 1.0,
                            is_training: False
                        })
                    print(
                        "Epoch {:3}\t Step {:5}:\t Loss={:.3f}, \tTraining Accuracy={:.5f} \tStep Time {:4.2f}m, Fetch Time {:4.2f}m"
                        .format(epoch, global_step, batch_loss, batch_accuracy,
                                step_time / 60, fetch_time / 60))
                    step_time = 0.0
                    fetch_time = 0.0

            #Validate and test after each epoch
            val_it = validate_dataset.make_one_shot_iterator()
            val_next_elem = val_it.get_next()
            tot_tp, tot_tn, tot_fp, tot_fn = 0, 0, 0, 0
            while True:
                try:
                    sample, label = sess.run(val_next_elem)
                    tp, fp, tn, fn = sess.run(
                        [tp_op, fp_op, tn_op, fn_op],
                        feed_dict={
                            x: sample,
                            y_: label,
                            dropout_rate: 1.0,
                            is_training: False
                        })
                except tf.errors.OutOfRangeError:
                    break
                tot_tp += tp
                tot_fp += fp
                tot_fn += fn
                tot_tn += tn
            precision, recall, accuracy, fscore, summ = sess.run([
                precision_op, recall_op, accuracy_op, fscore_op,
                validate_summaries
            ],
                                                                 feed_dict={
                                                                     tp_sum:
                                                                     tot_tp,
                                                                     tn_sum:
                                                                     tot_tn,
                                                                     fp_sum:
                                                                     tot_fp,
                                                                     fn_sum:
                                                                     tot_fn
                                                                 })
            validate_writer.add_summary(summ, global_step)
            print("Epoch %d, Step %d" % (epoch, global_step))
            print("=" * 10, "Validating Results", "=" * 10)
            print("TP: %g\nTN: %g\nFP: %g\nFN: %g" %
                  (tot_tp, tot_tn, tot_fp, tot_fn))
            print(
                "\tPrecision: %g\n\tRecall: %g\n\tF1_score: %g\n\tAccuracy: %g"
                % (precision, recall, fscore, accuracy))

            test_it = test_dataset.make_one_shot_iterator()
            test_next_elem = test_it.get_next()
            tot_tp, tot_tn, tot_fp, tot_tn = 0, 0, 0, 0
            while True:
                try:
                    sample, label = sess.run(test_next_elem)
                    tp, fp, tn, fn = sess.run(
                        [tp_op, fp_op, tn_op, fn_op],
                        feed_dict={
                            x: sample,
                            y_: label,
                            dropout_rate: 1.0,
                            is_training: False
                        })
                except tf.errors.OutOfRangeError:
                    break
                tot_tp += tp
                tot_fp += fp
                tot_fn += fn
                tot_tn += tn
            precision, recall, accuracy, fscore, summ = sess.run([
                precision_op, recall_op, accuracy_op, fscore_op, test_summaries
            ],
                                                                 feed_dict={
                                                                     tp_sum:
                                                                     tot_tp,
                                                                     tn_sum:
                                                                     tot_tn,
                                                                     fp_sum:
                                                                     tot_fp,
                                                                     fn_sum:
                                                                     tot_fn
                                                                 })

            test_writer.add_summary(summ, global_step)

            print("=" * 10, "Testing Results", "=" * 10)
            print("TP: %g\nTN: %g\nFP: %g\nFN: %g" %
                  (tot_tp, tot_tn, tot_fp, tot_fn))
            print(
                "\tPrecision: %g\n\tRecall: %g\n\tF1_score: %g\n\tAccuracy: %g"
                % (precision, recall, fscore, accuracy))
            print("=" * 10, "===============", "=" * 10)
Exemple #16
0
    def runm(self):

        time.Clock()
        from os.path import dirname, join

        here = dirname(__file__)
        scr = display.set_mode((600, 560))
        print(menu.__doc__)
        f = font.Font(join("data/FEASFBRG.ttf"), 45)
        f1 = font.Font(join("data/FEASFBRG.ttf"), 25)
        f2 = font.Font(join("data/FEASFBRG.ttf"), 15)  #'data/321impact.ttf'
        mainmenu = f.render("SNAKE GAME", 1, (0, 0, 0))
        r = mainmenu.get_rect()
        r.centerx, r.top = 300, 120
        # scr.blit(image.load(join('data/bg.png')),(0,0)) if time.get_ticks()&1 else scr.fill(-1)
        background_main = image.load("data/bg.png").convert()
        scr.blit(background_main, (0, 0))
        bg = scr.copy()
        scr.blit(mainmenu, r)
        display.flip()

        menu1 = {
            "menu": ["PLAY", "ABOUT", "EXIT"],
            "font1": f1,
            "pos": "center",
            "color1": (255, 0, 0),
            "light": 6,
            "speed": 200,
            "lag": 20,
        }
        menu2 = {
            "menu": ["1 PLAYER", "2 PLAYERS VS", "2 PLAYERS CO-OP", "2 PLAYERS NETWORK", "BACK"],
            "font1": f1,
            "font2": f,
            "pos": "center",
            "color1": (255, 0, 0),
            "light": 5,
            "speed": 200,
            "lag": 20,
        }  # "pos":'center',"color1":(50,100,150),"light":5,"speed":0,"font1":f1,"font2":f,"justify":0}
        menu3 = {
            "menu": ["AI-1", "AI-2"],
            "pos": (50, 250),
            "color1": (255, 0, 0),
            "light": 5,
            "speed": 0,
            "font1": f1,
            "font2": f,
            "justify": 0,
        }
        menu4 = {
            "menu": ["BACK"],
            "pos": (20, 450),
            "color1": (255, 0, 0),
            "light": 5,
            "speed": 0,
            "font2": f1,
            "justify": 0,
        }
        menu5 = {
            "menu": ["SERVER", "CLIENT"],
            "pos": (50, 250),
            "color1": (0, 0, 0),
            "light": 5,
            "speed": 0,
            "font1": f1,
            "font2": f,
            "justify": 0,
        }

        menus = (menu1, menu2, menu4, menu5)
        playlist = [menu1, menu2, menu4, menu5]

        resp = "re-show"
        while resp == "re-show":
            resp = menu(**menu1)[0]

        if resp == "ABOUT":
            webbrowser.open("http://www.google.com")

            display.update(scr.blit(bg, r, r))

            display.update(scr.blit(f2.render("JMI-CS3rd", 1, (200, 200, 200)), (200, 450)))
            display.update(scr.blit(f2.render("jmi.ac.in", 1, (200, 200, 200)), (205, 470)))
            display.update(scr.blit(f2.render("comfortably numb", 1, (200, 200, 200)), (235, 490)))

            #   scr.blit(background_main,(0,0))
            display.update(scr.blit(f.render("***ABOUT***", 1, (255, 255, 255)), (200, 120)))
            resp = menu(**menu4)[0]

        if resp == "BACK":
            scr.blit(background_main, (0, 0))
            display.update(scr.blit(f.render("Snake Game", 1, (255, 255, 255)), (185, 120)))
            resp = menu(**menu1)[0]

        if resp == "PLAY":
            display.update(scr.blit(bg, r, r))
            display.update(scr.blit(f.render("PLAY", 1, (255, 255, 255)), (255, 120)))
            resp = menu(**menu2)[0]
        # if resp == 'OPTION':
        #    fileopen=open('data/option.csv')
        if resp == "1 PLAYER":

            mysnake = singleplayer.Snake()
            mysnake.run()

        if resp == "2 PLAYERS VS":

            mysnake = snake.Snake()
            mysnake.run()

        if resp == "2 PLAYERS CO-OP":
            display.update(scr.blit(bg, r, r))
            display.update(scr.blit(f.render("AI", 1, (255, 255, 255)), (30, 120)))
            resp = menu(**menu3)[0]

        if resp == "2 PLAYERS NETWORK":
            display.update(scr.blit(bg, r, r))
            display.update(scr.blit(f.render("NETWORK", 1, (255, 255, 255)), (30, 120)))
            resp = menu(**menu5)[0]

        if resp == "BACK":
            scr.blit(background_main, (0, 0))
            display.update(scr.blit(f.render("SNAKE GAME", 1, (255, 255, 255)), (185, 120)))
            resp = menu(**menu1)[0]

        if resp == "CLIENT":
            import input

            myinput = input.input()
            myinput.runclient()

        #    import clientside
        #     myclient=clientside.Snake()
        #   myclient.run()
        if resp == "SERVER":
            import input

            myinput = input.input()
            myinput.runserver()

        #        import serverside
        #      myclient=serverside.Snake()
        #       myclient.run()
        if resp == "AI-1":
            fi1 = open("data/ai.txt", "w")
            fi1.write("1")
            fi1.close()
            import AI

            mysnake = AI.Snake()
            mysnake.run()
        if resp == "AI-2":
            fi2 = open("data/ai.txt", "w")
            fi2.write("2")
            fi2.close()
            import AI

            mysnake = AI.Snake()
            mysnake.run()
Exemple #17
0
    r"^([a-z0-9]+) RSHIFT (\d+) -> ([a-z]+)$": OP_RSHIFT,
    r"^NOT ([a-z0-9]+)() -> ([a-z0-9]+)$": OP_NOT,
}


def parse(s):
    for command, f in commands.items():
        search = regex.search(command, s)
        if search:
            return f, search.groups()
    print(s)
    raise RuntimeError


while True:
    for x in input.input(7, 2015):
        # print (x)
        f, params = parse(x)
        # print (f, params)
        try:
            f(*params)
            ## part 2: data['b'] = 16076
        except KeyError:
            # print("Skipping ", f, params)
            continue

    try:
        print(data['a'])
        exit()
    except KeyError:
        pass
Exemple #18
0
    def loadNetwork(self, ifile):
        """ Sets up the network topology and objects.

            Args:
                input:
                    string; input file name;
        """

        network_specs = input(ifile)

        self.realTimeGraph = RealTimeGraph(self.duration,
                                           self.interval,
                                           self.graph_type,
                                           network_specs['Hosts'],
                                           len(network_specs['Links']),
                                           len(network_specs['Flows']))

        for _ in range(network_specs['Hosts']):
            self.hosts.append(Host(self, self.newId()))
        
        for _ in range(network_specs['Routers']):
            self.routers.append(Router(self, self.newId(), self.update_int))
        
        # Initialize static routing
        if network_specs['Routers']:
            objs = self.routers + self.hosts
            routing = {
                obj.get_id(): {
                    obj2.get_id(): None for obj2 in objs} for obj in objs}
            dist = {
                obj.get_id(): {
                    obj2.get_id(): -1 for obj2 in objs} for obj in objs}

        for rate, delay, buffer_size, node1, node2 in network_specs['Links']:
            # fetch endpoints
            endpoints = []
            h, r = None, None
            # note this id here should start with 0
            for type, id in [node1, node2]:
                id -= 1
                if type == 'H':
                    endpoints.append(self.hosts[id])
                    h = self.hosts[id]
                else:
                    endpoints.append(self.routers[id])
                    r = self.routers[id]

            # create link obj
            link = Link(self, self.newId(), rate, delay, buffer_size, endpoints)

            # add link to the nodes
            for node in endpoints:
                node.add_link(link)

            if h is not None and r is not None:
                r.add_host(h)

            self.links.append(link)

        for data_amt, flow_start, src, dest, cc in network_specs['Flows']:
            src -= 1
            dest -= 1

            src_host = self.hosts[src]
            dest_host = self.hosts[dest]
            sending_flow = SendingFlow(self, self.newId(), data_amt, flow_start,
                                       dest_host.get_id(), src_host, cc)

            self.flows.append(sending_flow)
            src_host.add_flow(sending_flow)
Exemple #19
0
import os
import sys
import tensorflow as tf
import numpy as np
import scipy.io
import scipy.misc
from tkinter import *
import pandas as pd
from input import input

style_layer = ["conv1_1", "conv2_1", "conv3_1", "conv4_1", "conv5_1"]
#intializing output directory
im_path, fest = input()
output_dir = "./output"

image_for_style = "./style_images/" + fest + ".jpg"
content_image = im_path

image_width = 800
image_height = 600
color_channels = 3

beta = 5  #less content ratio
alpha = 200  #or else try 200
l = 1e4

mean_values = np.array([123.68, 116.779, 103.939]).reshape((1, 1, 1, 3))


def preprocess_input(path):
    image = scipy.misc.imread(path)
Exemple #20
0
 def test_input(self):
     self.assertEqual(input.input(1, 4, 'x**3 + x**2 + x + 1'), True)
Exemple #21
0
def h_crossover(parent1, parent2, eq, ieq, d_restrictions):
#chech if we get feasible child
	num_variables = len(parent1)
	r = random()
	child = [ 0.0 for _ in xrange(num_variables)]
 	for i in xrange(num_variables):
		child[i] = r * (parent2[i] - parent1[i]) + parent2[i]

	return child


if __name__ == "__main__":
#initial population

	data = []
	data = input(argv[1])
	num_variables = data[6]
	eq = data[1]
	ieq = data[3]
	d_restrictions = data[5]
	pop_size = 20
	population = initialize_population(argv[2] + ' ' + argv[3], pop_size)

	a_offsprings = a_crossover(population[0], population[1])
	print "arithmetical offsprings", a_offsprings

	s_offsprings = s_crossover(population[0], population[1], 1, eq, ieq, d_restrictions)
	print "simple offsprings", s_offsprings

	h_offsprings = h_crossover(population[0], population[1], eq, ieq, d_restrictions)
	print "heuristics offsprings", h_offsprings
Exemple #22
0
import input

real = input.input(2, 2015)


def box(l, w, h):
    return 2 * l * w + 2 * w * h + 2 * h * l + smallest_side(l, w, h)


def ribbon(l, w, h):
    return smallest_peri(l, w, h) + l * w * h


def smallest_peri(l, w, h):
    a, b, c = sorted([l, w, h])
    return a + b + a + b


def smallest_side(l, w, h):
    a, b, c = sorted([l, w, h])
    return a * b


assert box(2, 3, 4) == 58
assert box(1, 1, 10) == 43

c = 0
for i in real:
    str_dims = i.split('x')
    dims = [int(x) for x in str_dims]
    c = c + box(dims[0], dims[1], dims[2])
Exemple #23
0
import input

while True:
    print(input.input())

#test
Exemple #24
0
    def on_init(self):
        # (from: on_execute)
        # Puts pygame window in the middle
        os.environ['SDL_VIDEO_CENTERED'] = '1'

        # Check that Mixer was initiated. on_execute will fail/stop the program otherwise.
        if self.initpygame() is False:
            return False

        # Initialize Game Window
        # (Not Used Yet!) Video Display Object: If called before pygame.display.set_mode() can provide user's screen resolution
        # initialize window
        self._infoObject = pygame.display.Info()
        # Map Image in Background (Needs to be rendered)
        # Window Size
        resolutionx = 1000
        resolutiony = 800
        self._display_surfrender = pygame.Surface(
            (resolutionx, resolutiony))  # Map 800,600
        self._display_surf = pygame.display.set_mode((800, 600),
                                                     pygame.RESIZABLE)
        # CWD path for images
        self._cwdpath = os.getcwd()
        pygame.display.set_caption("Scuffed StarCraft")
        pygame.display.set_icon(
            pygame.image.load(os.path.join(self._cwdpath, "Images",
                                           "sc2.png")))
        # Ignore cursor for now need to figure out a way to do it on the OS probably because it lags
        # pygame.mouse.set_visible(False)
        pygame.event.set_grab(True)

        # Initialize FPS value (see .handlefps())
        # initialize other values
        self._lasttime = 0

        self._input = input.input()

        self._playerinfo = playerinfo.playerinfo()

        # Initialize Map Dimensions and Camera Set-Up
        self.map = Map.Map(resolutionx, resolutiony)

        # Initialize Overlay (UI)
        self.overlay = Overlay.Overlay()
        self.overlay.load_media(self._cwdpath)

        # Initialize Cursor/Map/Sounds and other general media
        self.load_media()

        # Initialize Troops and smaller entities
        self.load_entities()

        # Initialize Map resources
        self.load_resources()
        self.load_buildings()

        # Initialize Graph for Map
        self.load_Graph()

        # GAME OPTIONS
        self.overlay_enable = True  # Toggles overlay
        self.worldgraph_editmode = False  # Toggles being able to edit the world graph nodes
        self.worldgraph_render = False  # Toggles being able to see the world graph
        self.bspgraph_render = False  # Toggles being able to see the bsp graph

        self.clickcount = 0
        self.clickpoints = []

        pygame.mixer.music.load(
            os.path.join(self._cwdpath, "Sounds", "title_music.wav"))
        pygame.mixer.music.set_volume(0.5)
        pygame.mixer.music.play(-1)
Exemple #25
0
 def input(self, action_url, option='none'):
     dtmf = input(action_url, option)
     self.action.append(dtmf)
Exemple #26
0
sample = """939
7,13,x,x,59,x,31,19""".strip()

import input
import math
from functools import reduce


def fake_int(s):
    if s == "x":
        return -1
    else:
        return int(s)


data_raw = input.input(13)
data_raw = input.input(sample)
timestamp = int(data_raw[0])

old_nums = list(int(t) for t in data_raw[1].split(",") if t != "x")
nums = list(fake_int(t) for t in data_raw[1].split(","))

best_wait = 99999999
best_bus = None
#for num in nums:
#    missed_by = timestamp % num
#    if missed_by != 0:
#        time_to_next = num - missed_by
#    else:
#        time_to_next = 0
#    if time_to_next < best_wait:
 if "lca" in a[0]:
     lca_flag = 1
 elif "pca" in a[0]:
     pca_flag = 1
 if "svm" in a[1]:
     svm_flag = 1
 elif "adaboo" in a[1]:
     adaboo_flag = 1
 elif "rf" in a[1]:
     rf_flag = 1
 elif "nb" in a[1]:
     nb_flag = 1
 elif "bagging" in a[1]:
     bagging_flag = 1
 
 training_matrix = input.input("5k_spring_2016_training_dataset.txt", 15000, 40293)
 testing_matrix = input.input("5k_spring_2016_testing_dataset.txt", 15000, 40293)
 training_label = input.label("5k_spring_2016_label_training.txt", 15000)
 
 training_matrix, testing_matrix, combine = input_preprocess(training_matrix, testing_matrix)
 #Getting tf-idf of the matrix
 tf_idf_combine =  tf_idf.tf_idf(combine, combine)
 tf_idf_training_matrix = tf_idf.tf_idf(combine, training_matrix)
 tf_idf_testing_matrix = tf_idf.tf_idf(combine, testing_matrix)
 
 if (lca_flag):
     print("Doing LCA")
     train = lca(tf_idf_combine, tf_idf_training_matrix)
     test = lca(tf_idf_combine, tf_idf_testing_matrix)
 elif (pca_flag):
     print("Doing PCA")
Exemple #28
0
sample = """
London to Dublin = 464
London to Belfast = 518
Dublin to Belfast = 141
"""

# > 674
import input
import regex
from itertools import permutations

data = {}
for row in input.input(9, 2015):
    c1, c2, dist = regex.search(r"^(\w+) to (\w+) = (\d+)$", row).groups()
    data[(c1, c2)] = int(dist)
    data[(c2, c1)] = int(dist)

cities = set()
for d in data:
    cities.add(d[0])

mindist = -1
minpath = None
for perm in permutations(cities):
    dist = 0
    for i in range(len(cities) - 1):
        print(perm[i], perm[i + 1])
        dist = dist + data[(perm[i], perm[i + 1])]
    print(dist)
    if dist > mindist:
        minpath = perm
Exemple #29
0
class: 0-1 or 4-19
row: 0-5 or 8-19
seat: 0-13 or 16-19

your ticket:
11,12,13

nearby tickets:
3,9,18
15,1,5
5,14,9
""".strip()

import input

sample = input.input(sample_2)

real = input.input(16)

data = real
nearby_placeholder = data.index("nearby tickets:")
tickets = [[int(y) for y in x.split(',')]
           for x in data[nearby_placeholder + 1:]]

your_placeholder = data.index("your ticket:")
your_ticket = [int(y) for y in data[your_placeholder + 1].split(',')]
class_end = data.index("")
raw_classes = data[:class_end]
classes = {}
for cat in raw_classes:
    name, _, valid_text = cat.partition(": ")
Exemple #30
0
#!/usr/bin/python3

from input import input
from input import tokens
import re

sum = 0
bop = list()
s = input()
t = tokens()

all = set()

for i in tokens():
    r = t[i]

    for rr in r:
        all |= set(
            [s[:m.start()] + rr + s[m.end():] for m in re.finditer(i, s)])

print("Answer to 1: ", len(all))
Exemple #31
0
    def loadNetwork(self, ifile):
        """ Sets up the network topology and objects.

            Args:
                input:
                    string; input file name;
        """

        network_specs = input(ifile)

        self.realTimeGraph = RealTimeGraph(self.duration, self.interval,
                                           self.graph_type,
                                           network_specs['Hosts'],
                                           len(network_specs['Links']),
                                           len(network_specs['Flows']))

        for _ in range(network_specs['Hosts']):
            self.hosts.append(Host(self, self.newId()))

        for _ in range(network_specs['Routers']):
            self.routers.append(Router(self, self.newId(), self.update_int))

        # Initialize static routing
        if network_specs['Routers']:
            objs = self.routers + self.hosts
            routing = {
                obj.get_id(): {obj2.get_id(): None
                               for obj2 in objs}
                for obj in objs
            }
            dist = {
                obj.get_id(): {obj2.get_id(): -1
                               for obj2 in objs}
                for obj in objs
            }

        for rate, delay, buffer_size, node1, node2 in network_specs['Links']:
            # fetch endpoints
            endpoints = []
            h, r = None, None
            # note this id here should start with 0
            for type, id in [node1, node2]:
                id -= 1
                if type == 'H':
                    endpoints.append(self.hosts[id])
                    h = self.hosts[id]
                else:
                    endpoints.append(self.routers[id])
                    r = self.routers[id]

            # create link obj
            link = Link(self, self.newId(), rate, delay, buffer_size,
                        endpoints)

            # add link to the nodes
            for node in endpoints:
                node.add_link(link)

            if h is not None and r is not None:
                r.add_host(h)

            self.links.append(link)

        for data_amt, flow_start, src, dest, cc in network_specs['Flows']:
            src -= 1
            dest -= 1

            src_host = self.hosts[src]
            dest_host = self.hosts[dest]
            sending_flow = SendingFlow(self,
                                       self.newId(), data_amt, flow_start,
                                       dest_host.get_id(), src_host, cc)

            self.flows.append(sending_flow)
            src_host.add_flow(sending_flow)
Exemple #32
0
dotted black bags contain no other bags.
""".strip()

sample_2 = """
shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags.
"""

import input
import regex
bag_lines = input.input(sample)
bag_lines = input.input(7)


def parse_bag(s):
    outer, _, inners = s.partition(" contain ")
    outer = outer.replace(" bags", "")
    inner_options = []
    for bag in inners.split(", "):
        if bag == "no other bags.":
            continue
        num, _, descr = bag.partition(" ")
        num = int(num)
        descr = regex.sub(" bags?\.?", "", descr)
        inner_options.append([descr, num])
    return [outer, inner_options]
Exemple #33
0
train_step = tf.train.AdamOptimizer(0.005).minimize(Loss)

correct_prediction = tf.equal(tf.arg_max(OutputLayer, 1),
                              tf.arg_max(Y_Label, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # save_path = "./model/model_1.ckpt"
    # saver.restore(sess, save_path)

    for step in range(10000):
        train_images, train_labels = input.input('train', 30)
        sess.run(train_step,
                 feed_dict={
                     X: train_images,
                     Y_Label: train_labels
                 })
        if step % 10 == 0:
            eval_images, eval_labels = input.input('eval', 20)
            print(
                step,
                sess.run(accuracy,
                         feed_dict={
                             X: eval_images,
                             Y_Label: eval_labels
                         }))
Exemple #34
0
import input
import regex
import math
sample = """
1 + 2 * 3 + 4 * 5 + 6
1 + (2 * 3) + (4 * (5 + 6))
2 * 3 + (4 * 5)
5 + (8 * 3 + 9 + 3 * 4 * 3)
5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))
((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2
""".strip()

data = input.input(sample)
data = input.input(18)


def unadd(math):
    math = math.replace(" ", "")
    while True:
        s = regex.search(r"(\d+\+\d+)", math)
        if not s:
            break
        pre, post = s.span()
        new_math = math[pre:post]
        value = calc(new_math)
        math = math[:pre] + str(value) + math[post:]
    return math


def unbracket(math):
    s = regex.search(r"(\([^)(]+\))", math)
Exemple #35
0
from check import *
import subprocess as sp
import time
import tty
import sys
import os

colorama.init()

if __name__ == "__main__":
    # disabling buffering so don't have to press enter
    orig_settings = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin)
    player = Person(1, world_y)
    bossenemy = BossEnemy((world_x + 1) * frames - 2, world_y)
    input = input()
    input.hide_cursor()
    info = "SCORE = " + str(player.get_score()) + "        LIVES = " + str(
        player.get_lives()) + "       TIME LEFT= " + str(player.get_time())
    player.change_info(info)
    game_map = scenery(player, rows, columns, frames)
    start_time = time.time()
    offset = 0
    bullets = []
    global_time = time.time()
    gtime = time.time()

    while (1):
        prev_life = player.get_lives()
        if bossenemy.get_lives() <= 0 and player.get_lives(
        ) != 0 and player.get_time() != 0:
Exemple #36
0
"""7 FB -> 128 rows
3 LR -> 8 cols
seat id = row*8+col"""

import input

passes = input.input(5, 2020)


def parse_pass(s):
    s = s.replace("F", "0")
    s = s.replace("B", "1")
    s = s.replace("L", "0")
    s = s.replace("R", "1")
    row = int(s[:7], 2)
    col = int(s[7:], 2)

    return (row * 8 + col)


hi = 0
lo = 9999
seats = []
for bpass in passes:
    seat = parse_pass(bpass)
    seats.append(seat)
    hi = max(hi, seat)
    lo = min(lo, seat)

for i in range(lo, hi):
    if i not in seats:
Exemple #37
0
# not sure what this program is doing at the end, but it seems to give the right answer...

import input
import regex
real = input.input(19, 2015)
sample = input.input("""
H => HO
H => OH
O => HH

HOH
""")

irreducible = set()
raw = real
molecule = raw[-1]
trimmed = raw[:-2]
replacements = [regex.search(r'(\w+) => (\w+)', s).groups() for s in trimmed]
score = 9999


def simplify(molecule, depth=0):
    global score
    depth = depth + 1
    new_molecules = set()
    for replacement in replacements:
        targets = regex.finditer(replacement[1], molecule)
        for target in targets:
            prefix = molecule[:target.span()[0]]
            postfix = molecule[target.span()[1]:]
            new_molecule = prefix + replacement[0] + postfix
Exemple #38
0
    def runm(self):
        
        time.Clock()
        from os.path import dirname,join
       
        here = dirname(__file__)
        scr = display.set_mode((600,560))
        print(menu.__doc__)
        f = font.Font(join('data/FEASFBRG.ttf'),45)
        f1 = font.Font(join('data/FEASFBRG.ttf'),25)
        f2 = font.Font(join('data/FEASFBRG.ttf'),15)#'data/321impact.ttf'
        mainmenu = f.render('ANGRY SNAKES',1,(255,255,255))
        r = mainmenu.get_rect()
        r.centerx,r.top = 300,120
        #scr.blit(image.load(join('data/bg.png')),(0,0)) if time.get_ticks()&1 else scr.fill(-1)
        background_main = image.load('data/bg.png').convert()
        scr.blit(background_main,(0,0))
        bg = scr.copy()
        scr.blit(mainmenu,r)
        display.flip()
        
        menu1 = {"menu":['PLAY','ABOUT','EXIT'],"font1":f1,"pos":'center',"color1":(154,180,61),"light":6,"speed":200,"lag":20}
        menu2 = {"menu":['1 PLAYER','2 PLAYERS VS' ,'2 PLAYERS CO-OP','2 PLAYERS NETWORK','BACK'],"font1":f1,"font2":f,"pos":'center',"color1":(154,180,61),"light":5,"speed":200,"lag":20}#"pos":'center',"color1":(50,100,150),"light":5,"speed":0,"font1":f1,"font2":f,"justify":0}
        menu3 = {"menu":['AI-1','AI-2'],"pos":(50,250),"color1":(154,180,61),"light":5,"speed":0,"font1":f1,"font2":f,"justify":0}
        menu4 = {"menu":['BACK'],"pos":(20,450),"color1":(154,180,61),"light":5,"speed":0,"font2":f1,"justify":0}
        menu5 = {"menu":['SERVER','CLIENT'],"pos":(50,250),"color1":(154,180,61),"light":5,"speed":0,"font1":f1,"font2":f,"justify":0}

        menus = (menu1,menu2,menu4,menu5)
        playlist = [menu1,menu2,menu4,menu5]
        
        resp = "re-show"
        while resp == "re-show":
            resp = menu(**menu1)[0]
        
        
        
        
        if resp == 'ABOUT':
            webbrowser.open("http://194.225.238.146/~kharazi/")
            
            display.update(scr.blit(bg,r,r))
           
            display.update(scr.blit(f2.render('@author: vahid kharazi',1,(200,200,200)),(200,450)))
            display.update(scr.blit(f2.render('*****@*****.**',1,(200,200,200)),(205,470)))
            display.update(scr.blit(f2.render('Winter 1390',1,(200,200,200)),(235,490)))
            
         #   scr.blit(background_main,(0,0))
            display.update(scr.blit(f.render('***ABOUT***',1,(255,255,255)),(200,120)))
            resp = menu(**menu4)[0]
        
        
        if resp == 'BACK':
            scr.blit(background_main,(0,0))
            display.update(scr.blit(f.render('ANGRY SNAKES',1,(255,255,255)),(185,120)))
            resp = menu(**menu1)[0]
            
        if resp == 'PLAY':
            display.update(scr.blit(bg,r,r))
            display.update(scr.blit(f.render('PLAY',1,(255,255,255)),(255,120)))
            resp = menu(**menu2)[0]
       # if resp == 'OPTION':
        #    fileopen=open('data/option.csv')
        if resp == '1 PLAYER':
            
            mysnake = singleplayer.Snake()    
            mysnake.run()
     
        if resp == '2 PLAYERS VS':
            
            mysnake = snake.Snake()    
            mysnake.run()
    
        if resp == '2 PLAYERS CO-OP':
            display.update(scr.blit(bg,r,r))
            display.update(scr.blit(f.render('AI',1,(255,255,255)),(30,120)))
            resp = menu(**menu3)[0]
            
        

           
        if resp == '2 PLAYERS NETWORK':
            display.update(scr.blit(bg,r,r))
            display.update(scr.blit(f.render('NETWORK',1,(255,255,255)),(30,120)))
            resp = menu(**menu5)[0]
            
        if resp == 'BACK':
            scr.blit(background_main,(0,0))
            display.update(scr.blit(f.render('ANGRY SNAKES',1,(255,255,255)),(185,120)))
            resp = menu(**menu1)[0]
                        
        if resp == 'CLIENT':
            import input
            myinput = input.input()    
            myinput.runclient()

        #    import clientside
       #     myclient=clientside.Snake()
         #   myclient.run()
        if resp == 'SERVER':
            import input
            myinput = input.input()    
            myinput.runserver()

    #        import serverside
      #      myclient=serverside.Snake()
     #       myclient.run()
        if resp == 'AI-1':
            fi1=open('data/ai.txt','w')
            fi1.write('1')
            fi1.close()
            import AI
            mysnake = AI.Snake()    
            mysnake.run()
        if resp == 'AI-2':
            fi2=open('data/ai.txt','w')
            fi2.write('2')
            fi2.close()
            import AI
            mysnake = AI.Snake()    
            mysnake.run()