text:
Q: Why is the accurcy of my neural network not improving The accurcy of my neural network stop at 70% and not inproving. Please help me. Below is my code.
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler

data = pd.read_csv("data.csv", sep='|')
nonlinearitiesactFunction = {'sigmoid':tf.sigmoid, 'tanh':tf.tanh, 'elu':tf.nn.elu, 'softplus':tf.nn.softplus, 'softsign':tf.nn.softsign}
linearitiesactFunction = {'relu':tf.nn.relu, 'relu6':tf.nn.relu6}
clFunction = {'sigmoidCrossEntropy':tf.nn.sigmoid_cross_entropy_with_logits, 'softmax':tf.nn.softmax, 'softmaxCrossEntropy':tf.nn.softmax_cross_entropy_with_logits}
opt = {'Adam':tf.train.AdamOptimizer, 'GradientDescent':tf.train.GradientDescentOptimizer}

def retrieveXAndY():
    X = data.drop(['Name', 'md5', 'legitimate'], axis=1 ).as_matrix()
    y = data['legitimate'].as_matrix()
    return X, y

def addLayer(input, inSize, outSize, activationFunction = None):
    hiddenlay = {'weights':tf.Variable(tf.random_normal([inSize, outSize])),'biases':tf.Variable(tf.random_normal([outSize]))}
    hl = tf.add(tf.matmul(input,hiddenlay['weights']), hiddenlay['biases'])

    if activationFunction == None:
      output = hl
  else:
      output = activationFunction(hl)
    return output

 def costAndOpt(y,output, n_samples, learning_rate, optFunction = None):
  cost = tf.reduce_sum(tf.pow(y - output, 2))/(2*n_samples)
  optimizer = optFunction(learning_rate).minimize(cost)

  return cost, optimizer

def fiveLayer(x, n_nodes_hl1, n_nodes_hl2, n_nodes_hl3, n_nodes_hl4, n_nodes_hl5, n_output, activationFunction, optFunction):
    l1 = addLayer(x, n_feature,n_nodes_hl1,activationFunction)
    l2 = addLayer(l1, n_nodes_hl1,n_nodes_hl2,activationFunction)
    l3 = addLayer(l2, n_nodes_hl2,n_nodes_hl3,activationFunction)
    l4 = addLayer(l3, n_nodes_hl3,n_nodes_hl4,activationFunction)
    l5 = addLayer(l4, n_nodes_hl4,n_nodes_hl5,activationFunction)
    output = addLayer(l5, n_nodes_hl5, n_output, activationFunction)

    cost, optimizer = costAndOpt(y,output, n_samples, learning_rate, optFunction)

    return cost, optimizer

if __name__ == '__main__':

     inputX, inputY = retrieveXAndY()

#Normalization
    pca_input = PCA(n_components = int(inputX.shape[1]/2))
    inputX = pca_input.fit_transform(inputX)
    inputX = MinMaxScaler().fit_transform(inputX)

    inputY = inputY.reshape([-1,1])
    n_samples = inputY.size
    n_feature = inputX.shape[1]
    n_node = 40
    display_step = 50
    learning_rate=0.01

    n_nodes_hl1 = n_node
    n_nodes_hl2 = n_node
    n_nodes_hl3 = n_node
    n_nodes_hl4 = n_node
    n_nodes_hl5 = n_node
    n_output = 1 #number of output

#input data
    x = tf.placeholder(tf.float32,[None,n_feature]) #feature
    y = tf.placeholder(tf.float32,[None,n_output]) #label#cost, optimizer

cost, optimizer = fiveLayer(x, n_nodes_hl1, n_nodes_hl2, n_nodes_hl3, n_nodes_hl4, n_nodes_hl5, n_output, nonlinearitiesactFunction['softsign'], opt['Adam'])
cost1, optimizer1 = fiveLayer(x, n_nodes_hl1, n_nodes_hl2, n_nodes_hl3, n_nodes_hl4, n_nodes_hl5, n_output, clFunction['softmax'], opt['Adam'])
cost2, optimizer2 = fiveLayer(x, n_nodes_hl1, n_nodes_hl2, n_nodes_hl3, n_nodes_hl4, n_nodes_hl5, n_output, nonlinearitiesactFunction['softsign'], opt['Adam'])
cost3, optimizer3 = fiveLayer(x, n_nodes_hl1, n_nodes_hl2, n_nodes_hl3, n_nodes_hl4, n_nodes_hl5, n_output, nonlinearitiesactFunction['sigmoid'], opt['Adam'])
cost4, optimizer4 = fiveLayer(x, n_nodes_hl1, n_nodes_hl2, n_nodes_hl3, n_nodes_hl4, n_nodes_hl5, n_output, nonlinearitiesactFunction['tanh'], opt['Adam'])
cost5, optimizer5 = fiveLayer(x, n_nodes_hl1, n_nodes_hl2, n_nodes_hl3, n_nodes_hl4, n_nodes_hl5, n_output, nonlinearitiesactFunction['elu'], opt['Adam'])

hm_epochs = 2000

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for i in range(hm_epochs):
    # Take a gradient descent step using our inputs and labels
        _,c = sess.run([optimizer,cost],feed_dict={x: inputX, y: inputY})
        epoch_loss = 0
        if (i) % display_step == 0:
            epoch_loss += c
            print "Softmax Training step:", i, "cost=", c, 'loss=', epoch_loss  #, \"W=", sess.run(W), "b=", sess.run(b)

    mse = cost.eval({x: inputX, y: inputY})
    acc = 1-np.sqrt(mse)
    print "Acc = ", acc, "\n"

    for i in range(hm_epochs):
    # Take a gradient descent step using our inputs and labels
        _,c1 = sess.run([optimizer1,cost1],feed_dict={x: inputX, y: inputY})
        epoch_loss1 = 0
        if (i) % display_step == 0:
            epoch_loss1 += c1
            print "Softsign Training step:", i, "cost=", c1, 'loss=', epoch_loss1  #, \"W=", sess.run(W), "b=", sess.run(b)

    mse1 = cost1.eval({x: inputX, y: inputY})
    acc1 = 1-np.sqrt(mse1)
    print "Acc = ", acc1, "\n"

    for i in range(hm_epochs):
    # Take a gradient descent step using our inputs and labels
        _,c2 = sess.run([optimizer2,cost2],feed_dict={x: inputX, y: inputY})
        epoch_loss2 = 0
        if (i) % display_step == 0:
            epoch_loss2 += c2
            print "Sigmoid Training step:", i, "cost=", c2, 'loss=', epoch_loss2  #, \"W=", sess.run(W), "b=", sess.run(b)

    mse2 = cost2.eval({x: inputX, y: inputY})
    acc2 = 1-np.sqrt(mse2)
    print "Acc = ", acc2, "\n"

    for i in range(hm_epochs):
    # Take a gradient descent step using our inputs and labels
        _,c3 = sess.run([optimizer3,cost3],feed_dict={x: inputX, y: inputY})
        epoch_loss3 = 0
        if (i) % display_step == 0:
            epoch_loss3 += c3
            print "tanh Training step:", i, "cost=", c3, 'loss=', epoch_loss3  #, \"W=", sess.run(W), "b=", sess.run(b)

    mse3 = cost3.eval({x: inputX, y: inputY})
    acc3 = 1-np.sqrt(mse3)
    print "Acc = ", acc3, "\n"

    for i in range(hm_epochs):
    # Take a gradient descent step using our inputs and labels
        _,c4 = sess.run([optimizer4,cost4],feed_dict={x: inputX, y: inputY})
        epoch_loss4 = 0
        if (i) % display_step == 0:
            epoch_loss4 += c4
            print "elu Training step:", i, "cost=", c4, 'loss=', epoch_loss4  #, \"W=", sess.run(W), "b=", sess.run(b)

    mse4 = cost4.eval({x: inputX, y: inputY})
    acc4 = 1-np.sqrt(mse4)
    print "Acc = ", acc4, "\n"

I am using a dataset with 60000 records. Below is example of part of the dataset or can download the dataset from https://archive.ics.uci.edu/ml/datasets/Detect+Malacious+Executable(AntiVirus):
inputX = array([[  3.32000000e+02,   2.24000000e+02,   8.45000000e+03,
          8.00000000e+00,   0.00000000e+00,   5.32480000e+04,
          1.63840000e+04,   0.00000000e+00,   5.40480000e+04,
          4.09600000e+03,   5.73440000e+04,   2.08594534e+09,
          4.09600000e+03,   4.09600000e+03,   4.00000000e+00,
          0.00000000e+00,   8.00000000e+00,   0.00000000e+00,
          4.00000000e+00,   0.00000000e+00,   7.37280000e+04,
          4.09600000e+03,   1.20607000e+05,   2.00000000e+00,
          3.20000000e+02,   1.04857600e+06,   4.09600000e+03,
          1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
          1.60000000e+01,   4.00000000e+00,   2.70373594e+00,
          1.05637876e+00,   6.22819008e+00,   1.63840000e+04,
          4.09600000e+03,   5.32480000e+04,   1.59390000e+04,
          9.92000000e+02,   5.28640000e+04,   6.00000000e+00,
          1.37000000e+02,   8.10000000e+01,   2.50000000e+01,
          1.00000000e+00,   3.52426821e+00,   3.52426821e+00,
          3.52426821e+00,   8.92000000e+02,   8.92000000e+02,
          8.92000000e+02,   7.20000000e+01,   1.60000000e+01],
       [  3.32000000e+02,   2.24000000e+02,   8.45000000e+03,
          8.00000000e+00,   0.00000000e+00,   5.27360000e+04,
          1.12640000e+04,   0.00000000e+00,   5.35300000e+04,
          4.09600000e+03,   5.73440000e+04,   2.08699392e+09,
          4.09600000e+03,   5.12000000e+02,   4.00000000e+00,
          0.00000000e+00,   8.00000000e+00,   0.00000000e+00,
          4.00000000e+00,   0.00000000e+00,   7.37280000e+04,
          1.02400000e+03,   8.92300000e+04,   2.00000000e+00,
          3.20000000e+02,   1.04857600e+06,   4.09600000e+03,
          1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
          1.60000000e+01,   4.00000000e+00,   4.31899422e+00,
      3.30769150e+00,   6.15499505e+00,   1.42080000e+04,
      1.02400000e+03,   5.27360000e+04,   1.57382500e+04,
      9.92000000e+02,   5.22730000e+04,   6.00000000e+00,
      1.33000000e+02,   8.10000000e+01,   2.50000000e+01,
      1.00000000e+00,   3.54207119e+00,   3.54207119e+00,
      3.54207119e+00,   8.92000000e+02,   8.92000000e+02,
      8.92000000e+02,   7.20000000e+01,   1.60000000e+01],
   [  3.32000000e+02,   2.24000000e+02,   8.45000000e+03,
      8.00000000e+00,   0.00000000e+00,   4.09600000e+04,
      2.04800000e+04,   0.00000000e+00,   2.66080000e+04,
      4.09600000e+03,   4.50560000e+04,   1.92151552e+09,
      4.09600000e+03,   4.09600000e+03,   4.00000000e+00,
      0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      4.00000000e+00,   0.00000000e+00,   6.55360000e+04,
      4.09600000e+03,   1.21734000e+05,   2.00000000e+00,
      3.20000000e+02,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   5.00000000e+00,   3.58061262e+00,
      8.04176679e-02,   6.23193618e+00,   1.22880000e+04,
      4.09600000e+03,   4.09600000e+04,   1.04442000e+04,
      9.64000000e+02,   3.76480000e+04,   2.00000000e+00,
      6.80000000e+01,   0.00000000e+00,   1.12000000e+02,
      6.00000000e+00,   3.00438262e+00,   2.40651198e+00,
      3.59262288e+00,   6.10333333e+02,   1.24000000e+02,
      1.41200000e+03,   7.20000000e+01,   1.60000000e+01],
   [  3.32000000e+02,   2.24000000e+02,   2.58000000e+02,
      1.10000000e+01,   0.00000000e+00,   3.54816000e+05,
      2.57024000e+05,   0.00000000e+00,   1.83632000e+05,
      4.09600000e+03,   3.60448000e+05,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   5.00000000e+00,
      1.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      5.00000000e+00,   1.00000000e+00,   6.26688000e+05,
      1.02400000e+03,   0.00000000e+00,   2.00000000e+00,
      3.30880000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   5.00000000e+00,   4.59039653e+00,
      2.37894684e+00,   6.29682587e+00,   1.20524800e+05,
      7.68000000e+03,   3.54816000e+05,   1.22148600e+05,
      1.64680000e+04,   3.54799000e+05,   7.00000000e+00,
      1.38000000e+02,   0.00000000e+00,   0.00000000e+00,
      7.00000000e+00,   3.91441476e+00,   1.44168828e+00,
      7.67709054e+00,   7.29842857e+03,   1.60000000e+01,
      2.84380000e+04,   7.20000000e+01,   0.00000000e+00],
   [  3.32000000e+02,   2.24000000e+02,   2.71000000e+02,
      6.00000000e+00,   0.00000000e+00,   2.40640000e+04,
      1.64864000e+05,   1.02400000e+03,   1.25380000e+04,
      4.09600000e+03,   2.86720000e+04,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   4.00000000e+00,
      0.00000000e+00,   6.00000000e+00,   0.00000000e+00,
      4.00000000e+00,   0.00000000e+00,   2.41664000e+05,
      1.02400000e+03,   0.00000000e+00,   2.00000000e+00,
      3.27680000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   5.00000000e+00,   4.10454072e+00,
      0.00000000e+00,   6.44010555e+00,   6.75840000e+03,
      0.00000000e+00,   2.40640000e+04,   4.62608000e+04,
      3.14400000e+03,   1.54712000e+05,   8.00000000e+00,
      1.55000000e+02,   1.00000000e+00,   0.00000000e+00,
      6.00000000e+00,   3.19910735e+00,   1.97133529e+00,
      5.21481585e+00,   4.52000000e+02,   3.40000000e+01,
      9.58000000e+02,   0.00000000e+00,   1.50000000e+01],
   [  3.32000000e+02,   2.24000000e+02,   2.58000000e+02,
      1.00000000e+01,   0.00000000e+00,   1.18784000e+05,
      3.81952000e+05,   0.00000000e+00,   5.99140000e+04,
      4.09600000e+03,   1.22880000e+05,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   5.00000000e+00,
      1.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      5.00000000e+00,   1.00000000e+00,   5.20192000e+05,
      1.02400000e+03,   5.58287000e+05,   2.00000000e+00,
      3.30880000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   5.00000000e+00,   5.66240790e+00,
      4.18369159e+00,   7.96187140e+00,   1.00147200e+05,
      9.21600000e+03,   3.34848000e+05,   1.01559800e+05,
      9.36800000e+03,   3.34440000e+05,   7.00000000e+00,
      1.14000000e+02,   0.00000000e+00,   0.00000000e+00,
      1.80000000e+01,   6.53094643e+00,   2.45849223e+00,
      7.99268848e+00,   1.85234444e+04,   4.80000000e+01,
      3.39450000e+04,   7.20000000e+01,   1.40000000e+01],
   [  3.32000000e+02,   2.24000000e+02,   2.58000000e+02,
      1.00000000e+01,   0.00000000e+00,   1.74592000e+05,
      3.00032000e+05,   0.00000000e+00,   1.17140000e+05,
      4.09600000e+03,   1.80224000e+05,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   5.00000000e+00,
      1.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      5.00000000e+00,   1.00000000e+00,   4.87424000e+05,
      1.02400000e+03,   5.13173000e+05,   2.00000000e+00,
      3.30880000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   5.00000000e+00,   5.73547047e+00,
      4.75826034e+00,   7.36431335e+00,   9.30816000e+04,
      1.53600000e+04,   1.92000000e+05,   9.46988000e+04,
      2.15000000e+04,   1.91664000e+05,   1.10000000e+01,
      2.54000000e+02,   1.50000000e+01,   0.00000000e+00,
      1.50000000e+01,   5.73239307e+00,   2.85236422e+00,
      7.98772639e+00,   1.27061333e+04,   1.18000000e+02,
      6.05000000e+04,   7.20000000e+01,   1.40000000e+01],
   [  3.32000000e+02,   2.24000000e+02,   2.58000000e+02,
      9.00000000e+00,   0.00000000e+00,   4.75648000e+05,
      3.48672000e+05,   0.00000000e+00,   3.19769000e+05,
      4.09600000e+03,   4.83328000e+05,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   5.00000000e+00,
      0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      5.00000000e+00,   0.00000000e+00,   8.56064000e+05,
      1.02400000e+03,   1.82072586e+09,   2.00000000e+00,
      3.30880000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   5.00000000e+00,   5.13993423e+00,
      4.48079036e+00,   6.55814891e+00,   1.64864000e+05,
      1.38240000e+04,   4.75648000e+05,   1.68145200e+05,
      3.08400000e+04,   4.75580000e+05,   1.40000000e+01,
      4.21000000e+02,   1.50000000e+01,   0.00000000e+00,
      5.90000000e+01,   2.82782573e+00,   9.60953136e-01,
      7.21232881e+00,   2.63703390e+03,   2.00000000e+01,
      6.76240000e+04,   7.20000000e+01,   0.00000000e+00],
   [  3.32000000e+02,   2.24000000e+02,   2.59000000e+02,
      9.00000000e+00,   0.00000000e+00,   1.57696000e+05,
      6.24640000e+04,   0.00000000e+00,   6.70150000e+04,
      4.09600000e+03,   1.63840000e+05,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   5.00000000e+00,
      0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      5.00000000e+00,   0.00000000e+00,   2.33472000e+05,
      1.02400000e+03,   2.72988000e+05,   2.00000000e+00,
      3.30240000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   4.00000000e+00,   4.81988481e+00,
      2.97736539e+00,   6.48512410e+00,   5.50400000e+04,
      3.58400000e+03,   1.57696000e+05,   5.56267500e+04,
      6.70000000e+03,   1.57297000e+05,   2.00000000e+00,
      7.60000000e+01,   0.00000000e+00,   0.00000000e+00,
      1.30000000e+01,   3.94329633e+00,   1.81444345e+00,
      6.12204520e+00,   2.70815385e+03,   1.32000000e+02,
      9.64000000e+03,   7.20000000e+01,   1.40000000e+01],
   [  3.32000000e+02,   2.24000000e+02,   2.59000000e+02,
      8.30000000e+01,   8.20000000e+01,   7.24992000e+05,
      2.30604800e+06,   0.00000000e+00,   4.24345600e+06,
      3.52256000e+06,   4.30899200e+06,   4.19430400e+06,
      4.09600000e+03,   4.09600000e+03,   5.00000000e+00,
      0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      5.00000000e+00,   0.00000000e+00,   6.70924800e+06,
      4.09600000e+03,   3.07704700e+06,   2.00000000e+00,
      3.27680000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   9.00000000e+00,   3.78312500e+00,
      0.00000000e+00,   7.99951830e+00,   3.36782222e+05,
      0.00000000e+00,   1.88416000e+06,   7.44182333e+05,
      2.27200000e+03,   3.06129900e+06,   4.00000000e+00,
      2.43000000e+02,   0.00000000e+00,   0.00000000e+00,
      2.10000000e+01,   3.98746295e+00,   2.64215931e+00,
      6.47369968e+00,   1.42880000e+04,   7.60000000e+01,
      2.70376000e+05,   0.00000000e+00,   0.00000000e+00],
   [  3.32000000e+02,   2.24000000e+02,   2.58000000e+02,
      1.00000000e+01,   0.00000000e+00,   1.20320000e+05,
      3.85024000e+05,   0.00000000e+00,   6.15780000e+04,
      4.09600000e+03,   1.26976000e+05,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   5.00000000e+00,
      1.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      5.00000000e+00,   1.00000000e+00,   5.28384000e+05,
      1.02400000e+03,   5.66330000e+05,   2.00000000e+00,
      3.30880000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   5.00000000e+00,   5.64644365e+00,
      4.11726412e+00,   7.96277585e+00,   1.01068800e+05,
      9.72800000e+03,   3.30752000e+05,   1.02623800e+05,
      9.40400000e+03,   3.39652000e+05,   3.00000000e+00,
      8.90000000e+01,   0.00000000e+00,   0.00000000e+00,
      6.00000000e+00,   3.72982391e+00,   2.45849223e+00,
      5.31755236e+00,   2.73950000e+03,   4.80000000e+01,
      9.64000000e+03,   7.20000000e+01,   1.50000000e+01],
   [  3.32000000e+02,   2.24000000e+02,   2.59000000e+02,
      1.00000000e+01,   0.00000000e+00,   2.33984000e+05,
      1.37779200e+06,   0.00000000e+00,   9.31200000e+04,
      4.09600000e+03,   2.41664000e+05,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   5.00000000e+00,
      1.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      5.00000000e+00,   1.00000000e+00,   1.63020800e+06,
      1.02400000e+03,   1.66150900e+06,   2.00000000e+00,
      3.32800000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   3.00000000e+00,   5.46068132e+00,
      3.13962777e+00,   7.09009944e+00,   5.37258667e+05,
      5.63200000e+03,   1.37216000e+06,   5.39602667e+05,
      1.33160000e+04,   1.37185600e+06,   1.00000000e+00,
      8.00000000e+01,   0.00000000e+00,   0.00000000e+00,
      1.80000000e+01,   4.32832189e+00,   2.32321967e+00,
      7.06841290e+00,   7.61582778e+04,   9.00000000e+00,
      1.34273500e+06,   7.20000000e+01,   1.90000000e+01],
   [  3.32000000e+02,   2.24000000e+02,   2.71000000e+02,
      6.00000000e+00,   0.00000000e+00,   4.91520000e+04,
      5.61152000e+05,   0.00000000e+00,   3.38800000e+04,
      4.09600000e+03,   5.32480000e+04,   4.19430400e+06,
      4.09600000e+03,   4.09600000e+03,   4.00000000e+00,
      0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      4.00000000e+00,   0.00000000e+00,   6.14400000e+05,
      4.09600000e+03,   0.00000000e+00,   2.00000000e+00,
      0.00000000e+00,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   4.00000000e+00,   3.69925758e+00,
      0.00000000e+00,   6.48297395e+00,   1.94600000e+04,
      1.60000000e+01,   4.91520000e+04,   1.50074000e+05,
      1.60000000e+01,   5.48460000e+05,   4.00000000e+00,
      1.19000000e+02,   1.00000000e+01,   0.00000000e+00,
      0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      0.00000000e+00,   0.00000000e+00,   0.00000000e+00],
   [  3.32000000e+02,   2.24000000e+02,   2.58000000e+02,
      1.00000000e+01,   0.00000000e+00,   2.91840000e+04,
      4.45952000e+05,   1.68960000e+04,   1.48190000e+04,
      4.09600000e+03,   3.68640000e+04,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   5.00000000e+00,
      0.00000000e+00,   6.00000000e+00,   0.00000000e+00,
      5.00000000e+00,   0.00000000e+00,   1.76537600e+06,
      1.02400000e+03,   5.94294000e+05,   2.00000000e+00,
      3.41120000e+04,   1.04857600e+06,   4.09600000e+03,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   6.00000000e+00,   3.76419176e+00,
      0.00000000e+00,   6.47970818e+00,   7.93600000e+03,
      0.00000000e+00,   2.91840000e+04,   2.92339333e+05,
      2.53600000e+03,   1.28204800e+06,   8.00000000e+00,
      1.71000000e+02,   1.00000000e+00,   0.00000000e+00,
      6.00000000e+00,   3.15203588e+00,   2.16096405e+00,
      5.21367450e+00,   3.54333333e+02,   2.00000000e+01,
      7.44000000e+02,   0.00000000e+00,   0.00000000e+00],
   [  3.32000000e+02,   2.24000000e+02,   3.31670000e+04,
      2.00000000e+00,   2.50000000e+01,   3.78880000e+04,
      1.53600000e+04,   0.00000000e+00,   4.00000000e+04,
      4.09600000e+03,   4.50560000e+04,   4.19430400e+06,
      4.09600000e+03,   5.12000000e+02,   1.00000000e+00,
      0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
      4.00000000e+00,   0.00000000e+00,   8.19200000e+04,
      1.02400000e+03,   6.78554440e+07,   2.00000000e+00,
      0.00000000e+00,   1.04857600e+06,   1.63840000e+04,
      1.04857600e+06,   4.09600000e+03,   0.00000000e+00,
      1.60000000e+01,   8.00000000e+00,   2.33301385e+00,
      0.00000000e+00,   6.63664803e+00,   6.65600000e+03,
      0.00000000e+00,   3.78880000e+04,   7.19800000e+03,
      8.00000000e+00,   3.77320000e+04,   8.00000000e+00,
      9.60000000e+01,   0.00000000e+00,   0.00000000e+00,
      1.40000000e+01,   3.42918455e+00,   2.41356665e+00,
      5.05007355e+00,   7.17142857e+02,   4.40000000e+01,
      2.21600000e+03,   0.00000000e+00,   1.50000000e+01]])

inputY = array([ 1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0., 0.,  0.])


text:
Q: Why am I only getting one take! from this channel? Trying to understand how channels work; I don't get why my take! only works once in this REPL sequence, even though I try multiple puts along the way:
cplay.core> (def h (chan))
#'cplay.core/h
cplay.core> (go (put! h "hello"))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@4afdd6ba>
cplay.core> (go (take! h (fn [x] (println x))))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@9fe39a1>
cplay.core> hello

cplay.core> (go (take! h (fn [x] (println x))))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@206564e9>
cplay.core> (go (put! h "hello"))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@6c0ec468>
cplay.core> (go (take! h (fn [x] (println x))))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@60c85184>
cplay.core> (go (take! h (fn [x] (println x))))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@3edc08c3>
cplay.core> (go (take! h (fn [x] (println x))))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@6a7b295f>
cplay.core> (go (put! h "hello"))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@60331d8b>
cplay.core> (go (take! h (fn [x] (println x))))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@557c3bce>
cplay.core> (go (put! h "hello"))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@203fdcfb>
cplay.core> (go (put! h "hello"))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@ed11c1>
cplay.core> (go (take! h (fn [x] (println x))))
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@6c7ea146>
cplay.core>

Is it because I then take from the channel several times in succession when nothing is on the channel, thereby leaving "voids" that are filled by subsequent puts until the channel somehow gets back to and even number of puts and takes?

A: The println behavior is quiet weird in this async scenario.
If your last invocation is the "take!" fn then you'll end up with the print result in your repl, but is four last invocation is the "put!" fn  then you have to find the print result on the nrepl-server terminal.
This behavior and necessary workspace it's introduced on the beginning of Timothy Baldridge video of core.async
And here one screenshot of my 2 frames in emacs, one for the nrepl and the other for the nrepl-server output

A: Don't wrap put! and take! with go. Inside go you want <! or !>:
user=> (require '[clojure.core.async :refer (chan put! take! <! >!)])
nil
user=> (def h (chan))
#'user/h
user=> (put! h "hello")
true
user=> (take! h println)
hello
nil
user=> (put! h "hello")
true
user=> (take! h println)
hello
nil
user=> (put! h "hello")
true
user=> (take! h println)
hello
nil
user=> (put! h "hello")
true
user=> (take! h println)
hello
nil
user=> (take! h println)
nil
user=> (put! h "hello")
hello
true

redpajama_set_name: RedPajamaStackExchange


text:
Q: zsh $fpath file with multiple functions In order to load functions in zsh, everything I read says that each function needs to be in separate file and that file needs to be the same name last the function. the path to that function then also needs to be in your $fpath.
Is it possible to have multiple functions in one file in $fpath?
For instance:
    # rsync transfer for DAMS uploads
function rsyncDAMS () {
    rsync -avvPhi --no-p --stats "${@}"
}
export -f rsyncDAMS

    # general rsync transfer
function rsyncT () {
    rsync -avvPhi --stats "${@}"
}
export -f rsyncT

    # general rsync transfer with deletion of source files
function rsyncD () {
    rsync -avvPhi --remove-source-files --stats "${@}"
}
export -f rsyncD

instead of three separate files called rsyncDAMS, rsyncT and rsyncD
could I have one file called rsync_functions with all three of those functions in it and be able to call each function separately by its name? I'd put the ```rsync`` files in my $fpath but I've read nothing that says this will work.
Will it?


text:
Q: home screen web app cuts off part of the page when fullscreen First I have to say that I am new to this web app home screen button theme.
These lines:
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />

worked cool for me so far, yet there is a problem when orientation is changed from landscape to portrait. Then the app cuts of just the part where the browser chrome was and leaves a white field instead on the right side.
Strangely when I start in portrait mode and then change to landscape all works well as supposed to back and forth.
How is this to be avoided?
Thanks so much for help
Garavani

A: The following code solved my problem:
$(window).on('orientationchange', function() {
                    // only necessary for home screen use
                    // otherwise blank space is left where the adress bar was (on orientation change from landscape to portrait)
                    document.body.scrollLeft = 0;
                } );


text:
Q: Is it possible to view bugs submitted by others to Apple's bug reporter? Engineering has determined that your bug report is a duplicate of another issue and will be closed.
This is a message I see quite often these days at http://bugreport.apple.com and it is frustrating for several reasons:

*

*you submitted a bug for nothing without the possibility to check the database first

*you can't check if it is truly a duplicate

*there is no follow-up on your issue

*you'll never know if they are fixing the bug

I can't believe that these major disadvantages are on purpose.
So: Is it possible to view bugs submitted by others to Apple's bug reporter?

A: It is not possible. But there is a website called OpenRadar where the community files the same bugs as in Apple's bug reporter.
It's supposed (never confirmed) that Apple analyses all bugs and solves the ones with more duplicates. In that way, people report again and again the same bugs on Apple's Bugreport in order to speed up the process.
So, if you want a bug to be solved asap, file your bug report, duplicate in open radar and then share that radar to as many people as you know.

A: It is currently impossible. Only Apple employees with special permissions can access the full Radar database. 3rd parties (such as registered developers, integrators, resellers and others) can only access entries they created in the BugReport system.
One specifically annoying consequence is this:
Many Apple code samples contain workarounds for old radar bugs with references to those bugs (e.g. CFProxySupportTool sample project contains workarounds for rdar://problem/5530166 and rdar://problem/5533931)
However, when using older sample such as this, It is impossible to know when is it safe to remove those workarounds - because you can't know if the specific bug was resolved in some OS version.


text:
Q: Gson: Expected a string but was BEGIN_OBJECT at line 1 column 3 path $[0] I want to get an ArrayList out of a String containing:`
[
    {
        "name": "*",
        "package": "permission",
        "id": "permission.*"
    },
    {
        "name": "*",
        "package": "info",
        "id": "info.*"
    },
    {
        "name": "help",
        "package": "info",
        "id": "info.help"
    },
    {
        "name": "ping",
        "package": "info",
        "id": "info.ping"
    },
    {
        "name": "premium",
        "package": "info",
        "id": "info.premium"
    }
]

However, I get a JsonSyntaxException every time. My Permission.class looks like this:
public enum Permission {
    ALL("permission", "*"),

    INFO("info", "*"),
    INFO_HELP("info", "help"),
    INFO_PING("info", "ping"),
    INFO_PREMIUM("info", "premium"),

    ;
    @SerializedName("permPack")
    public final String permPack;
    @SerializedName("permName")
    public final String permName;
    @SerializedName("permId")
    public final String id;

    Permission(String permPack, String name) {
        this.permPack = permPack;
        this.permName = name;
        this.id = permPack + "." + name;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return permName;
    }

    public String getPermPack() {
        return permPack;
    }

    public static Permission getById(String Id) {
        List<Permission> perms = Arrays.asList(Permission.values());
        for (int i = 0; i < perms.size(); i++) {
            if (perms.get(i).getId().equals(Id)){
                return perms.get(i);
            }
        }
        return null;
    }
}

I tried to deserialize the String using:
    Type listType = new TypeToken<ArrayList<Permission>>(){}.getType();
    ArrayList<Permission> availablePermsList = gson.fromJson(permissionString, listType);

I also tried to add a name to this String or writing an own deserializer using Permission.getById, nothing works. I am out of ideas.

A: This is how your POJO Class should look like instead of enum it should be plain java class
class Permission {
        private String id;
        private String name;
        @SerializedName("package")
        private String packageName;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPackageName() {
            return packageName;
        }

        public void setPackageName(String packageName) {
            this.packageName = packageName;
        }

        @Override
        public String toString() {
            return "Permission{" +
                    "id='" + id + '\'' +
                    ", name='" + name + '\'' +
                    ", packageName='" + packageName + '\'' +
                    '}';
        }
    }

For answering i have used JsonReader from a file, instead you can directly use
 string in gson.fromJson(...) method
This is how i am calling to convert Array of string to Permission List
Type permissionsListType = new TypeToken<ArrayList<Permission>>(){}.getType();
JsonReader jsonReader = new JsonReader(new FileReader(new File("permissions.json")));
Gson gson = new Gson();
ArrayList<Permission> availablePermsList = gson.fromJson(jsonReader, permissionsListType);

System.out.println(availablePermsList);


text:
Q: Mismatch error in function that returns minimum in the row of another workbook I am working on a VBA function that reads the 11th row of another worksheet and finds the minimum value on the row.
However, the minimum's absolute value must be less than 100. (The row displays both percentages and regular values and I only need the minimum percentage.)
Here is what I have so far, thanks to the help of answers in a previous question I asked:
If (.Cells(11, Colcount).Value < min) And (Abs(.Cells(11, Colcount).Value) <= 100) Then

This line is giving me the error:

Run-time error '13': Type mismatch

Furthermore, once I have the value of the minimal value in the 11th row, I want to assign the value of the cell right above to a variable, thanks to the function Worst.
Function Loss(worksheet1 As Worksheet) As Double

    Dim min As Double
    Dim i As Integer
    Dim myRight As Long, Colcount As Long

    min = 100

    With worksheet1
        myRight = .Cells(1, .Columns.Count).End(xlToLeft).Column

        For Colcount = 4 To myRight
            If (.Cells(11, Colcount).Value < min) And (Abs(.Cells(11, Colcount).Value) <= 100) Then
                min = .Cells(11, Colcount).Value
            End If
        Next Colcount

    End With

    Loss = min

End Function

Function Worst(worksheet1 As Worksheet) As String

    Dim min As Double
    Dim i As Integer
    Dim myRight As Long, Colcount As Long

    min = 100

    With worksheet1
     myRight = .Cells(1, .Columns.Count).End(xlToLeft).Column

     For Colcount = 4 To myRight

            If (.Cells(11, Colcount).Value < min) And (Abs(.Cells(11, Colcount).Value) <= 100) Then
               min = .Cells(11, Colcount).Value
              Worst = .Cells(10, Colcount).Value
          End If
     Next Colcount
End With

End Function

A: You'll get a Type Mismatch if the cell value is not numeric.
Add an additional check using IsNumeric before attempting the comparison and Abs.
Function Loss(worksheet1 As Worksheet) As Double

    Dim min As Double
    min = 100

    Dim myRight As Long
    myRight = worksheet1.Cells(1, worksheet1.Columns.Count).End(xlToLeft).Column

    Dim colCount As Long

    For colCount = 4 To myRight
        With worksheet1.Cells(11, colCount)
            If IsNumeric(.Value) Then
                If .Value < min And Abs(.Value) <= 100 Then
                    min = .Value
                End If
            End If
        End With
    Next colCount

    Loss = min
End Function


text:
Q: Adding icon to costum JDialog I want to change the icon next to the title of my costum JDialog, but i cant get it to work. It worked this way for a JOptionPane before.
private ResourceLoader rl = ResourceLoader.getInstance();
...
setBounds(100, 100, 603, 419);
setTitle("über CogFit");
new ImageIcon(this.rl.loadImage("gfx/srh_logo_32x32.png"));

I already tried this:
JDialog - how to change icon
but it also didnt work.
Thanks for the help

A: If you want to set the icon displayed in the tile bar you must use the JDialog#setIconImage(Image) method.
https://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#setIconImage(java.awt.Image)


text:
Q: problem understanding Python Sokoban code I am trying to build a Sokoban puzzle application in Python.
(description of the rules:
http://en.m.wikipedia.org/wiki/Sokoban)
I successfully implemented the game, but I thought it would be better if the computer can calculate the best solution to solve a specific puzzle.
While I was looking for a reference, I came across this Python implementation on Rosetta Code:

from array import array
from collections import deque
import psyco

data = []
nrows = 0
px = py = 0
sdata = ""
ddata = ""

def init(board):
    global data, nrows, sdata, ddata, px, py
    data = filter(None, board.splitlines())
    nrows = max(len(r) for r in data)

    maps = {' ':' ', '.': '.', '@':' ', '#':'#', '$':' '}
    mapd = {' ':' ', '.': ' ', '@':'@', '#':' ', '$':'*'}

    for r, row in enumerate(data):
        for c, ch in enumerate(row):
            sdata += maps[ch]
            ddata += mapd[ch]
            if ch == '@':
                px = c
                py = r

def push(x, y, dx, dy, data):
    if sdata[(y+2*dy) * nrows + x+2*dx] == '#' or \
       data[(y+2*dy) * nrows + x+2*dx] != ' ':
        return None

    data2 = array("c", data)
    data2[y * nrows + x] = ' '
    data2[(y+dy) * nrows + x+dx] = '@'
    data2[(y+2*dy) * nrows + x+2*dx] = '*'
    return data2.tostring()

def is_solved(data):
    for i in xrange(len(data)):
        if (sdata[i] == '.') != (data[i] == '*'):
            return False
    return True

def solve():
    open = deque([(ddata, "", px, py)])
    visited = set([ddata])
    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),
            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))

    lnrows = nrows
    while open:
        cur, csol, x, y = open.popleft()

        for di in dirs:
            temp = cur
            dx, dy = di[0], di[1]

            if temp[(y+dy) * lnrows + x+dx] == '*':
                temp = push(x, y, dx, dy, temp)
                if temp and temp not in visited:
                    if is_solved(temp):
                        return csol + di[3]
                    open.append((temp, csol + di[3], x+dx, y+dy))
                    visited.add(temp)
            else:
                if sdata[(y+dy) * lnrows + x+dx] == '#' or \
                   temp[(y+dy) * lnrows + x+dx] != ' ':
                    continue

                data2 = array("c", temp)
                data2[y * lnrows + x] = ' '
                data2[(y+dy) * lnrows + x+dx] = '@'
                temp = data2.tostring()

                if temp not in visited:
                    if is_solved(temp):
                        return csol + di[2]
                    open.append((temp, csol + di[2], x+dx, y+dy))
                    visited.add(temp)

    return "No solution"

level = """\
#######
#     #
#     #
#. #  #
#. $$ #
#.$$  #
#.#  @#
#######"""

psyco.full()
init(level)
print level, "\n\n", solve()

It basically reads a text string representing the puzzle, and solves it using BFS.
One of the things that I had trouble understanding, however, was what sdata and ddata represent respectively. It looks like sdata and ddata map different characters, but I don't understand why.
Any ideas?
Thanks :)

A: If you look at what the data is mapping to:
. = end point
@ = the guy
# = wall
$ = diamond
maps = {' ':' ', '.': '.', '@':' ', '#':'#', '$':' '}
mapd = {' ':' ', '.': ' ', '@':'@', '#':' ', '$':'*'}

ssata appears to be a map of the end point and and the wall.
ddata appears to be a map of the player and the diamonds.

A: sdata holds the static data from the maze (the parts that don't change as we search), and ddata holds the dynamic data (the parts that do change as we search), and is used to hold the initial state.
It is probably done this way because its possible for boxes and the guy to be in the same position as a goal, which would make much of the code more complex to implement.
It is the ddata that is initially pushed onto the open list as the start position for the search, and into the visited set to mark positions that have already been searched.


text:
Q: Understanding task_basic_info task resident_size short question: someone (cit. 5) told me that resident memory could be reclaimed by my system. What does this mean? Does it mean that my App is not using that memory or is the resident memory value directly related to the memory being currently used by my App? I haven't found much documentation on this apart from those answers.
I am trying to solve an issue. I am writing a game usign iOS 6.0 and Cocos2d 2.0 and I do get some memory problems. I have Cococs2d 2.0 as static library and I wrote my code using ARC (which I suspect being the reason).
Going from Initial scene to Character Selection Scene and then to Planet Selection scene and finally Game scene I observe that the resident_size of memory increases.
I added this code at each scene init and I tracked down the values. The following picture show the user experience path I do. On the left colum there are the scene names, on the second colum the amount of memory used in the normal flow (not going back to the previous scene) and in the third block of colums there are the values of resident memory going back and forwards from specific scenes.

As we can observe the Main scene presents an issue probably different from the other scenes. Every time I load the scene I get a memory increase of about 15 MB.
I run an indipendent test on the scene (using a reload callback method) and I get the following values:

Interestingly, running the same test on the CharacterSelection Scene does not have a progressive increase of memory after the third load (stays 37MB). However I do not understand why initially goes from 27 MB to 32 MB and NOT to 37MB (or, I should say, I do not understand why it goes from 32 MB to 37 MB).
I run another set of test trying to parse from one scene to the other and I do get interesting results. Here is the schema:

**Someone answered to me saying "Resident memory is a measurement of the memory that has been allocated to your application and has not yet been reclaimed by the system, but some/most of the resident memory could be reclaimed by the system."
Does this mean that resident memory values are not necessarily memory used by my App?
According to my test, there does seem to be a correlation between scenes and their memory used and resident memory value.
So if this is correct I should keep trying to solve this issue as the higher the resident memory value is the more likely my APP is to be killed. If, instead the memory would be available to the system to be used then there would be no crash. Given that there are crashes I assume that the memory is somehow leaked. However the leak tool does not detect any leaks (is this because I am using XCode 4.5?).
Any help? Is this related to using ARC?

A: The issue was that I was measuring the memory during the init method of the new scene. The report was hence including the assets of the previous scene (as it was not yet being deallocated).
Adding a callback with a 0.1 delay solved it and answering my questions:
Q:

someone (cit. 5) told me that resident memory could be reclaimed by my
  system. What does this mean? Does it mean that my App is not using
  that memory or is the resident memory value directly related to the
  memory being currently used by my App?

A:
it is the memory directly related to the memory being used by my App. Using a delay in the callback of this function plus a call to [[CCTextureCache sharedTextureCache] dumpCachedTextureInfo]; will confirm this.
Q:

Any help? Is this related to using ARC?

A:
Not in this case fortunately. There where other issues causing leaks in some scenes. For example, the starting scene was subclass of another scene. This starting scene had some child nodes being added as child which where not being removed on the cleanup method of the scene. Adding an explicit removal of those child nodes solved the issue. I am not sure why this was necessary (I was expecting all child nodes to be automatically removed) but it solved the issue.


text:
Q: Unable to save a preprocessed data as csv to a folder in s3 bucket I have the following tree structure of my folder:
.
├── All_seasons_combined_script.py
├── Base_SLP
│   ├── G0.xlsx
│   ├── G1.xlsx
│   ├── G2.xlsx
│   ├── G3.xlsx
│   ├── G4.xlsx
│   ├── G5.xlsx
│   ├── G6.xlsx
│   ├── H0.xlsx
│   ├── L0.xlsx
│   ├── L1.xlsx
│   └── L2.xlsx
├── Pipfile
├── Pipfile.lock
├── README.md
├── requirements.txt
└── slp_handler.py

I have the following code in slp_handler.py:
def yearly_slp_handler(event, context):
    try:
        COUNTRY = event['country']
        currentYear = datetime.datetime.now().strftime("%Y")
        HOLIDAYS = get_holidays(currentYear, COUNTRY)

        excel_path = os.path.join(Path(), "Base_SLP")
        print(excel_path)
        os.chdir(excel_path)

        absolute_path = Path(os.path.abspath(
            os.path.dirname('Base_SLP'))).parent
        print(absolute_path)

        EXCEL_FILES = glob.glob('*.xlsx')
        print(EXCEL_FILES)

        for file in EXCEL_FILES:
            time_series_df = season_df(file, HOLIDAYS)
            save_name = file.split('.')[0] + '_' + \
                currentYear + '_timeseries.csv'

            time_series_df.to_csv(save_name, index=None)

            s3 = boto3.resource('s3')
            bucket_name = 'mybucket/folder'
            s3.meta.client.upload_file(
                Filename=save_name, Bucket=bucket_name, Key=save_name)

            print('CSV dropped in the bucket folder.')

        return {'Status': 200}

    except Exception as e:
        print(e)
        return {'Status': 400}

where get_holidays & season_df are a couple of functions I have for pre-processing the data.
What I am trying to do is to read all the excel files in the Base_SLP folder, pre-process each of them and save them as csv using to_csv in a folder in the s3 bucket.
When I deploy the code as lambda and test it, it gives me the following error:
START RequestId: xxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxx Version: $LATEST
./Base_SLP
/var/task
['G0.xlsx', 'G1.xlsx', 'G2.xlsx', 'G3.xlsx', 'G4.xlsx', 'G5.xlsx', 'G6.xlsx', 'H0.xlsx', 'L0.xlsx', 'L1.xlsx', 'L2.xlsx']
[Errno 30] Read-only file system: 'G0_2020_timeseries.csv'

I want the preprocessed file to be converted into a csv and then this csv must be dropped in a folder in the s3 bucket. I tried the answer by onur, but it is still not working.
I also tried saving the csv in the /tmp/ folder and them uploading it from there to the folder in s3 using S3.Object.upload_file:
for file in EXCEL_FILES:
  time_series_df = season_df(file, HOLIDAYS)
  save_name = file.split('.')[0] + '_' + \
      currentYear + '_timeseries.csv'

  time_series_df.to_csv('/tmp/' + save_name, index=None)
  print('DF converted to CSV.')

  saving_file_path = os.path.join('folder', save_name)
  print(saving_file_path)

  # Create S3 object
  s3 = boto3.resource('s3')
  s3.Object('mybucket', 'folder').upload_file(
      '/tmp/' + save_name)
  print('CSV dropped in the bucket folder.')

return {'Status': 200}

but it was throwing the following error:
Failed to upload /tmp/G0_2020_timeseries.csv to mybucket/folder/G0_2020_timeseries.csv: An error occurred (NoSuchBucket) when calling the PutObject operation: The specified bucket does not exist

The bucket and the folder exist and have public access. But still, it is throwing this error.
My lambda has the AmazonS3FullAccess access attached to it.
What is the mistake I am doing?

A: It seems that you are trying to save your files in /var/task. In lambda environment, only /tmp is writable to your function.
Therefore, you could trying the following:
            save_name = '/tmp/' + file.split('.')[0] + '_' + \
                currentYear + '_timeseries.csv'


text:
Q: Replace a string in bash, with a variable based on that string I am trying to parse a file for IP addresses and then replace them with a 1 for 1 mapped IP address. For example, find all instances of 1.1.1.1 and replace these with 100.100.1.1, and all instances of 5.5.5.5 and replace those with 100.100.5.5. There may be thousands of IPs, so I do not want to parse the file for each substitution using static sed commands.
I am trying to use an associative array for this, but I am falling short.
echo "1.1.1.1 5.5.5.5" > testfile.txt
declare -A testarray
testarray[ip_1.1.1.1]="100.100.1.1"
testarray[ip_5.5.5.5]="100.100.5.5"
sed -r "s/(([0-9]{1,3}\.){3}[0-9]{1,3})/${testarray[ip_\1]}/g" testfile.txt

Using the capture group inside the variable doesn't work. However using the text directly does.
sed -r "s/(([0-9]{1,3}\.){3}[0-9]{1,3})/${testarray[ip_1.1.1.1]}/g" testfile.txt
100.100.1.1 100.100.1.1

Of course this replaces all IPs with 100.100.1.1, I want to replace based on the array association.
Is there any way to take a capture group and use it in a variable for a replacement in bash? I have tried a few variants with quotes as well as building a variable in advance that still depends on '\1' but it either fails, or just returns the literal output of the variable. I don't know if there is a better tool than sed for this.
I also tried using variables instead of an array, but I ran into the same issue.

A: POSIX shell script, input is testfile.txt, comma seperated "from to" pairs are in replacements.txt:
echo 1.1.1.1 100.100.1.1 ,5.5.5.5 100.100.5.5 | tr ',' '\n' > replacements.txt
echo "1.1.1.1 6.7.8.9 5.5.5.5" | tr ' ' '\n' > testfile.txt

while read x ; do
    while read a b ; do
        if [ $a = $x ] ; then
            x=$b
            break
        fi
    done < replacements.txt
    echo $x
done < testfile.txt

Output:
100.100.1.1
6.7.8.9
100.100.5.5

Notes:  inefficient, it rereads at least one line of replacements.txt for every line of testfile.txt, but that does permit replacement lists bigger than bash's available memory.


text:
Q: Dynamic %%GLOBAL_UPC%% variable on blueprint theme I would like to know if the global variable %%GLOBAL_UPC%% (UPC/EAN) can be changed dynamically as the SKU variable does too.
The UPC fields appears inside of Options &SKU tab from backend. But only display the first value when i display  %%GLOBAL_UPC%% in product page.
Exist some javascript or method to show the others values when changing options??
Remember that im talking about UPC (Not SKU) using the blueprint theme.

A: It cannot be changed dynamically like the SKU. There is only a single UPC value per parent product in the BigCommerce data model.


text:
Q: Validation rule to disqualify leads before conversion (based on certain criteria) Is it possible to implement a data validation rule to disqualify leads which annual revenue is less than £50,000K?
How to apply this limitation at the time of conversion into a contact/account/opportunity?

A: I assume that disqualification means you have to restrict the lead from the conversion process. You can use the 'IsConverted' field on the lead object along with the annual revenue field.
Example : AND(IsConverted, AnnualRevenue__c < 50000).
This will restrict the lead with revenue of less than 50000 from conversion.


text:
Q: How to print a pdf file to stdout using python? A correct pdf file has been created by a script (whose output can't be directly written to stdout, unfortunately). Say the file's name is 'myfile.pdf'.
I want to print the exact pdf content to stdout. (No processing in between).
To test this, I have written this short read_pdf.py script:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

with open('myfile.pdf', mode='rb') as pdf_file:
    for line in pdf_file:
        print(str(line))

I use the 'rb' mode because reading this in text mode leads to a UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 10: invalid continuation byte. So, it doesn't look like there's any other alternative (if text mode doesn't work, then binary mode).
Now of course the problem is that the output consists of b'blablabla' lines that cannot be used as a pdf file. To check it, I redirect read_pdf.py to a file and try to open it with a pdf viewer and of course it doesn't work:
$ ./read_pdf.py > test_output.pdf
$ evince test_output.pdf
Syntax Error: Couldn't find trailer dictionary
Syntax Error: Couldn't read xref table
Syntax Error: Couldn't find trailer dictionary
Syntax Error: Couldn't read xref table

So, what is the right way to do it? I haven't checked any pdf dedicated library because it doesn't look necessary, I'd like to be able to read and print correct content without importing a pdf library for that.
chardet.detect(pdf_file.read()) couldn't help (it returned {'encoding': None, 'confidence': 0.0}).
EDIT:
* I'm looking for a solution for python3 and for a Linux/Unix system, not windows.
* I need to know how to do this in python because its's actually part of a bigger project entirely written in python

A: I think your problem is that you are reading line by line, therefore adding extra carriage returns. I tried and works perfectly on OSX:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

with open('myfile.pdf', mode='rb') as pdf_file:
        print(pdf_file.read())

For the sake of completeness, as noted by @zezollo, in Linux the file will still be corrupted using the print function, so it is necessary to write directly on the buffer:
import sys

with open('myfile.pdf', mode='rb') as pdf_file:
    sys.stdout.buffer.write(pdf_file.read())

A: The answer is actually to use sys.stdout.buffer.write(), instead of print(), and in addition to pdf_file.read():
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

with open('myfile.pdf', mode='rb') as pdf_file:
    sys.stdout.buffer.write(pdf_file.read())


text:
Q: No Lightbox in IE 8 Everything works fine, except for IE 8. Lightbox (jQuery plugin) is not working there. Instead of Lightbox, it opens the URL of the link. What am I doing wrong? The URL is http://keramiek.milacic.nl/tegels.
Regards,
Kevin

A: I would recommend trying colorBox as a much better solution than lightbox in every respect
http://colorpowered.com/colorbox/

A: A possibility is the way you have initialised the lightbox. At the moment it targets "#content a" but looking at the source:

Maybe you need to target the objects specifically instead of using the umbrella "#content a"
Something like "#content table td p a"


text:
Q: sns.barplot from dict with tuple keys I can successfully create a pandas barplot based off of a groupy as follows:
df.groupby('stop_duration')['violation_raw'].value_counts().plot(kind="barh")

It works fine.
But I like to use sns.barplot because I have certain aesthetics I like to adhere to.
I use this general structure to print dicts to sns.barplots all the time:
plt.figure(figsize=(7, 7))
gbsdvrvc = df.groupby('stop_duration')['violation_raw'].value_counts().to_dict()

cc = sns.barplot(x=list(gbsdvrvc.values()), y=list(gbsdvrvc.keys()), orient='h', palette="dark:salmon_r")
for item in cc.get_xticklabels():
    cc.bar_label(cc.containers[0])
plt.xlabel("Count", labelpad=12)
plt.ylabel("Stop Duration, Violation Raw", labelpad=12, fontdict={'fontsize': 16, 'fontweight': 'bold'})
plt.tight_layout()
plt.show()

However, this exact code generates a KeyError:
Traceback (most recent call last):
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 348, in <module>
    cc = sns.barplot(x=list(gbsdvrvc.values()), y=list(gbsdvrvc.keys()), orient='h', palette="dark:salmon_r")
  File "C:\Users\Mark\AppData\Local\Programs\Python\Python38\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
    return f(**kwargs)
  File "C:\Users\Mark\AppData\Local\Programs\Python\Python38\lib\site-packages\seaborn\categorical.py", line 3182, in barplot
    plotter = _BarPlotter(x, y, hue, data, order, hue_order,
  File "C:\Users\Mark\AppData\Local\Programs\Python\Python38\lib\site-packages\seaborn\categorical.py", line 1584, in __init__
    self.establish_variables(x, y, hue, data, orient,
  File "C:\Users\Mark\AppData\Local\Programs\Python\Python38\lib\site-packages\seaborn\categorical.py", line 206, in establish_variables
    plot_data, value_label = self._group_longform(vals, groups,
  File "C:\Users\Mark\AppData\Local\Programs\Python\Python38\lib\site-packages\seaborn\categorical.py", line 253, in _group_longform
    grouped_vals = vals.groupby(grouper)
  File "C:\Users\Mark\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\series.py", line 1884, in groupby
    return SeriesGroupBy(
  File "C:\Users\Mark\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\groupby\groupby.py", line 889, in __init__
    grouper, exclusions, obj = get_grouper(
  File "C:\Users\Mark\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\groupby\grouper.py", line 862, in get_grouper
    raise KeyError(gpr)
KeyError: ('0-15 Min', 'Speeding')

I guess it does not like the tuples as keys?
The dict (gbsdvrvc) is created just fine:

As mentioned above, I can do this with the pandas bar plot just fine (.plot(kind="barh")).
Why am I unable to create the desired sns.barplot from this dictionary (gbsdvrvc)?
Here is a working example using the same code. The keys in the dict used for this output were not tuples:

A: @JohanC let me know (see above) that Seaborn does NOT expect tuples as keys.
Based on that, I wrote the following code to convert each tuple of strings into a list of strings, the strings being a single string representation of each tuple.
gbsdvrvc = df.groupby('stop_duration')['violation_raw'].value_counts().to_dict()
# pprint(gbsdvrvc)
y = list(gbsdvrvc.keys())

def convertTuple(list_of_tup):
    # initialize an empty string
    los = []
    for tup in list_of_tup:
        str_ = ''
        for item_ in tup:
            str_ = str_ + item_
            if str_ not in los:
                los.append(str_)
    return los

merged_keys = convertTuple(y)

# items to be removed
unwanted = {'0-15 Min', '16-30 Min', '30+ Min'}
filtered = [ele for ele in merged_keys if ele not in unwanted]

This solved my problem.
Only odd thing is that the dict has 36 unique key\value pairs.  After running convertTuple I end up with 39 items in my list??
The extras are in the above set 'unwanted'.
No idea why they are appearing.
I simply get rid of them and then it works.
{('0-15 Min', 'APB'): 37,
 ('0-15 Min', 'Call for Service'): 547,
 ('0-15 Min', 'Equipment/Inspection Violation'): 9173,
 ('0-15 Min', 'Motorist Assist/Courtesy'): 119,
 ('0-15 Min', 'Other Traffic Violation'): 11763,
 ('0-15 Min', 'Registration Violation'): 2421,
 ('0-15 Min', 'Seatbelt Violation'): 2665,
 ('0-15 Min', 'Special Detail/Directed Patrol'): 1622,
 ('0-15 Min', 'Speeding'): 41014,
 ('0-15 Min', 'Suspicious Person'): 32,
 ('0-15 Min', 'Violation of City/Town Ordinance'): 144,
 ('0-15 Min', 'Warrant'): 6,
 ('16-30 Min', 'APB'): 24,
 ('16-30 Min', 'Call for Service'): 435,
 ('16-30 Min', 'Equipment/Inspection Violation'): 1373,
 ('16-30 Min', 'Motorist Assist/Courtesy'): 59,
 ('16-30 Min', 'Other Traffic Violation'): 3150,
 ('16-30 Min', 'Registration Violation'): 804,
 ('16-30 Min', 'Seatbelt Violation'): 249,
 ('16-30 Min', 'Special Detail/Directed Patrol'): 613,
 ('16-30 Min', 'Speeding'): 6848,
 ('16-30 Min', 'Suspicious Person'): 13,
 ('16-30 Min', 'Violation of City/Town Ordinance'): 61,
 ('16-30 Min', 'Warrant'): 6,
 ('30+ Min', 'APB'): 18,
 ('30+ Min', 'Call for Service'): 316,
 ('30+ Min', 'Equipment/Inspection Violation'): 474,
 ('30+ Min', 'Motorist Assist/Courtesy'): 25,
 ('30+ Min', 'Other Traffic Violation'): 1310,
 ('30+ Min', 'Registration Violation'): 207,
 ('30+ Min', 'Seatbelt Violation'): 38,
 ('30+ Min', 'Special Detail/Directed Patrol'): 220,
 ('30+ Min', 'Speeding'): 600,
 ('30+ Min', 'Suspicious Person'): 11,
 ('30+ Min', 'Violation of City/Town Ordinance'): 6,
 ('30+ Min', 'Warrant'): 3}


text:
Q: How to create a Class with List<> properties The problem:
- I want to read filename into a List<> inside a class.

*

*How to I read the filename into List<> in foreach Statement?

*How to set up the get and set statement in List<> properties in the class.

*For this operation, which type to use: static class or normal class?
------revise------------- This is the problem :
sorry for the confusion.
What I wanted is to add the filenames into the List<> in the class. I want to have a list of filename in the List for later use.
1) How do I add the filename into the List  g_Photoname in the Class in Click Event or Page Load Event?
protected void Button_Click(object sender, EventArgs e)
{
//-1- Get  all the files in Temp directory
       var pe = new PicExample(@"c:\temp\");

        foreach (string f in pe.FileList)
        {

   // Question : How do I add the f in the List<> in this class ?

  //  PhotoNameCollection = f ;  ???  Can do?

        }

}
2) Create a static class to hold the list of filename in the List<> in class
a) How do I set up the get ad set statement for the List<> in this class?
b) Is the List<> correcctly used in this class?
public class PhotoNameCollection
{
    private List<string> g_Photoname

    public List<string> PhotoName
    {
        get
    {

     }

   set
        {
    }

    }

 }

A: Something like this should help get you started ...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var pe = new PicExample(@"c:\temp\");

            foreach (var p in pe.FileList)
            {
                Console.WriteLine(p);
            }

            Console.ReadLine();
        }
    }

    public class PicExample
    {
        private List<string> _fileNames = new List<string>();

        public PicExample( string directory )
        {
            var files = Directory.EnumerateFiles(directory);

            foreach (var file in files)
            {
                _fileNames.Add(file);
            }
        }

        public List<string> FileList
        {
            get { return _fileNames; }
            set { _fileNames = value; }
        }
    }
}


text:
Q: jInstagram unrecognized Date format In reference to jInstagram library, the method MediaFeedData.getCreatedTime() returns a String whose format I cannot understand.
Examples of its return value:

*

*1445858153

*1445858042

*1445857646

*1445857633
What date format is this? And how can I cast it into a java.util.Date object?

A: This is the long representation of Date. You can call new Date(14458581538*1000) to obtain date information from this.
use the below code:
long lDate = (long)14458581538*1000;
Date date= new Date(lDate);
System.out.println(date);

A: Those are so called Timestamps
You can convert them to a readable date and adjust the format with SimlpeDateFormat
String stringDate = new SimpleDateFormat("MM/dd/yyyy").format(1445858153);
System.out.println(stringDate);

To make a Date object from a timestamp use:
  Date date = new Date(1445858153);
  System.out.println(date);

Give it a try


text:
Q: How can I call a trait's non-static method from a static method with PHP7? trait ClearFolder
{
    public function clearFolder($dir)
    {
        //codes...
    }

    public function clearInFolder($dir)
    {
        $this->clearFolder($dir);

        mkdir($dir);
    }
}

use boot\library\traits\ClearFolder;

class FileCache
{
    //codes....

    use ClearFolder;
    public static function clearAll()
    {
        //Case1. Uncaught Error: Using $this when not in object...
        $this->clearInFolder(self::$storage . '/');

        //Case2. Non-static method boot\libr... should not be called statically
        self::clearInFolder(self::$storage . '/');

        //Case3. Cannot instantiate trait...
        $trait = new ClearFolder;

    }
}

To use a non-static method of another class inside a static method, I have to create an instance with the new keyword. But I can't use 'new' with a trait.
And I use 'declare (strict_types = 1);' and ' error_reporting(E_ALL);'.
Should I change the trait's method statically and replace everything that uses the trait?

A: If you want to use a non static function from a trait you must create a instance:
trait trait1
{
    public function dummy()
    {
      var_dump("fkt dummy");
    }
}
class c1{
  use trait1;

  public static function static1(){
    (new static)->dummy();
  }
}

c1::static1();  //string(9) "fkt dummy"

Or you declare your function in the trait as static:
trait trait1
{
    public static function dummy()
    {
      var_dump("fkt dummy");
    }
}
class c1{
  use trait1;
}

c1::dummy(); //string(9) "fkt dummy"

Not nice, but works. But you should not use this without thinking about your code design.


text:
Q: Count data if existing in other table My query with a few INNER JOINs generate a result like this:
File_ID | Folder_ID |        email               | name
   1          4        user@mydomain.com           User1
   2          4        user2@differentdomain.com   User2
   3          4        user3@NOTmydomain.com       User3

I also have a table for all the users in my domain.
Email                |
---------------------|
user1@mydomain.com   |
user2@mydomain.com   |
user3@mydomain.com   |

Now I want to compare and count the result of the first table on how many data in the results are with LIKE '@mydomain.com' but NOT EXISTS/ NOT IN the Email table. So in this example the result of the COUNT = 0 since user@mydomain is not on the Email table even it has '@mydomain.com'.`
Thank you!


text:
Q: getting null row key after using primefaces filter When i am not using filter in primefaces datatable and try to select row then for example press edit it working well and takes the selected row.but when i use primefaces filter and then select the filtered row then edit
i got org.primefaces.model.SelectableDataModel when selection is enabled exception.
i know that mean i have a null row key but i don't know why.i am using a valid row key(id) the primary key of the datatable and when i use the debug i found that it get the id two times in the failure case,first time it got the right filtered id and the second time it get null id.
my question why it gets the rowkey id two times which get the null in the second time and cause the exception
    <h:body>
    <h:form prependId="false" id="growlForm">
        <p:growl id="growl" showDetail="false" />
    </h:form>
    <h:form id="dataForm">
    <p:panel id="ingerdientsTable">
    <f:facet name="header">
          <h:outputText value="Standard Food List" />
        </f:facet>
         <p:dataTable id="ingedientsTable" widgetVar="ingedientsTable" var="ingerdients" resizableColumns="true"
                    selectionMode="single" selection="#{mealBean.selectedStandardIngerdients}"
                     rowKey="#{ingerdients.getId()}" value="#{mealBean.allIngerdients}" rowsPerPageTemplate="5,10,25,50" rows="20"
                     paginator="true" style="padding-top:10px;padding-bottom:10px" tableStyle="table-layout: auto"
                     paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown} ">

                    <p:column headerText="Food Type"  filterBy="#{ingerdients.name}"><h:outputText value="#{ingerdients.name}" /></p:column>
                    <p:column headerText="Protein(gm)"  filterBy="#{ingerdients.containedProtiens}"><h:outputText value="#{ingerdients.containedProtiens}" /></p:column>
                    <p:column headerText="Carbs(gm)"  filterBy="#{ingerdients.containedCarbs}"><h:outputText value="#{ingerdients.containedCarbs}" /></p:column>
                    <p:column headerText="Fats(gm)"  filterBy="#{ingerdients.containedFats}"><h:outputText value="#{ingerdients.containedFats}" /></p:column>
                    <p:column headerText="Total Calories" filterBy="#{ingerdients.totalCalories}"><h:outputText value="#{ingerdients.totalCalories}" /></p:column>
                    <p:column styleClass="action-column">
                        <f:facet name="header">
                            <h:outputText value="Actions" />
                        </f:facet>
                        <p:commandButton id="addToMeal" value="Add To Meal" icon="ui-icon-create" update="addToMealDialog"
                            action="#{mealBean.showIngerdientsToMealDialog(ingerdients)}" immediate="true"
                            title="Add To meal" ajax="true">
                        </p:commandButton>
                        <p:tooltip for="addToMeal" value="Add To Meal"
                            showEffect="fade" hideEffect="fade" />
                            </p:column>

                    </p:dataTable>
        </p:panel>

public class StandardIngerdients{
    @Id
    @Column(name="Id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    @ManyToOne
    @JoinColumn(name="FolderPathId",referencedColumnName="Id",nullable=true)
    private FolderPath folderPath;

    @Column(name="Name")
    private String name;
    @Column(name="ContainedProteins")
    @NotNull
    private Double containedProtiens;
    @Column(name="ContainedCarbs")
    @NotNull
    private Double containedCarbs;
    @Column(name="ContainedFats")
    @NotNull
    private Double containedFats;
    @Column(name="TotalCalories")
    @NotNull
    private Double totalCalories;
    @Column(name="ImageName")
    private String imageName;
    public Integer getId() {
        return id;
    }
    public void setId(Integer Id) {
        this.id = Id;
    }
    public FolderPath getFolderPath() {
        return folderPath;
    }
    public void setFolderPath(FolderPath folderPath) {
        this.folderPath = folderPath;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public Double getContainedProtiens() {
        return containedProtiens;
    }
    public void setContainedProtiens(Double containedProtiens) {
        this.containedProtiens = containedProtiens;
    }
    public Double getContainedCarbs() {
        return containedCarbs;
    }
    public void setContainedCarbs(Double containedCarbs) {
        this.containedCarbs = containedCarbs;
    }
    public Double getContainedFats() {
        return containedFats;
    }
    public void setContainedFats(Double containedFats) {
        this.containedFats = containedFats;
    }
    public Double getTotalCalories() {
        return totalCalories;
    }
    public void setTotalCalories(Double totalCalories) {
        this.totalCalories = totalCalories;
    }
    public String getImageName() {
        return imageName;
    }
    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

}

A: I was having the same problem. The thing is I make my class to implement Serializable which guarantee the "integrity" (so to speak) of data in order not to disappear hehe... so your class would be like this:
 public class StandardIngerdients implements Serializable {

A: you can try below code i think solve it
rowKey="#{ingerdients.id}"


text:
Q: 3 way Boolean value with Java I have 3 conditions based on my Boolean values.
Condition 1: When the value is false, the user should get a blank form
 with a submit button
Condition 2: When the user submits the form, the Boolean value is set
 to true and the form becomes a read only form, so that the user cannot
 edit the form and resubmit. At this point of time, the submit button
 is hidden.
Condition 3: Suppose it is absolutely necessary to make an update, the
 owner of the application can go to the database and change the value of Boolean bit  to false, so that the form becomes editable. But at this point of
 time, I need the Submit button to change to Modify button.
So there are 3 possibilities here with only 2 Boolean values. So my question is, how can I know between the two false calls (Condition 1 and Condition 3) that which one is Submit call i.e the user is filling the form for the first time and which one is Modify call i.e user is updating the same form? Any help is appreciated. Thank you.

A: You need Enum https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
.
Please have a look

A: You can use integer instead of boolean with state of 1, 2 ,3 and store this. or you can add another boolean for modifying state.
with switch case you can handle situations
switch(state){
    case 1:
    //your code for state one
    break;
    case 2:
    //your code for state one
    break;
    case 3:
    //your code for state one
    break;
}


text:
Q: How to parse child document Mongodb i get child document mongodb
android retriving data and read them
NodeJS+MongoDB
 [ { pinNumber: '4',
   nameDevice: 'den ngu',
   pintype: 0,
   deleted: '0',
   status: '0',
   laston: '31 thg 5, 2017 10:53:02' },
 { pinNumber: '9',
   nameDevice: 'quat ngu',
   pintype: 0,
   deleted: '0',
   status: '0',
   laston: '31 thg 5, 2017 10:54:14' },
 { pinNumber: '4',
   nameDevice: 'den',
   pintype: 0,
   deleted: '0',
   status: '0',
   space_id: '592cf576a53411474242b5fa',
   laston: '31 thg 5, 2017 11:45:31' } ] }

i can't parse them, help me!

A: Assuming you want to parse this json in java you can look at this :
How to parse JSON in Java

import org.json.*;
JSONObject data = new JSONObject("you json here");
for(int i=0 ;i < data.length() ; i++){
String pinNumber = data.getJSONObject(i).getString("pinNumber");
}

Downloadable jar: http://mvnrepository.com/artifact/org.json/json
You seem to have a extra '}' in the end in your json.


text:
Q: Java Runtime Environment getting "fatal error SIGSEGV" for program using JOGL I am trying to run a Java program through Eclipse. Whenever I try and run the thing, this is what I get:
Info: XInitThreads() called for concurrent Thread support
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x000010f1, pid=2750, tid=1923033968
#
# JRE version: 6.0_22-b04
# Java VM: Java HotSpot(TM) Server VM (17.1-b03 mixed mode linux-x86 )
# Problematic frame:
# C  0x000010f1
#
# An error report file with more information is saved as:
# /home/anjruu/ragamuffin/trunk/pipeline/hs_err_pid2750.log
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp

I am not getting any build errors, and have tried it using both the Java 6 OpenJDK, as well as Sun's jdk1.6.0_22, both behave the same. I am running an Ubuntu 10.10 system. The program uses JOGL (Java OpenGL), is that relevant?
The log file is about 400 lines long, so I figure that maybe posting the entire thing isn't so useful, and I'm not sure what sections would be, but if someone can let me know what I should include, I can do so.

A: This looks like a bug in some C code somewhere. Given that it happened on two different JVMs I'd tend to suspect native extensions, perhaps JOGL.
Have you checked the file the report points you too: hs_err_pid2750.log? Looking at that and then searching for some of those contents can often point you to others with the same problem and sometimes a fix.

A: If you are using JOGL on a Linux system then it is almost certain that the problem lies there. 3D graphics is not very robust on most Linux systems, and JOGL stresses 3D graphics systems a lot because it does unusual things with them, mostly to do with multithreading.
Most of the time the problem lies with out-of-date or non-conforming display drivers. Make sure your system has the latest drivers, and use the proprietary ones, not the ones that come with the installation and not any open source ones - sorry but this is one case where knowing the hardware backwards (like the graphics card providers do) really improves quality and performance. This will usually fix the problem.
If that doesn't help you are going to have to do something drastic. Often disabling hardware graphics acceleration will fix it, but with loss of performance of course. The log file should give you the full stack trace, which may be useful if you are comfortable with device driver coding and have the source of the drivers. Alternatively try using a different graphics card - new ones are cheap if you haven't upgraded yours recently.
I spent months of my life trying to track down bugs like this on a JOGL app running on Linux in the general case, and I still found installations where the window would draw blank. Good luck.

A: As other posters have said, HotSpot errors in JOGL programs can often be fixed by updating your graphics card drivers to the latest version.
However, if you're using the new JOGL 2.0 beta, the problem might be that you're either not calling GLProfile.initSingleton(), or you're not calling it early enough (it has to be before any X Windows calls).
I've got a tutorial at http://wadeawalker.wordpress.com/2010/10/09/tutorial-a-cross-platform-workbench-program-using-java-opengl-and-eclipse/ that shows how to create a simple JOGL 2.0 program. I've tested this program on CentOS 5.4 and it works correctly. Back before I had GLProfile.initSingleton() in the right place in this tutorial, I saw the same SIGSEGV error as you.


text:
Q: Is SSL certificate needed for Google and Facebook OAuth2 provider in ASP.NET MVC I read a tutorial how to add support for Google and Facebook OAuth2 provider. One step in this tutorial is setting up SSL in the project. I don't have SSL certificate on my hosting. It is still possible to implement these providers without SSL certificate? I don't want any security warnings on my site.

A: No, you don't need SSL in your application in order to connect with third party OAuth providers. Of course you will be exposing the security of your authentication cookies because they will be sent as cleartext on each request.
So even if this is not a requirement, it is strongly recommended.


text:
Q: seperate DB for each laravel/homestead project I've come across so many posts about this problem but albeit am following all the solutions its still not working for me
this is my homestead.ymal
sites:
    - map: homestead.com
      to: /home/nanashi/public
    - map: boomer.com
      to: /home/boomer/public

databases:
    - homestead
    - boomer

my .env file
DB_CONNECTION=mysql
DB_HOST=192.168.10.10
DB_PORT=33060
DB_DATABASE=boomer
DB_USERNAME=root
DB_PASSWORD=

I have several migration and while I try to run it from the vagrant machine itself(after SSHing into it), it gives me an error of table already exists
I want to connect to boomer DB (which is empty) and make migration there but the VM still connects to the DB names homestead(for another project)
I tried to provision the VM but still, nothing happens
I've also changed the port to 3306*0*

A: Your .env should look like this:
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=boomer
DB_USERNAME=homestead
DB_PASSWORD=secret

To run your artisan commands, you should first log into your vagrant machine with:
vagrant ssh

-> then go in to the project folder and then run your migration commands there
php artisan migrate

A: 1-create the project on your physical machine
2-I pushed the project to github
3- i ssh into the VM, and created the DB from there.
4- changed the DB engine to InnoDB
5- git clone my project from github
6- i ran the migrations
I know my solution is not ideal, but these are the steps i followed to solve my problem for anyone out there got stuck on the same issue


text:
Q: accord / concord usage What difference of sense would you hear in the following between "accord" and "concord":
"…all of whom remain within the enviable sphere of domestic accord/concord."
The OED is inconclusive, if not tautological, the first entry under "concord, n." making use of "accord:"
"1. Agreement between persons; concurrence in feeling and opinion; harmony, accord."

A: In some ways, the two words mean the same thing in your example. It tells me that people are in agreement and everyone is "playing according to the rules".
However, concord means more than just agreement — it's a harmonious agreement. People aren't just following the rules, they're getting along with each other in a pleasant way.

A: From: http://the-difference-between.com/accord/concord
"As nouns the difference between concord and accord is that concord is a state of agreement; harmony; union [or concord can be a variety of American grape, with large dark blue (almost black) grapes in compact clusters]; while accord is agreement or concurrence of opinion, will, or action.
While the references I checked support the use of "concord" in your example, it is a word I encounter in everyday writing or speech far less often than "accord." While unlikely to be confused in the example phrase as "…all of whom remain within the enviable sphere of [a] domestic grape," the use of "accord" is far more common, if less precise, and the frequency of use for "accord" has exceeded that for "concord" consistently according to Google Books Ngram Viewer.
(I don't know how to paste in the chart showing the use of the two words from 1700 to 2008, but here is the link: http://tinyurl.com/accord-vs-concord )


text:
Q: Google Script urlFetchApp Post failing calling Jira Tempo worklogs I trying to write a google script to query Jira Tempo worklogs.
This is what I have so far:
function postDataForAPI() {

  var payloadData = {
    "taskKey" :   []
  };
  payloadData.taskKey.push("AA-123");

  var payload = Utilities.jsonStringify(payloadData);

  var url = "https://api.tempo.io/core/4/worklogs/search";
  var digestfull = PropertiesService.getUserProperties().getProperty("digest"); //get username and password (base64 encrypted)

  var options = { "Accept":"application/json",
              "Content-Type":"application/json",
              "method": "POST",
              "headers": {"Authorization": digestfull},
              "muteHttpExceptions": true,
              "payload" : payload
             };

  var resp = UrlFetchApp.fetch(url,options);
  if (resp.getResponseCode() != 200) {
    Browser.msgBox("Error retrieving data for url " + url + ":" + resp.getContentText());
    return "";
  }
  else {
    return resp.getContentText();
  }

}

When I execute the above it fails.
If I use curl then I can successfully make the request (I think this is essentially the same POST):
curl -u "username:password"  -X POST https://api.tempo.io/rest/tempo-timesheets/4/worklogs/search -H 'Content-Type: application/json' -d '{"taskKey":["AA-123"]}'

Making GET requests against the same API works fine:
function getDataForAPI() {

  var url = "https://api.tempo.io/core/4/worklogs/101112";
  var digestfull = PropertiesService.getUserProperties().getProperty("digest"); //get username and password (base64 encrypted)

  var options = { "Accept":"application/json",
              "Content-Type":"application/json",
              "method": "GET",
              "headers": {"Authorization": digestfull},
              "muteHttpExceptions": true
             };

  var resp = UrlFetchApp.fetch(url,options);
  if (resp.getResponseCode() != 200) {
    Browser.msgBox("Error retrieving data for url " + url + ":" + resp.getContentText());
    return "";
  }
  else {
    return resp.getContentText();
  }

}

So I'm confident it is not Authorisation (GET request succeeds). The curl request succeeds and appears to be in the same form as the google script and yet the google script POST fails.
What do I have wrong?

A: I believe your goal is as follows.

*

*You want to convert the following curl command to Google Apps Script.
  curl -u "username:password"  -X POST https://api.tempo.io/rest/tempo-timesheets/4/worklogs/search -H 'Content-Type: application/json' -d '{"taskKey":["AA-123"]}'

Modification points:

*

*It seems that "Accept":"application/json" is not used in the sample curl command.

*"Content-Type":"application/json" is required to be included in the request header. But, at UrlFetchApp, the property of contentType can be used.

*Utilities.jsonStringify has been deprecated. Ref
When these points are reflected in your script, it becomes as follows.
Modified script:
function postDataForAPI() {
  var payloadData = { "taskKey": [] };
  payloadData.taskKey.push("AA-123");
  var url = "https://api.tempo.io/core/4/worklogs/search";
  var digestfull = PropertiesService.getUserProperties().getProperty("digest");
  var options = {
    "method": "POST",
    "contentType": "application/json",
    "headers": { "Authorization": digestfull },
    "muteHttpExceptions": true,
    "payload": JSON.stringify(payloadData)
  };
  var resp = UrlFetchApp.fetch(url, options);
  if (resp.getResponseCode() != 200) {
    Browser.msgBox("Error retrieving data for url " + url + ":" + resp.getContentText());
    return "";
  }
  else {
    return resp.getContentText();
  }
}

Note:

*

*When I saw your provided curl command, it seems that the URL is different. The sample curl command uses https://api.tempo.io/rest/tempo-timesheets/4/worklogs/search. But your script uses https://api.tempo.io/core/4/worklogs/search. I'm worried about this difference. So if the above-modified script didn't work, please check the URL again.

*The request of this modified script is the same as the sample curl command. But if an error occurs, please check each value like digestfull and payloadData, again.
Reference:

*

*fetch(url, params)


text:
Q: Android - Perform an action with voice command Searched through the internet and couldn't find a god example of achieving the following. There is a Launcher activity. User will be navigated to the launcher activity first and inside that activity , when the user says a certain word like "Start" or something like that the app should navigate the user to another activity. I've gone through a set of tutorials , and I've seen some similar questions at SO but none of them make sense to me. What will be the best approach to achieve this ?

A: Basically what you have to do is

*

*build a framework/module to handle Speech Input (speech-2-text)

*

*Depending on Input by user, perform an action


text:
Q: Validating a ListBoxItem rather than a ListBox I have a ListBox bound to a list of objects that implement IDataErrorInfo. I have set the ValidatesOnDataErrors property to True on my ListBox. If I select an invalid item, a red border appears around my ListBox. How can I modify my ItemContainerStyle such that the red border appears arround the selected item rather than the actual ListBox?

A: You can set ValidatesOnDataErrors in the ListBox's ItemTemplate directly, on the Binding which binds the bound item's property to the control that displays it. That should make the red border show up around the control in question. If, in addition to that, the border still shows up on the ListBox as a whole, you can set Validation.ErrorTemplate="{x:Null}" on the ListBox.
If you don't want the border to show around one control in the ItemTemplate, but around the whole Item, you could try setting the Listboxes ItemBindingGroup.


text:
Q: Rendering HTML inside double curly braces I am using a pipe in an Ionic/Angular app that is transforming a text and returning a result with an html code.
This an example of how I am using my pipe:
<ion-label>
  {{ text | mypipe: 'lo':'secondary' }}
</ion-label>

The resulting HTML of the code within the double curls is as follows:
Loth<ion-text color='secondary'>lo</ion-text>rien

The problem is that upon execution, all I am seeing in my label is Loth<ion-text color='secondary'>lo</ion-text>rien instead of Lothlorien with the colored portion of the text (i.e: 'lo')
Any idea why I am having this behavior and how to fix it?
Thanks

A: TLDR:
When you want to render html which contains angular components you have to create/compile them dynamically in runtime.
Angular by default sanitizes anything that goes into the view. To display html in your template you have to use:

Your pipe should return SafeHtml:
@Pipe({
    name: 'mypipe'
})
export class MyPipe implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) {}

    public transform(value, params): SafeHtml {
        //do whatever your pipe does and then
        return this.sanitizer.bypassSecurityTrustHtml(somethingToReturn);
    }
}

See this question.
You can also write a generic pipe, like in this article and then just use it:

But since your markup contains another angular component, it wont work. It would work with standard html markup.
You want to look for a way how to not only render some html but to compile your template dynamically and create the resulting component dynamically. Something along these lines.


text:
Q: I have a method which only needs to be executed once in PHP but will be called twice. How do I structure this? I have a method in PHP which calls a SOAP service, parses some data and returns it.
It will return the same data - it asks how many records in a data object.
I need to call it twice with a pass.
My question is, what is best practice for structuring this in PHP? I've tried to see if the function has been called already.Do I use static variables / functions?
function MinimumRequired() {
        return $this->NumberPeopleJoined();
    }

function NumberPeopleJoined () {
        if (isset($NumberPeople)) {
            Debug::Show($NumberPeople);
        }
        static $NumberPeople;
        $NumberPeople = Surge_Controller::NumberPeopleJoined();
        return $NumberPeople;
    }

Thanks!

A: Just create a local class member, and check if that has a value. If not, set the value to whatever is retrieved from Surge_Controller, and if it was already set, just return the value:
<?php

class Surge_Controller {
    static public function NumberPeopleJoined() {
        echo "Surge_Controller::NumberPeopleJoined() got called.\n";
        return 2;
    }
}

class Foo {
    protected $cacheNumberPeople;

    function MinimumRequired() {
        return $this->NumberPeopleJoined();
    }

    function NumberPeopleJoined () {
        if( !isset( $this->cacheNumberPeople ) ) {
            $this->cacheNumberPeople = Surge_Controller::NumberPeopleJoined();
        }
        return $this->cacheNumberPeople;
    }
}

$foo = new Foo( );
echo $foo->numberPeopleJoined( ) . "\n";
echo $foo->numberPeopleJoined( ) . "\n";

Output:
$ php foo.php
Surge_Controller::NumberPeopleJoined() got called.
2
2

A: The simple way is to have a global variable, and check if is "true", and set it to true at the end of your function. The value can be cached too...
But if you want to make your code fun, you can use underscore:
http://brianhaveri.github.com/Underscore.php/#once
http://brianhaveri.github.com/Underscore.php/#memoize


text:
Q: Problems with memory allocation #include <stdio.h>
#include <stdlib.h>
int main ()
{
    char *buffer=malloc(1);
    char *temporary=malloc(1);
    int length=0;
    signed int character;
    for(length=0;(character = getchar())!=EOF;length++)
    {
        buffer[length]=character;
        if((length==0) || ((length%1000)==0))
        {
            temporary=realloc(buffer,length+1001);
            if(temporary!=NULL)
            {
                buffer= temporary;
            }
            else
            {
                printf("Error: Out of memory!\n");
                free(temporary);
                free(buffer);
                return 1;
            }
        }
    }
    buffer[length]='\0';
    length-=1;
    while(length>=0)
    {
        printf("%c",buffer[length]);
        length--;
    }
    printf("\n");
    free(buffer);
    //////////////free(temporary); //( HERE)
    return 0;
}

My program should read a string or a input textfile, store it, and then print it out backwards which is working. I just don't understand why I can't free the temporary value at end.  It's failing with a double free error.
I would like to know why I cant put a free(temporary) where I wrote "here".
If you want to point out another problem in my code i'm happy to learn something.

A: When this code executes the line
buffer = temporary;

two things happen.  First, the memory that buffer was holding is "leaked"; you no longer have that address to pass to free().  Second, buffer and temporary now both point to a single piece of memory allocated by malloc() or by realloc().  Thus, when you call free() on either buffer or temporary, you have freed that chunk of memory; to call free() again would be a double free error.
I suggest something like this:
if (length >= buffer_size)
{
    const size_t new_size = buffer_size + 1000;
    char *temp = realloc(buffer, new_size);
    if (!temp)
    {
        free(buffer);
        /* handle the error in some way */
    }
    buffer = temp;
    buffer_size = new_size;
}

Also, it is best practice to actually check for errors.  malloc() and realloc() can fail.
Also, there isn't much point in allocating a single byte of memory for each buffer.  You might as well start out by allocating 1000 bytes or whatever.
Also, the way you check to see if the buffer needs realloc() seems needlessly tricky.  I would suggest keeping a variable that tracks how long the buffer is, and call realloc() when the buffer is not long enough, and then store into the buffer after the realloc().
EDIT: I think you got a bit confused about temporary.  Look at the code I put and you will see that I put the temp variable inside the block of code of the if statement.  It's more obvious how long temp will hold a useful value (not very long).  Declaring temporary at the outer scope, and also calling malloc() to put a byte into it, is just confusing.


text:
Q: WooCommerce - Modify meta key when adding to cart I have a WooCommerce product that has a meta key of custom_length that is set with a value of 100
I want to be able to modify this value when the item is added to the cart. So the product itself in WooCommerce would still have the value of 100 set, but the product in the cart would have something else, like 135
I am  looking for a hook or filter that will let me do this modification, would the add_to_cart be the correct action to be focusing on?

A: Not sure what you want to do, but seems like you are looking for woocommerce_add_to_cart_validation filter. It will run after you click add-to-cart button and before products being added to cart.
Here is a quick example with it's accepted variables:
function my_awesome_validate_add_to_cart ( $passed, $product_id, $quantity, $variation_id, $variations ) {
    if ( something ){
        //do something
    }
    return $passed;//$passed is boolean. Make sure to return this. TRUE will successfully add product to cart, and FALSE will return error.

}
add_filter( 'woocommerce_add_to_cart_validation', 'my_awesome_validate_add_to_cart ', 10, 5 );


text:
Q: Why can't I add an attribute to a datastore object (dynamically) and store it in session? I am not able to retrieve attributes in session that have been added dynamically to a datastore object. Here's a (simplified) example... To save time on suggestions, I do not want to actually hard code the attribute to the datastore object.
Class User(ndb.Model):
   email = ndb.String...

// I use a handler to get the user object from the datastore
// and store the object in session
user = function_to_get_user_by_key(key)

// Add an temporary attribute
user.temp_var = 'test'

// Store in session
self.session['user'] = user

// Get the user in the same script to test the attribute
user = self.session.get('user')

print user.temp_var // Works - I see the result

// Redirect to a new script (By the way, assume these scripts are in separate methods       within a handler class)

user = self.session.get('user')
print user.temp_var // Gives an attribute error - basically saying the class does not have this attribute

Any idea as to why this happens?

A: When you redirect to a new script, I assume it's with another HTTP request?
On a new request you're going to be using a new instance of the session object.  Between your requests, your session would have been serialized and saved to memcache or the datastore.  On your new request, you would have deserialized your session.
You might want to check how the serialization went and why your user object wasn't serialized as you expected.  Most likely the User class has its own serialization code based off the Kind attributes, and temp_var may be ignored by the serialization since it's not part of the class.
You might also put temp_var directly in the session, in which case it should serialize properly.


text:
Q: Modelling recurrent items (expenses) as records with Rails I am writing what could be defined as an accountancy/invoicing app using Rails 5. I am in need of implementing a section that predicts the company's cashflow in the future. So far I've got the following:

*

*Actual bank movements and balances (in the past), imported from the bank

*Future invoices (income) which are expected to be paid on a certain date

*Future one-time expenses which are expected to be paid on a certain date

Using these three sets of data, I can calculate, for any given date in the future, the sum of: the last known bank balance, plus all the future invoices values coming IN, minus all the future expenses going OUT, so I get, theoretically, the expected balance of the company for any given date.
My doubt arises when it comes to recurrent expenses (or potentially incomes). Given that all of the items I mentioned before (bank movements, invoices and expenses) are actual ActiveRecord records stored in my database, I'm not sure about how to treat the recurrent expenses, for example:
Let's imagine I want to enter a known future recurrent paycheck of a certain employee, which is $2000 every first day of the month.
1- Should I generate at some point the next X entries and treat them as normal future expenses (each with its own ID, date and amount)?
2- The other option I've thought of is having some kind of "declaration" on the nature of the recurrent expense, as in "it's $2000 every day 1 of month until -forever-", similarly to a cronjob. But, if I were to take this approach, I'd like to have an ActiveRecord - similar interface, so that I can do something like:
cashflow = []
last_movement = BankMovement.last
value = last_movement.balance
(last_movement.date..(last_movement.date + 12.months)).each do |day|
  value += Invoice.pending.expected_on(day).sum(:gross_amount)
  value -= Expense.pending.expected_on(day).sum(:gross_amount)
  value -= RecurringExpense.expected_on(day).sum(:gross_amount)
  cashflow.push( { date: day, balance: value } )
end

This feels almost right but, I'm not sure about how to link the actual expense when it comes with the recurrent/calculated one. How can I then change the date if the expense gets paid the day after it was supposed? I need to have an actual record of each one of those, at least whenever they are "consolidated".
I'm not really sure if I was clear enough with my trouble here, so, should anyone want and have some spare time to help me out, please feel free to ask for any extra relevant info, I'd really appreciate some help, especially if we can find a way of doing this "the Rails way"!